text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```javascript /*! * Vue.js v1.0.24 * (c) 2016 Evan You */ 'use strict'; function set(obj, key, val) { if (hasOwn(obj, key)) { obj[key] = val; return; } if (obj._isVue) { set(obj._data, key, val); return; } var ob = obj.__ob__; if (!ob) { obj[key] = val; return; } ob.convert(key, val); ob.dep.notify(); if (ob.vms) { var i = ob.vms.length; while (i--) { var vm = ob.vms[i]; vm._proxy(key); vm._digest(); } } return val; } /** * Delete a property and trigger change if necessary. * * @param {Object} obj * @param {String} key */ function del(obj, key) { if (!hasOwn(obj, key)) { return; } delete obj[key]; var ob = obj.__ob__; if (!ob) { if (obj._isVue) { delete obj._data[key]; obj._digest(); } return; } ob.dep.notify(); if (ob.vms) { var i = ob.vms.length; while (i--) { var vm = ob.vms[i]; vm._unproxy(key); vm._digest(); } } } var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Check whether the object has the property. * * @param {Object} obj * @param {String} key * @return {Boolean} */ function hasOwn(obj, key) { return hasOwnProperty.call(obj, key); } /** * Check if an expression is a literal value. * * @param {String} exp * @return {Boolean} */ var literalValueRE = /^\s?(true|false|-?[\d\.]+|'[^']*'|"[^"]*")\s?$/; function isLiteral(exp) { return literalValueRE.test(exp); } /** * Check if a string starts with $ or _ * * @param {String} str * @return {Boolean} */ function isReserved(str) { var c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F; } /** * Guard text output, make sure undefined outputs * empty string * * @param {*} value * @return {String} */ function _toString(value) { return value == null ? '' : value.toString(); } /** * Check and convert possible numeric strings to numbers * before setting back to data * * @param {*} value * @return {*|Number} */ function toNumber(value) { if (typeof value !== 'string') { return value; } else { var parsed = Number(value); return isNaN(parsed) ? value : parsed; } } /** * Convert string boolean literals into real booleans. * * @param {*} value * @return {*|Boolean} */ function toBoolean(value) { return value === 'true' ? true : value === 'false' ? false : value; } /** * Strip quotes from a string * * @param {String} str * @return {String | false} */ function stripQuotes(str) { var a = str.charCodeAt(0); var b = str.charCodeAt(str.length - 1); return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str; } /** * Camelize a hyphen-delmited string. * * @param {String} str * @return {String} */ var camelizeRE = /-(\w)/g; function camelize(str) { return str.replace(camelizeRE, toUpper); } function toUpper(_, c) { return c ? c.toUpperCase() : ''; } /** * Hyphenate a camelCase string. * * @param {String} str * @return {String} */ var hyphenateRE = /([a-z\d])([A-Z])/g; function hyphenate(str) { return str.replace(hyphenateRE, '$1-$2').toLowerCase(); } /** * Converts hyphen/underscore/slash delimitered names into * camelized classNames. * * e.g. my-component => MyComponent * some_else => SomeElse * some/comp => SomeComp * * @param {String} str * @return {String} */ var classifyRE = /(?:^|[-_\/])(\w)/g; function classify(str) { return str.replace(classifyRE, toUpper); } /** * Simple bind, faster than native * * @param {Function} fn * @param {Object} ctx * @return {Function} */ function bind(fn, ctx) { return function (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx); }; } /** * Convert an Array-like object to a real Array. * * @param {Array-like} list * @param {Number} [start] - start index * @return {Array} */ function toArray(list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret; } /** * Mix properties into target object. * * @param {Object} to * @param {Object} from */ function extend(to, from) { var keys = Object.keys(from); var i = keys.length; while (i--) { to[keys[i]] = from[keys[i]]; } return to; } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. * * @param {*} obj * @return {Boolean} */ function isObject(obj) { return obj !== null && typeof obj === 'object'; } /** * Strict object type check. Only returns true * for plain JavaScript objects. * * @param {*} obj * @return {Boolean} */ var toString = Object.prototype.toString; var OBJECT_STRING = '[object Object]'; function isPlainObject(obj) { return toString.call(obj) === OBJECT_STRING; } /** * Array type check. * * @param {*} obj * @return {Boolean} */ var isArray = Array.isArray; /** * Define a property. * * @param {Object} obj * @param {String} key * @param {*} val * @param {Boolean} [enumerable] */ function def(obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Debounce a function so it only gets called after the * input stops arriving after the given wait period. * * @param {Function} func * @param {Number} wait * @return {Function} - the debounced function */ function _debounce(func, wait) { var timeout, args, context, timestamp, result; var later = function later() { var last = Date.now() - timestamp; if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; } }; return function () { context = this; args = arguments; timestamp = Date.now(); if (!timeout) { timeout = setTimeout(later, wait); } return result; }; } /** * Manual indexOf because it's slightly faster than * native. * * @param {Array} arr * @param {*} obj */ function indexOf(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) return i; } return -1; } /** * Make a cancellable version of an async callback. * * @param {Function} fn * @return {Function} */ function cancellable(fn) { var cb = function cb() { if (!cb.cancelled) { return fn.apply(this, arguments); } }; cb.cancel = function () { cb.cancelled = true; }; return cb; } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? * * @param {*} a * @param {*} b * @return {Boolean} */ function looseEqual(a, b) { /* eslint-disable eqeqeq */ return a == b || (isObject(a) && isObject(b) ? JSON.stringify(a) === JSON.stringify(b) : false); /* eslint-enable eqeqeq */ } var hasProto = ('__proto__' in {}); // Browser environment sniffing var inBrowser = typeof window !== 'undefined' && Object.prototype.toString.call(window) !== '[object Object]'; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; // UA sniffing for working around browser-specific quirks var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isAndroid = UA && UA.indexOf('android') > 0; var isIos = UA && /(iphone|ipad|ipod|ios)/i.test(UA); var isWechat = UA && UA.indexOf('micromessenger') > 0; var transitionProp = undefined; var transitionEndEvent = undefined; var animationProp = undefined; var animationEndEvent = undefined; // Transition property/event sniffing if (inBrowser && !isIE9) { var isWebkitTrans = window.ontransitionend === undefined && window.onwebkittransitionend !== undefined; var isWebkitAnim = window.onanimationend === undefined && window.onwebkitanimationend !== undefined; transitionProp = isWebkitTrans ? 'WebkitTransition' : 'transition'; transitionEndEvent = isWebkitTrans ? 'webkitTransitionEnd' : 'transitionend'; animationProp = isWebkitAnim ? 'WebkitAnimation' : 'animation'; animationEndEvent = isWebkitAnim ? 'webkitAnimationEnd' : 'animationend'; } /** * Defer a task to execute it asynchronously. Ideally this * should be executed as a microtask, so we leverage * MutationObserver if it's available, and fallback to * setTimeout(0). * * @param {Function} cb * @param {Object} ctx */ var nextTick = (function () { var callbacks = []; var pending = false; var timerFunc; function nextTickHandler() { pending = false; var copies = callbacks.slice(0); callbacks = []; for (var i = 0; i < copies.length; i++) { copies[i](); } } /* istanbul ignore if */ if (typeof MutationObserver !== 'undefined' && !(isWechat && isIos)) { var counter = 1; var observer = new MutationObserver(nextTickHandler); var textNode = document.createTextNode(counter); observer.observe(textNode, { characterData: true }); timerFunc = function () { counter = (counter + 1) % 2; textNode.data = counter; }; } else { // webpack attempts to inject a shim for setImmediate // if it is used as a global, so we have to work around that to // avoid bundling unnecessary code. var context = inBrowser ? window : typeof global !== 'undefined' ? global : {}; timerFunc = context.setImmediate || setTimeout; } return function (cb, ctx) { var func = ctx ? function () { cb.call(ctx); } : cb; callbacks.push(func); if (pending) return; pending = true; timerFunc(nextTickHandler, 0); }; })(); var _Set = undefined; /* istanbul ignore if */ if (typeof Set !== 'undefined' && Set.toString().match(/native code/)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = function () { this.set = Object.create(null); }; _Set.prototype.has = function (key) { return this.set[key] !== undefined; }; _Set.prototype.add = function (key) { this.set[key] = 1; }; _Set.prototype.clear = function () { this.set = Object.create(null); }; } function Cache(limit) { this.size = 0; this.limit = limit; this.head = this.tail = undefined; this._keymap = Object.create(null); } var p = Cache.prototype; /** * Put <value> into the cache associated with <key>. * Returns the entry which was removed to make room for * the new entry. Otherwise undefined is returned. * (i.e. if there was enough room already). * * @param {String} key * @param {*} value * @return {Entry|undefined} */ p.put = function (key, value) { var removed; if (this.size === this.limit) { removed = this.shift(); } var entry = this.get(key, true); if (!entry) { entry = { key: key }; this._keymap[key] = entry; if (this.tail) { this.tail.newer = entry; entry.older = this.tail; } else { this.head = entry; } this.tail = entry; this.size++; } entry.value = value; return removed; }; /** * Purge the least recently used (oldest) entry from the * cache. Returns the removed entry or undefined if the * cache was empty. */ p.shift = function () { var entry = this.head; if (entry) { this.head = this.head.newer; this.head.older = undefined; entry.newer = entry.older = undefined; this._keymap[entry.key] = undefined; this.size--; } return entry; }; /** * Get and register recent use of <key>. Returns the value * associated with <key> or undefined if not in cache. * * @param {String} key * @param {Boolean} returnEntry * @return {Entry|*} */ p.get = function (key, returnEntry) { var entry = this._keymap[key]; if (entry === undefined) return; if (entry === this.tail) { return returnEntry ? entry : entry.value; } // HEAD--------------TAIL // <.older .newer> // <--- add direction -- // A B C <D> E if (entry.newer) { if (entry === this.head) { this.head = entry.newer; } entry.newer.older = entry.older; // C <-- E. } if (entry.older) { entry.older.newer = entry.newer; // C. --> E } entry.newer = undefined; // D --x entry.older = this.tail; // D. --> E if (this.tail) { this.tail.newer = entry; // E. <-- D } this.tail = entry; return returnEntry ? entry : entry.value; }; var cache$1 = new Cache(1000); var filterTokenRE = /[^\s'"]+|'[^']*'|"[^"]*"/g; var reservedArgRE = /^in$|^-?\d+/; /** * Parser state */ var str; var dir; var c; var prev; var i; var l; var lastFilterIndex; var inSingle; var inDouble; var curly; var square; var paren; /** * Push a filter to the current directive object */ function pushFilter() { var exp = str.slice(lastFilterIndex, i).trim(); var filter; if (exp) { filter = {}; var tokens = exp.match(filterTokenRE); filter.name = tokens[0]; if (tokens.length > 1) { filter.args = tokens.slice(1).map(processFilterArg); } } if (filter) { (dir.filters = dir.filters || []).push(filter); } lastFilterIndex = i + 1; } /** * Check if an argument is dynamic and strip quotes. * * @param {String} arg * @return {Object} */ function processFilterArg(arg) { if (reservedArgRE.test(arg)) { return { value: toNumber(arg), dynamic: false }; } else { var stripped = stripQuotes(arg); var dynamic = stripped === arg; return { value: dynamic ? arg : stripped, dynamic: dynamic }; } } /** * Parse a directive value and extract the expression * and its filters into a descriptor. * * Example: * * "a + 1 | uppercase" will yield: * { * expression: 'a + 1', * filters: [ * { name: 'uppercase', args: null } * ] * } * * @param {String} s * @return {Object} */ function parseDirective(s) { var hit = cache$1.get(s); if (hit) { return hit; } // reset parser state str = s; inSingle = inDouble = false; curly = square = paren = 0; lastFilterIndex = 0; dir = {}; for (i = 0, l = str.length; i < l; i++) { prev = c; c = str.charCodeAt(i); if (inSingle) { // check single quote if (c === 0x27 && prev !== 0x5C) inSingle = !inSingle; } else if (inDouble) { // check double quote if (c === 0x22 && prev !== 0x5C) inDouble = !inDouble; } else if (c === 0x7C && // pipe str.charCodeAt(i + 1) !== 0x7C && str.charCodeAt(i - 1) !== 0x7C) { if (dir.expression == null) { // first filter, end of expression lastFilterIndex = i + 1; dir.expression = str.slice(0, i).trim(); } else { // already has filter pushFilter(); } } else { switch (c) { case 0x22: inDouble = true;break; // " case 0x27: inSingle = true;break; // ' case 0x28: paren++;break; // ( case 0x29: paren--;break; // ) case 0x5B: square++;break; // [ case 0x5D: square--;break; // ] case 0x7B: curly++;break; // { case 0x7D: curly--;break; // } } } } if (dir.expression == null) { dir.expression = str.slice(0, i).trim(); } else if (lastFilterIndex !== 0) { pushFilter(); } cache$1.put(s, dir); return dir; } var directive = Object.freeze({ parseDirective: parseDirective }); var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g; var cache = undefined; var tagRE = undefined; var htmlRE = undefined; /** * Escape a string so it can be used in a RegExp * constructor. * * @param {String} str */ function escapeRegex(str) { return str.replace(regexEscapeRE, '\\$&'); } function compileRegex() { var open = escapeRegex(config.delimiters[0]); var close = escapeRegex(config.delimiters[1]); var unsafeOpen = escapeRegex(config.unsafeDelimiters[0]); var unsafeClose = escapeRegex(config.unsafeDelimiters[1]); tagRE = new RegExp(unsafeOpen + '((?:.|\\n)+?)' + unsafeClose + '|' + open + '((?:.|\\n)+?)' + close, 'g'); htmlRE = new RegExp('^' + unsafeOpen + '.*' + unsafeClose + '$'); // reset cache cache = new Cache(1000); } /** * Parse a template text string into an array of tokens. * * @param {String} text * @return {Array<Object> | null} * - {String} type * - {String} value * - {Boolean} [html] * - {Boolean} [oneTime] */ function parseText(text) { if (!cache) { compileRegex(); } var hit = cache.get(text); if (hit) { return hit; } if (!tagRE.test(text)) { return null; } var tokens = []; var lastIndex = tagRE.lastIndex = 0; var match, index, html, value, first, oneTime; /* eslint-disable no-cond-assign */ while (match = tagRE.exec(text)) { /* eslint-enable no-cond-assign */ index = match.index; // push text token if (index > lastIndex) { tokens.push({ value: text.slice(lastIndex, index) }); } // tag token html = htmlRE.test(match[0]); value = html ? match[1] : match[2]; first = value.charCodeAt(0); oneTime = first === 42; // * value = oneTime ? value.slice(1) : value; tokens.push({ tag: true, value: value.trim(), html: html, oneTime: oneTime }); lastIndex = index + match[0].length; } if (lastIndex < text.length) { tokens.push({ value: text.slice(lastIndex) }); } cache.put(text, tokens); return tokens; } /** * Format a list of tokens into an expression. * e.g. tokens parsed from 'a {{b}} c' can be serialized * into one single expression as '"a " + b + " c"'. * * @param {Array} tokens * @param {Vue} [vm] * @return {String} */ function tokensToExp(tokens, vm) { if (tokens.length > 1) { return tokens.map(function (token) { return formatToken(token, vm); }).join('+'); } else { return formatToken(tokens[0], vm, true); } } /** * Format a single token. * * @param {Object} token * @param {Vue} [vm] * @param {Boolean} [single] * @return {String} */ function formatToken(token, vm, single) { return token.tag ? token.oneTime && vm ? '"' + vm.$eval(token.value) + '"' : inlineFilters(token.value, single) : '"' + token.value + '"'; } /** * For an attribute with multiple interpolation tags, * e.g. attr="some-{{thing | filter}}", in order to combine * the whole thing into a single watchable expression, we * have to inline those filters. This function does exactly * that. This is a bit hacky but it avoids heavy changes * to directive parser and watcher mechanism. * * @param {String} exp * @param {Boolean} single * @return {String} */ var filterRE = /[^|]\|[^|]/; function inlineFilters(exp, single) { if (!filterRE.test(exp)) { return single ? exp : '(' + exp + ')'; } else { var dir = parseDirective(exp); if (!dir.filters) { return '(' + exp + ')'; } else { return 'this._applyFilters(' + dir.expression + // value ',null,' + // oldValue (null for read) JSON.stringify(dir.filters) + // filter descriptors ',false)'; // write? } } } var text = Object.freeze({ compileRegex: compileRegex, parseText: parseText, tokensToExp: tokensToExp }); var delimiters = ['{{', '}}']; var unsafeDelimiters = ['{{{', '}}}']; var config = Object.defineProperties({ /** * Whether to print debug messages. * Also enables stack trace for warnings. * * @type {Boolean} */ debug: false, /** * Whether to suppress warnings. * * @type {Boolean} */ silent: false, /** * Whether to use async rendering. */ async: true, /** * Whether to warn against errors caught when evaluating * expressions. */ warnExpressionErrors: true, /** * Whether to allow devtools inspection. * Disabled by default in production builds. */ devtools: process.env.NODE_ENV !== 'production', /** * Internal flag to indicate the delimiters have been * changed. * * @type {Boolean} */ _delimitersChanged: true, /** * List of asset types that a component can own. * * @type {Array} */ _assetTypes: ['component', 'directive', 'elementDirective', 'filter', 'transition', 'partial'], /** * prop binding modes */ _propBindingModes: { ONE_WAY: 0, TWO_WAY: 1, ONE_TIME: 2 }, /** * Max circular updates allowed in a batcher flush cycle. */ _maxUpdateCount: 100 }, { delimiters: { /** * Interpolation delimiters. Changing these would trigger * the text parser to re-compile the regular expressions. * * @type {Array<String>} */ get: function get() { return delimiters; }, set: function set(val) { delimiters = val; compileRegex(); }, configurable: true, enumerable: true }, unsafeDelimiters: { get: function get() { return unsafeDelimiters; }, set: function set(val) { unsafeDelimiters = val; compileRegex(); }, configurable: true, enumerable: true } }); var warn = undefined; var formatComponentName = undefined; if (process.env.NODE_ENV !== 'production') { (function () { var hasConsole = typeof console !== 'undefined'; warn = function (msg, vm) { if (hasConsole && !config.silent) { console.error('[Vue warn]: ' + msg + (vm ? formatComponentName(vm) : '')); } }; formatComponentName = function (vm) { var name = vm._isVue ? vm.$options.name : vm.name; return name ? ' (found in component: <' + hyphenate(name) + '>)' : ''; }; })(); } /** * Append with transition. * * @param {Element} el * @param {Element} target * @param {Vue} vm * @param {Function} [cb] */ function appendWithTransition(el, target, vm, cb) { applyTransition(el, 1, function () { target.appendChild(el); }, vm, cb); } /** * InsertBefore with transition. * * @param {Element} el * @param {Element} target * @param {Vue} vm * @param {Function} [cb] */ function beforeWithTransition(el, target, vm, cb) { applyTransition(el, 1, function () { before(el, target); }, vm, cb); } /** * Remove with transition. * * @param {Element} el * @param {Vue} vm * @param {Function} [cb] */ function removeWithTransition(el, vm, cb) { applyTransition(el, -1, function () { remove(el); }, vm, cb); } /** * Apply transitions with an operation callback. * * @param {Element} el * @param {Number} direction * 1: enter * -1: leave * @param {Function} op - the actual DOM operation * @param {Vue} vm * @param {Function} [cb] */ function applyTransition(el, direction, op, vm, cb) { var transition = el.__v_trans; if (!transition || // skip if there are no js hooks and CSS transition is // not supported !transition.hooks && !transitionEndEvent || // skip transitions for initial compile !vm._isCompiled || // if the vm is being manipulated by a parent directive // during the parent's compilation phase, skip the // animation. vm.$parent && !vm.$parent._isCompiled) { op(); if (cb) cb(); return; } var action = direction > 0 ? 'enter' : 'leave'; transition[action](op, cb); } var transition = Object.freeze({ appendWithTransition: appendWithTransition, beforeWithTransition: beforeWithTransition, removeWithTransition: removeWithTransition, applyTransition: applyTransition }); /** * Query an element selector if it's not an element already. * * @param {String|Element} el * @return {Element} */ function query(el) { if (typeof el === 'string') { var selector = el; el = document.querySelector(el); if (!el) { process.env.NODE_ENV !== 'production' && warn('Cannot find element: ' + selector); } } return el; } /** * Check if a node is in the document. * Note: document.documentElement.contains should work here * but always returns false for comment nodes in phantomjs, * making unit tests difficult. This is fixed by doing the * contains() check on the node's parentNode instead of * the node itself. * * @param {Node} node * @return {Boolean} */ function inDoc(node) { if (!node) return false; var doc = node.ownerDocument.documentElement; var parent = node.parentNode; return doc === node || doc === parent || !!(parent && parent.nodeType === 1 && doc.contains(parent)); } /** * Get and remove an attribute from a node. * * @param {Node} node * @param {String} _attr */ function getAttr(node, _attr) { var val = node.getAttribute(_attr); if (val !== null) { node.removeAttribute(_attr); } return val; } /** * Get an attribute with colon or v-bind: prefix. * * @param {Node} node * @param {String} name * @return {String|null} */ function getBindAttr(node, name) { var val = getAttr(node, ':' + name); if (val === null) { val = getAttr(node, 'v-bind:' + name); } return val; } /** * Check the presence of a bind attribute. * * @param {Node} node * @param {String} name * @return {Boolean} */ function hasBindAttr(node, name) { return node.hasAttribute(name) || node.hasAttribute(':' + name) || node.hasAttribute('v-bind:' + name); } /** * Insert el before target * * @param {Element} el * @param {Element} target */ function before(el, target) { target.parentNode.insertBefore(el, target); } /** * Insert el after target * * @param {Element} el * @param {Element} target */ function after(el, target) { if (target.nextSibling) { before(el, target.nextSibling); } else { target.parentNode.appendChild(el); } } /** * Remove el from DOM * * @param {Element} el */ function remove(el) { el.parentNode.removeChild(el); } /** * Prepend el to target * * @param {Element} el * @param {Element} target */ function prepend(el, target) { if (target.firstChild) { before(el, target.firstChild); } else { target.appendChild(el); } } /** * Replace target with el * * @param {Element} target * @param {Element} el */ function replace(target, el) { var parent = target.parentNode; if (parent) { parent.replaceChild(el, target); } } /** * Add event listener shorthand. * * @param {Element} el * @param {String} event * @param {Function} cb * @param {Boolean} [useCapture] */ function on(el, event, cb, useCapture) { el.addEventListener(event, cb, useCapture); } /** * Remove event listener shorthand. * * @param {Element} el * @param {String} event * @param {Function} cb */ function off(el, event, cb) { el.removeEventListener(event, cb); } /** * For IE9 compat: when both class and :class are present * getAttribute('class') returns wrong value... * * @param {Element} el * @return {String} */ function getClass(el) { var classname = el.className; if (typeof classname === 'object') { classname = classname.baseVal || ''; } return classname; } /** * In IE9, setAttribute('class') will result in empty class * if the element also has the :class attribute; However in * PhantomJS, setting `className` does not work on SVG elements... * So we have to do a conditional check here. * * @param {Element} el * @param {String} cls */ function setClass(el, cls) { /* istanbul ignore if */ if (isIE9 && !/svg$/.test(el.namespaceURI)) { el.className = cls; } else { el.setAttribute('class', cls); } } /** * Add class with compatibility for IE & SVG * * @param {Element} el * @param {String} cls */ function addClass(el, cls) { if (el.classList) { el.classList.add(cls); } else { var cur = ' ' + getClass(el) + ' '; if (cur.indexOf(' ' + cls + ' ') < 0) { setClass(el, (cur + cls).trim()); } } } /** * Remove class with compatibility for IE & SVG * * @param {Element} el * @param {String} cls */ function removeClass(el, cls) { if (el.classList) { el.classList.remove(cls); } else { var cur = ' ' + getClass(el) + ' '; var tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' '); } setClass(el, cur.trim()); } if (!el.className) { el.removeAttribute('class'); } } /** * Extract raw content inside an element into a temporary * container div * * @param {Element} el * @param {Boolean} asFragment * @return {Element|DocumentFragment} */ function extractContent(el, asFragment) { var child; var rawContent; /* istanbul ignore if */ if (isTemplate(el) && isFragment(el.content)) { el = el.content; } if (el.hasChildNodes()) { trimNode(el); rawContent = asFragment ? document.createDocumentFragment() : document.createElement('div'); /* eslint-disable no-cond-assign */ while (child = el.firstChild) { /* eslint-enable no-cond-assign */ rawContent.appendChild(child); } } return rawContent; } /** * Trim possible empty head/tail text and comment * nodes inside a parent. * * @param {Node} node */ function trimNode(node) { var child; /* eslint-disable no-sequences */ while ((child = node.firstChild, isTrimmable(child))) { node.removeChild(child); } while ((child = node.lastChild, isTrimmable(child))) { node.removeChild(child); } /* eslint-enable no-sequences */ } function isTrimmable(node) { return node && (node.nodeType === 3 && !node.data.trim() || node.nodeType === 8); } /** * Check if an element is a template tag. * Note if the template appears inside an SVG its tagName * will be in lowercase. * * @param {Element} el */ function isTemplate(el) { return el.tagName && el.tagName.toLowerCase() === 'template'; } /** * Create an "anchor" for performing dom insertion/removals. * This is used in a number of scenarios: * - fragment instance * - v-html * - v-if * - v-for * - component * * @param {String} content * @param {Boolean} persist - IE trashes empty textNodes on * cloneNode(true), so in certain * cases the anchor needs to be * non-empty to be persisted in * templates. * @return {Comment|Text} */ function createAnchor(content, persist) { var anchor = config.debug ? document.createComment(content) : document.createTextNode(persist ? ' ' : ''); anchor.__v_anchor = true; return anchor; } /** * Find a component ref attribute that starts with $. * * @param {Element} node * @return {String|undefined} */ var refRE = /^v-ref:/; function findRef(node) { if (node.hasAttributes()) { var attrs = node.attributes; for (var i = 0, l = attrs.length; i < l; i++) { var name = attrs[i].name; if (refRE.test(name)) { return camelize(name.replace(refRE, '')); } } } } /** * Map a function to a range of nodes . * * @param {Node} node * @param {Node} end * @param {Function} op */ function mapNodeRange(node, end, op) { var next; while (node !== end) { next = node.nextSibling; op(node); node = next; } op(end); } /** * Remove a range of nodes with transition, store * the nodes in a fragment with correct ordering, * and call callback when done. * * @param {Node} start * @param {Node} end * @param {Vue} vm * @param {DocumentFragment} frag * @param {Function} cb */ function removeNodeRange(start, end, vm, frag, cb) { var done = false; var removed = 0; var nodes = []; mapNodeRange(start, end, function (node) { if (node === end) done = true; nodes.push(node); removeWithTransition(node, vm, onRemoved); }); function onRemoved() { removed++; if (done && removed >= nodes.length) { for (var i = 0; i < nodes.length; i++) { frag.appendChild(nodes[i]); } cb && cb(); } } } /** * Check if a node is a DocumentFragment. * * @param {Node} node * @return {Boolean} */ function isFragment(node) { return node && node.nodeType === 11; } /** * Get outerHTML of elements, taking care * of SVG elements in IE as well. * * @param {Element} el * @return {String} */ function getOuterHTML(el) { if (el.outerHTML) { return el.outerHTML; } else { var container = document.createElement('div'); container.appendChild(el.cloneNode(true)); return container.innerHTML; } } var commonTagRE = /^(div|p|span|img|a|b|i|br|ul|ol|li|h1|h2|h3|h4|h5|h6|code|pre|table|th|td|tr|form|label|input|select|option|nav|article|section|header|footer)$/i; var reservedTagRE = /^(slot|partial|component)$/i; var isUnknownElement = undefined; if (process.env.NODE_ENV !== 'production') { isUnknownElement = function (el, tag) { if (tag.indexOf('-') > -1) { // path_to_url return el.constructor === window.HTMLUnknownElement || el.constructor === window.HTMLElement; } else { return (/HTMLUnknownElement/.test(el.toString()) && // Chrome returns unknown for several HTML5 elements. // path_to_url !/^(data|time|rtc|rb)$/.test(tag) ); } }; } /** * Check if an element is a component, if yes return its * component id. * * @param {Element} el * @param {Object} options * @return {Object|undefined} */ function checkComponentAttr(el, options) { var tag = el.tagName.toLowerCase(); var hasAttrs = el.hasAttributes(); if (!commonTagRE.test(tag) && !reservedTagRE.test(tag)) { if (resolveAsset(options, 'components', tag)) { return { id: tag }; } else { var is = hasAttrs && getIsBinding(el, options); if (is) { return is; } else if (process.env.NODE_ENV !== 'production') { var expectedTag = options._componentNameMap && options._componentNameMap[tag]; if (expectedTag) { warn('Unknown custom element: <' + tag + '> - ' + 'did you mean <' + expectedTag + '>? ' + 'HTML is case-insensitive, remember to use kebab-case in templates.'); } else if (isUnknownElement(el, tag)) { warn('Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.'); } } } } else if (hasAttrs) { return getIsBinding(el, options); } } /** * Get "is" binding from an element. * * @param {Element} el * @param {Object} options * @return {Object|undefined} */ function getIsBinding(el, options) { // dynamic syntax var exp = el.getAttribute('is'); if (exp != null) { if (resolveAsset(options, 'components', exp)) { el.removeAttribute('is'); return { id: exp }; } } else { exp = getBindAttr(el, 'is'); if (exp != null) { return { id: exp, dynamic: true }; } } } /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. * * All strategy functions follow the same signature: * * @param {*} parentVal * @param {*} childVal * @param {Vue} [vm] */ var strats = config.optionMergeStrategies = Object.create(null); /** * Helper that recursively merges two data objects together. */ function mergeData(to, from) { var key, toVal, fromVal; for (key in from) { toVal = to[key]; fromVal = from[key]; if (!hasOwn(to, key)) { set(to, key, fromVal); } else if (isObject(toVal) && isObject(fromVal)) { mergeData(toVal, fromVal); } } return to; } /** * Data */ strats.data = function (parentVal, childVal, vm) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal; } if (typeof childVal !== 'function') { process.env.NODE_ENV !== 'production' && warn('The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm); return parentVal; } if (!parentVal) { return childVal; } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn() { return mergeData(childVal.call(this), parentVal.call(this)); }; } else if (parentVal || childVal) { return function mergedInstanceDataFn() { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm) : childVal; var defaultData = typeof parentVal === 'function' ? parentVal.call(vm) : undefined; if (instanceData) { return mergeData(instanceData, defaultData); } else { return defaultData; } }; } }; /** * El */ strats.el = function (parentVal, childVal, vm) { if (!vm && childVal && typeof childVal !== 'function') { process.env.NODE_ENV !== 'production' && warn('The "el" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm); return; } var ret = childVal || parentVal; // invoke the element factory if this is instance merge return vm && typeof ret === 'function' ? ret.call(vm) : ret; }; /** * Hooks and param attributes are merged as arrays. */ strats.init = strats.created = strats.ready = strats.attached = strats.detached = strats.beforeCompile = strats.compiled = strats.beforeDestroy = strats.destroyed = strats.activate = function (parentVal, childVal) { return childVal ? parentVal ? parentVal.concat(childVal) : isArray(childVal) ? childVal : [childVal] : parentVal; }; /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets(parentVal, childVal) { var res = Object.create(parentVal || null); return childVal ? extend(res, guardArrayAssets(childVal)) : res; } config._assetTypes.forEach(function (type) { strats[type + 's'] = mergeAssets; }); /** * Events & Watchers. * * Events & watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = strats.events = function (parentVal, childVal) { if (!childVal) return parentVal; if (!parentVal) return childVal; var ret = {}; extend(ret, parentVal); for (var key in childVal) { var parent = ret[key]; var child = childVal[key]; if (parent && !isArray(parent)) { parent = [parent]; } ret[key] = parent ? parent.concat(child) : [child]; } return ret; }; /** * Other object hashes. */ strats.props = strats.methods = strats.computed = function (parentVal, childVal) { if (!childVal) return parentVal; if (!parentVal) return childVal; var ret = Object.create(null); extend(ret, parentVal); extend(ret, childVal); return ret; }; /** * Default strategy. */ var defaultStrat = function defaultStrat(parentVal, childVal) { return childVal === undefined ? parentVal : childVal; }; /** * Make sure component options get converted to actual * constructors. * * @param {Object} options */ function guardComponents(options) { if (options.components) { var components = options.components = guardArrayAssets(options.components); var ids = Object.keys(components); var def; if (process.env.NODE_ENV !== 'production') { var map = options._componentNameMap = {}; } for (var i = 0, l = ids.length; i < l; i++) { var key = ids[i]; if (commonTagRE.test(key) || reservedTagRE.test(key)) { process.env.NODE_ENV !== 'production' && warn('Do not use built-in or reserved HTML elements as component ' + 'id: ' + key); continue; } // record a all lowercase <-> kebab-case mapping for // possible custom element case error warning if (process.env.NODE_ENV !== 'production') { map[key.replace(/-/g, '').toLowerCase()] = hyphenate(key); } def = components[key]; if (isPlainObject(def)) { components[key] = Vue.extend(def); } } } } /** * Ensure all props option syntax are normalized into the * Object-based format. * * @param {Object} options */ function guardProps(options) { var props = options.props; var i, val; if (isArray(props)) { options.props = {}; i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { options.props[val] = null; } else if (val.name) { options.props[val.name] = val; } } } else if (isPlainObject(props)) { var keys = Object.keys(props); i = keys.length; while (i--) { val = props[keys[i]]; if (typeof val === 'function') { props[keys[i]] = { type: val }; } } } } /** * Guard an Array-format assets option and converted it * into the key-value Object format. * * @param {Object|Array} assets * @return {Object} */ function guardArrayAssets(assets) { if (isArray(assets)) { var res = {}; var i = assets.length; var asset; while (i--) { asset = assets[i]; var id = typeof asset === 'function' ? asset.options && asset.options.name || asset.id : asset.name || asset.id; if (!id) { process.env.NODE_ENV !== 'production' && warn('Array-syntax assets must provide a "name" or "id" field.'); } else { res[id] = asset; } } return res; } return assets; } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. * * @param {Object} parent * @param {Object} child * @param {Vue} [vm] - if vm is present, indicates this is * an instantiation merge. */ function mergeOptions(parent, child, vm) { guardComponents(child); guardProps(child); if (process.env.NODE_ENV !== 'production') { if (child.propsData && !vm) { warn('propsData can only be used as an instantiation option.'); } } var options = {}; var key; if (child['extends']) { parent = typeof child['extends'] === 'function' ? mergeOptions(parent, child['extends'].options, vm) : mergeOptions(parent, child['extends'], vm); } if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { parent = mergeOptions(parent, child.mixins[i], vm); } } for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField(key) { var strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options; } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. * * @param {Object} options * @param {String} type * @param {String} id * @param {Boolean} warnMissing * @return {Object|Function} */ function resolveAsset(options, type, id, warnMissing) { /* istanbul ignore if */ if (typeof id !== 'string') { return; } var assets = options[type]; var camelizedId; var res = assets[id] || // camelCase ID assets[camelizedId = camelize(id)] || // Pascal Case ID assets[camelizedId.charAt(0).toUpperCase() + camelizedId.slice(1)]; if (process.env.NODE_ENV !== 'production' && warnMissing && !res) { warn('Failed to resolve ' + type.slice(0, -1) + ': ' + id, options); } return res; } var uid$1 = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. * * @constructor */ function Dep() { this.id = uid$1++; this.subs = []; } // the current target watcher being evaluated. // this is globally unique because there could be only one // watcher being evaluated at any time. Dep.target = null; /** * Add a directive subscriber. * * @param {Directive} sub */ Dep.prototype.addSub = function (sub) { this.subs.push(sub); }; /** * Remove a directive subscriber. * * @param {Directive} sub */ Dep.prototype.removeSub = function (sub) { this.subs.$remove(sub); }; /** * Add self as a dependency to the target watcher. */ Dep.prototype.depend = function () { Dep.target.addDep(this); }; /** * Notify all subscribers of a new value. */ Dep.prototype.notify = function () { // stablize the subscriber list first var subs = toArray(this.subs); for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto) /** * Intercept mutating methods and emit events */ ;['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'].forEach(function (method) { // cache original method var original = arrayProto[method]; def(arrayMethods, method, function mutator() { // avoid leaking arguments: // path_to_url var i = arguments.length; var args = new Array(i); while (i--) { args[i] = arguments[i]; } var result = original.apply(this, args); var ob = this.__ob__; var inserted; switch (method) { case 'push': inserted = args; break; case 'unshift': inserted = args; break; case 'splice': inserted = args.slice(2); break; } if (inserted) ob.observeArray(inserted); // notify change ob.dep.notify(); return result; }); }); /** * Swap the element at the given index with a new value * and emits corresponding event. * * @param {Number} index * @param {*} val * @return {*} - replaced element */ def(arrayProto, '$set', function $set(index, val) { if (index >= this.length) { this.length = Number(index) + 1; } return this.splice(index, 1, val)[0]; }); /** * Convenience method to remove the element at given index or target element reference. * * @param {*} item */ def(arrayProto, '$remove', function $remove(item) { /* istanbul ignore if */ if (!this.length) return; var index = indexOf(this, item); if (index > -1) { return this.splice(index, 1); } }); var arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * By default, when a reactive property is set, the new value is * also converted to become reactive. However in certain cases, e.g. * v-for scope alias and props, we don't want to force conversion * because the value may be a nested value under a frozen data structure. * * So whenever we want to set a reactive property without forcing * conversion on the new value, we wrap that call inside this function. */ var shouldConvert = true; function withoutConversion(fn) { shouldConvert = false; fn(); shouldConvert = true; } /** * Observer class that are attached to each observed * object. Once attached, the observer converts target * object's property keys into getter/setters that * collect dependencies and dispatches updates. * * @param {Array|Object} value * @constructor */ function Observer(value) { this.value = value; this.dep = new Dep(); def(value, '__ob__', this); if (isArray(value)) { var augment = hasProto ? protoAugment : copyAugment; augment(value, arrayMethods, arrayKeys); this.observeArray(value); } else { this.walk(value); } } // Instance methods /** * Walk through each property and convert them into * getter/setters. This method should only be called when * value type is Object. * * @param {Object} obj */ Observer.prototype.walk = function (obj) { var keys = Object.keys(obj); for (var i = 0, l = keys.length; i < l; i++) { this.convert(keys[i], obj[keys[i]]); } }; /** * Observe a list of Array items. * * @param {Array} items */ Observer.prototype.observeArray = function (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; /** * Convert a property into getter/setter so we can emit * the events when the property is accessed/changed. * * @param {String} key * @param {*} val */ Observer.prototype.convert = function (key, val) { defineReactive(this.value, key, val); }; /** * Add an owner vm, so that when $set/$delete mutations * happen we can notify owner vms to proxy the keys and * digest the watchers. This is only called when the object * is observed as an instance's root $data. * * @param {Vue} vm */ Observer.prototype.addVm = function (vm) { (this.vms || (this.vms = [])).push(vm); }; /** * Remove an owner vm. This is called when the object is * swapped out as an instance's $data object. * * @param {Vue} vm */ Observer.prototype.removeVm = function (vm) { this.vms.$remove(vm); }; // helpers /** * Augment an target Object or Array by intercepting * the prototype chain using __proto__ * * @param {Object|Array} target * @param {Object} src */ function protoAugment(target, src) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ } /** * Augment an target Object or Array by defining * hidden properties. * * @param {Object|Array} target * @param {Object} proto */ function copyAugment(target, src, keys) { for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; def(target, key, src[key]); } } /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. * * @param {*} value * @param {Vue} [vm] * @return {Observer|undefined} * @static */ function observe(value, vm) { if (!value || typeof value !== 'object') { return; } var ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if (shouldConvert && (isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue) { ob = new Observer(value); } if (ob && vm) { ob.addVm(vm); } return ob; } /** * Define a reactive property on an Object. * * @param {Object} obj * @param {String} key * @param {*} val */ function defineReactive(obj, key, val) { var dep = new Dep(); var property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return; } // cater for pre-defined getter/setters var getter = property && property.get; var setter = property && property.set; var childOb = observe(val); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter() { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); } if (isArray(value)) { for (var e, i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); } } } return value; }, set: function reactiveSetter(newVal) { var value = getter ? getter.call(obj) : val; if (newVal === value) { return; } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = observe(newVal); dep.notify(); } }); } var util = Object.freeze({ defineReactive: defineReactive, set: set, del: del, hasOwn: hasOwn, isLiteral: isLiteral, isReserved: isReserved, _toString: _toString, toNumber: toNumber, toBoolean: toBoolean, stripQuotes: stripQuotes, camelize: camelize, hyphenate: hyphenate, classify: classify, bind: bind, toArray: toArray, extend: extend, isObject: isObject, isPlainObject: isPlainObject, def: def, debounce: _debounce, indexOf: indexOf, cancellable: cancellable, looseEqual: looseEqual, isArray: isArray, hasProto: hasProto, inBrowser: inBrowser, devtools: devtools, isIE9: isIE9, isAndroid: isAndroid, isIos: isIos, isWechat: isWechat, get transitionProp () { return transitionProp; }, get transitionEndEvent () { return transitionEndEvent; }, get animationProp () { return animationProp; }, get animationEndEvent () { return animationEndEvent; }, nextTick: nextTick, get _Set () { return _Set; }, query: query, inDoc: inDoc, getAttr: getAttr, getBindAttr: getBindAttr, hasBindAttr: hasBindAttr, before: before, after: after, remove: remove, prepend: prepend, replace: replace, on: on, off: off, setClass: setClass, addClass: addClass, removeClass: removeClass, extractContent: extractContent, trimNode: trimNode, isTemplate: isTemplate, createAnchor: createAnchor, findRef: findRef, mapNodeRange: mapNodeRange, removeNodeRange: removeNodeRange, isFragment: isFragment, getOuterHTML: getOuterHTML, mergeOptions: mergeOptions, resolveAsset: resolveAsset, checkComponentAttr: checkComponentAttr, commonTagRE: commonTagRE, reservedTagRE: reservedTagRE, get warn () { return warn; } }); var uid = 0; function initMixin (Vue) { /** * The main init sequence. This is called for every * instance, including ones that are created from extended * constructors. * * @param {Object} options - this options object should be * the result of merging class * options and the options passed * in to the constructor. */ Vue.prototype._init = function (options) { options = options || {}; this.$el = null; this.$parent = options.parent; this.$root = this.$parent ? this.$parent.$root : this; this.$children = []; this.$refs = {}; // child vm references this.$els = {}; // element references this._watchers = []; // all watchers as an array this._directives = []; // all directives // a uid this._uid = uid++; // a flag to avoid this being observed this._isVue = true; // events bookkeeping this._events = {}; // registered callbacks this._eventsCount = {}; // for $broadcast optimization // fragment instance properties this._isFragment = false; this._fragment = // @type {DocumentFragment} this._fragmentStart = // @type {Text|Comment} this._fragmentEnd = null; // @type {Text|Comment} // lifecycle state this._isCompiled = this._isDestroyed = this._isReady = this._isAttached = this._isBeingDestroyed = this._vForRemoving = false; this._unlinkFn = null; // context: // if this is a transcluded component, context // will be the common parent vm of this instance // and its host. this._context = options._context || this.$parent; // scope: // if this is inside an inline v-for, the scope // will be the intermediate scope created for this // repeat fragment. this is used for linking props // and container directives. this._scope = options._scope; // fragment: // if this instance is compiled inside a Fragment, it // needs to reigster itself as a child of that fragment // for attach/detach to work properly. this._frag = options._frag; if (this._frag) { this._frag.children.push(this); } // push self into parent / transclusion host if (this.$parent) { this.$parent.$children.push(this); } // merge options. options = this.$options = mergeOptions(this.constructor.options, options, this); // set ref this._updateRef(); // initialize data as empty object. // it will be filled up in _initData(). this._data = {}; // call init hook this._callHook('init'); // initialize data observation and scope inheritance. this._initState(); // setup event system and option events. this._initEvents(); // call created hook this._callHook('created'); // if `el` option is passed, start compilation. if (options.el) { this.$mount(options.el); } }; } var pathCache = new Cache(1000); // actions var APPEND = 0; var PUSH = 1; var INC_SUB_PATH_DEPTH = 2; var PUSH_SUB_PATH = 3; // states var BEFORE_PATH = 0; var IN_PATH = 1; var BEFORE_IDENT = 2; var IN_IDENT = 3; var IN_SUB_PATH = 4; var IN_SINGLE_QUOTE = 5; var IN_DOUBLE_QUOTE = 6; var AFTER_PATH = 7; var ERROR = 8; var pathStateMachine = []; pathStateMachine[BEFORE_PATH] = { 'ws': [BEFORE_PATH], 'ident': [IN_IDENT, APPEND], '[': [IN_SUB_PATH], 'eof': [AFTER_PATH] }; pathStateMachine[IN_PATH] = { 'ws': [IN_PATH], '.': [BEFORE_IDENT], '[': [IN_SUB_PATH], 'eof': [AFTER_PATH] }; pathStateMachine[BEFORE_IDENT] = { 'ws': [BEFORE_IDENT], 'ident': [IN_IDENT, APPEND] }; pathStateMachine[IN_IDENT] = { 'ident': [IN_IDENT, APPEND], '0': [IN_IDENT, APPEND], 'number': [IN_IDENT, APPEND], 'ws': [IN_PATH, PUSH], '.': [BEFORE_IDENT, PUSH], '[': [IN_SUB_PATH, PUSH], 'eof': [AFTER_PATH, PUSH] }; pathStateMachine[IN_SUB_PATH] = { "'": [IN_SINGLE_QUOTE, APPEND], '"': [IN_DOUBLE_QUOTE, APPEND], '[': [IN_SUB_PATH, INC_SUB_PATH_DEPTH], ']': [IN_PATH, PUSH_SUB_PATH], 'eof': ERROR, 'else': [IN_SUB_PATH, APPEND] }; pathStateMachine[IN_SINGLE_QUOTE] = { "'": [IN_SUB_PATH, APPEND], 'eof': ERROR, 'else': [IN_SINGLE_QUOTE, APPEND] }; pathStateMachine[IN_DOUBLE_QUOTE] = { '"': [IN_SUB_PATH, APPEND], 'eof': ERROR, 'else': [IN_DOUBLE_QUOTE, APPEND] }; /** * Determine the type of a character in a keypath. * * @param {Char} ch * @return {String} type */ function getPathCharType(ch) { if (ch === undefined) { return 'eof'; } var code = ch.charCodeAt(0); switch (code) { case 0x5B: // [ case 0x5D: // ] case 0x2E: // . case 0x22: // " case 0x27: // ' case 0x30: // 0 return ch; case 0x5F: // _ case 0x24: // $ return 'ident'; case 0x20: // Space case 0x09: // Tab case 0x0A: // Newline case 0x0D: // Return case 0xA0: // No-break space case 0xFEFF: // Byte Order Mark case 0x2028: // Line Separator case 0x2029: // Paragraph Separator return 'ws'; } // a-z, A-Z if (code >= 0x61 && code <= 0x7A || code >= 0x41 && code <= 0x5A) { return 'ident'; } // 1-9 if (code >= 0x31 && code <= 0x39) { return 'number'; } return 'else'; } /** * Format a subPath, return its plain form if it is * a literal string or number. Otherwise prepend the * dynamic indicator (*). * * @param {String} path * @return {String} */ function formatSubPath(path) { var trimmed = path.trim(); // invalid leading 0 if (path.charAt(0) === '0' && isNaN(path)) { return false; } return isLiteral(trimmed) ? stripQuotes(trimmed) : '*' + trimmed; } /** * Parse a string path into an array of segments * * @param {String} path * @return {Array|undefined} */ function parse(path) { var keys = []; var index = -1; var mode = BEFORE_PATH; var subPathDepth = 0; var c, newChar, key, type, transition, action, typeMap; var actions = []; actions[PUSH] = function () { if (key !== undefined) { keys.push(key); key = undefined; } }; actions[APPEND] = function () { if (key === undefined) { key = newChar; } else { key += newChar; } }; actions[INC_SUB_PATH_DEPTH] = function () { actions[APPEND](); subPathDepth++; }; actions[PUSH_SUB_PATH] = function () { if (subPathDepth > 0) { subPathDepth--; mode = IN_SUB_PATH; actions[APPEND](); } else { subPathDepth = 0; key = formatSubPath(key); if (key === false) { return false; } else { actions[PUSH](); } } }; function maybeUnescapeQuote() { var nextChar = path[index + 1]; if (mode === IN_SINGLE_QUOTE && nextChar === "'" || mode === IN_DOUBLE_QUOTE && nextChar === '"') { index++; newChar = '\\' + nextChar; actions[APPEND](); return true; } } while (mode != null) { index++; c = path[index]; if (c === '\\' && maybeUnescapeQuote()) { continue; } type = getPathCharType(c); typeMap = pathStateMachine[mode]; transition = typeMap[type] || typeMap['else'] || ERROR; if (transition === ERROR) { return; // parse error } mode = transition[0]; action = actions[transition[1]]; if (action) { newChar = transition[2]; newChar = newChar === undefined ? c : newChar; if (action() === false) { return; } } if (mode === AFTER_PATH) { keys.raw = path; return keys; } } } /** * External parse that check for a cache hit first * * @param {String} path * @return {Array|undefined} */ function parsePath(path) { var hit = pathCache.get(path); if (!hit) { hit = parse(path); if (hit) { pathCache.put(path, hit); } } return hit; } /** * Get from an object from a path string * * @param {Object} obj * @param {String} path */ function getPath(obj, path) { return parseExpression(path).get(obj); } /** * Warn against setting non-existent root path on a vm. */ var warnNonExistent; if (process.env.NODE_ENV !== 'production') { warnNonExistent = function (path, vm) { warn('You are setting a non-existent path "' + path.raw + '" ' + 'on a vm instance. Consider pre-initializing the property ' + 'with the "data" option for more reliable reactivity ' + 'and better performance.', vm); }; } /** * Set on an object from a path * * @param {Object} obj * @param {String | Array} path * @param {*} val */ function setPath(obj, path, val) { var original = obj; if (typeof path === 'string') { path = parse(path); } if (!path || !isObject(obj)) { return false; } var last, key; for (var i = 0, l = path.length; i < l; i++) { last = obj; key = path[i]; if (key.charAt(0) === '*') { key = parseExpression(key.slice(1)).get.call(original, original); } if (i < l - 1) { obj = obj[key]; if (!isObject(obj)) { obj = {}; if (process.env.NODE_ENV !== 'production' && last._isVue) { warnNonExistent(path, last); } set(last, key, obj); } } else { if (isArray(obj)) { obj.$set(key, val); } else if (key in obj) { obj[key] = val; } else { if (process.env.NODE_ENV !== 'production' && obj._isVue) { warnNonExistent(path, obj); } set(obj, key, val); } } } return true; } var path = Object.freeze({ parsePath: parsePath, getPath: getPath, setPath: setPath }); var expressionCache = new Cache(1000); var allowedKeywords = 'Math,Date,this,true,false,null,undefined,Infinity,NaN,' + 'isNaN,isFinite,decodeURI,decodeURIComponent,encodeURI,' + 'encodeURIComponent,parseInt,parseFloat'; var allowedKeywordsRE = new RegExp('^(' + allowedKeywords.replace(/,/g, '\\b|') + '\\b)'); // keywords that don't make sense inside expressions var improperKeywords = 'break,case,class,catch,const,continue,debugger,default,' + 'delete,do,else,export,extends,finally,for,function,if,' + 'import,in,instanceof,let,return,super,switch,throw,try,' + 'var,while,with,yield,enum,await,implements,package,' + 'protected,static,interface,private,public'; var improperKeywordsRE = new RegExp('^(' + improperKeywords.replace(/,/g, '\\b|') + '\\b)'); var wsRE = /\s/g; var newlineRE = /\n/g; var saveRE = /[\{,]\s*[\w\$_]+\s*:|('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`)|new |typeof |void /g; var restoreRE = /"(\d+)"/g; var pathTestRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?'\]|\[".*?"\]|\[\d+\]|\[[A-Za-z_$][\w$]*\])*$/; var identRE = /[^\w$\.](?:[A-Za-z_$][\w$]*)/g; var booleanLiteralRE = /^(?:true|false)$/; /** * Save / Rewrite / Restore * * When rewriting paths found in an expression, it is * possible for the same letter sequences to be found in * strings and Object literal property keys. Therefore we * remove and store these parts in a temporary array, and * restore them after the path rewrite. */ var saved = []; /** * Save replacer * * The save regex can match two possible cases: * 1. An opening object literal * 2. A string * If matched as a plain string, we need to escape its * newlines, since the string needs to be preserved when * generating the function body. * * @param {String} str * @param {String} isString - str if matched as a string * @return {String} - placeholder with index */ function save(str, isString) { var i = saved.length; saved[i] = isString ? str.replace(newlineRE, '\\n') : str; return '"' + i + '"'; } /** * Path rewrite replacer * * @param {String} raw * @return {String} */ function rewrite(raw) { var c = raw.charAt(0); var path = raw.slice(1); if (allowedKeywordsRE.test(path)) { return raw; } else { path = path.indexOf('"') > -1 ? path.replace(restoreRE, restore) : path; return c + 'scope.' + path; } } /** * Restore replacer * * @param {String} str * @param {String} i - matched save index * @return {String} */ function restore(str, i) { return saved[i]; } /** * Rewrite an expression, prefixing all path accessors with * `scope.` and generate getter/setter functions. * * @param {String} exp * @return {Function} */ function compileGetter(exp) { if (improperKeywordsRE.test(exp)) { process.env.NODE_ENV !== 'production' && warn('Avoid using reserved keywords in expression: ' + exp); } // reset state saved.length = 0; // save strings and object literal keys var body = exp.replace(saveRE, save).replace(wsRE, ''); // rewrite all paths // pad 1 space here becaue the regex matches 1 extra char body = (' ' + body).replace(identRE, rewrite).replace(restoreRE, restore); return makeGetterFn(body); } /** * Build a getter function. Requires eval. * * We isolate the try/catch so it doesn't affect the * optimization of the parse function when it is not called. * * @param {String} body * @return {Function|undefined} */ function makeGetterFn(body) { try { /* eslint-disable no-new-func */ return new Function('scope', 'return ' + body + ';'); /* eslint-enable no-new-func */ } catch (e) { process.env.NODE_ENV !== 'production' && warn('Invalid expression. ' + 'Generated function body: ' + body); } } /** * Compile a setter function for the expression. * * @param {String} exp * @return {Function|undefined} */ function compileSetter(exp) { var path = parsePath(exp); if (path) { return function (scope, val) { setPath(scope, path, val); }; } else { process.env.NODE_ENV !== 'production' && warn('Invalid setter expression: ' + exp); } } /** * Parse an expression into re-written getter/setters. * * @param {String} exp * @param {Boolean} needSet * @return {Function} */ function parseExpression(exp, needSet) { exp = exp.trim(); // try cache var hit = expressionCache.get(exp); if (hit) { if (needSet && !hit.set) { hit.set = compileSetter(hit.exp); } return hit; } var res = { exp: exp }; res.get = isSimplePath(exp) && exp.indexOf('[') < 0 // optimized super simple getter ? makeGetterFn('scope.' + exp) // dynamic getter : compileGetter(exp); if (needSet) { res.set = compileSetter(exp); } expressionCache.put(exp, res); return res; } /** * Check if an expression is a simple path. * * @param {String} exp * @return {Boolean} */ function isSimplePath(exp) { return pathTestRE.test(exp) && // don't treat true/false as paths !booleanLiteralRE.test(exp) && // Math constants e.g. Math.PI, Math.E etc. exp.slice(0, 5) !== 'Math.'; } var expression = Object.freeze({ parseExpression: parseExpression, isSimplePath: isSimplePath }); // we have two separate queues: one for directive updates // and one for user watcher registered via $watch(). // we want to guarantee directive updates to be called // before user watchers so that when user watchers are // triggered, the DOM would have already been in updated // state. var queue = []; var userQueue = []; var has = {}; var circular = {}; var waiting = false; /** * Reset the batcher's state. */ function resetBatcherState() { queue.length = 0; userQueue.length = 0; has = {}; circular = {}; waiting = false; } /** * Flush both queues and run the watchers. */ function flushBatcherQueue() { var _again = true; _function: while (_again) { _again = false; runBatcherQueue(queue); runBatcherQueue(userQueue); // user watchers triggered more watchers, // keep flushing until it depletes if (queue.length) { _again = true; continue _function; } // dev tool hook /* istanbul ignore if */ if (devtools && config.devtools) { devtools.emit('flush'); } resetBatcherState(); } } /** * Run the watchers in a single queue. * * @param {Array} queue */ function runBatcherQueue(queue) { // do not cache length because more watchers might be pushed // as we run existing watchers for (var i = 0; i < queue.length; i++) { var watcher = queue[i]; var id = watcher.id; has[id] = null; watcher.run(); // in dev build, check and stop circular updates. if (process.env.NODE_ENV !== 'production' && has[id] != null) { circular[id] = (circular[id] || 0) + 1; if (circular[id] > config._maxUpdateCount) { warn('You may have an infinite update loop for watcher ' + 'with expression "' + watcher.expression + '"', watcher.vm); break; } } } queue.length = 0; } /** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. * * @param {Watcher} watcher * properties: * - {Number} id * - {Function} run */ function pushWatcher(watcher) { var id = watcher.id; if (has[id] == null) { // push watcher into appropriate queue var q = watcher.user ? userQueue : queue; has[id] = q.length; q.push(watcher); // queue the flush if (!waiting) { waiting = true; nextTick(flushBatcherQueue); } } } var uid$2 = 0; /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. * * @param {Vue} vm * @param {String|Function} expOrFn * @param {Function} cb * @param {Object} options * - {Array} filters * - {Boolean} twoWay * - {Boolean} deep * - {Boolean} user * - {Boolean} sync * - {Boolean} lazy * - {Function} [preProcess] * - {Function} [postProcess] * @constructor */ function Watcher(vm, expOrFn, cb, options) { // mix in options if (options) { extend(this, options); } var isFn = typeof expOrFn === 'function'; this.vm = vm; vm._watchers.push(this); this.expression = expOrFn; this.cb = cb; this.id = ++uid$2; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; this.newDeps = []; this.depIds = new _Set(); this.newDepIds = new _Set(); this.prevError = null; // for async error stacks // parse expression for getter/setter if (isFn) { this.getter = expOrFn; this.setter = undefined; } else { var res = parseExpression(expOrFn, this.twoWay); this.getter = res.get; this.setter = res.set; } this.value = this.lazy ? undefined : this.get(); // state for avoiding false triggers for deep and Array // watchers during vm._digest() this.queued = this.shallow = false; } /** * Evaluate the getter, and re-collect dependencies. */ Watcher.prototype.get = function () { this.beforeGet(); var scope = this.scope || this.vm; var value; try { value = this.getter.call(scope, scope); } catch (e) { if (process.env.NODE_ENV !== 'production' && config.warnExpressionErrors) { warn('Error when evaluating expression ' + '"' + this.expression + '": ' + e.toString(), this.vm); } } // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } if (this.preProcess) { value = this.preProcess(value); } if (this.filters) { value = scope._applyFilters(value, null, this.filters, false); } if (this.postProcess) { value = this.postProcess(value); } this.afterGet(); return value; }; /** * Set the corresponding value with the setter. * * @param {*} value */ Watcher.prototype.set = function (value) { var scope = this.scope || this.vm; if (this.filters) { value = scope._applyFilters(value, this.value, this.filters, true); } try { this.setter.call(scope, scope, value); } catch (e) { if (process.env.NODE_ENV !== 'production' && config.warnExpressionErrors) { warn('Error when evaluating setter ' + '"' + this.expression + '": ' + e.toString(), this.vm); } } // two-way sync for v-for alias var forContext = scope.$forContext; if (forContext && forContext.alias === this.expression) { if (forContext.filters) { process.env.NODE_ENV !== 'production' && warn('It seems you are using two-way binding on ' + 'a v-for alias (' + this.expression + '), and the ' + 'v-for has filters. This will not work properly. ' + 'Either remove the filters or use an array of ' + 'objects and bind to object properties instead.', this.vm); return; } forContext._withLock(function () { if (scope.$key) { // original is an object forContext.rawValue[scope.$key] = value; } else { forContext.rawValue.$set(scope.$index, value); } }); } }; /** * Prepare for dependency collection. */ Watcher.prototype.beforeGet = function () { Dep.target = this; }; /** * Add a dependency to this directive. * * @param {Dep} dep */ Watcher.prototype.addDep = function (dep) { var id = dep.id; if (!this.newDepIds.has(id)) { this.newDepIds.add(id); this.newDeps.push(dep); if (!this.depIds.has(id)) { dep.addSub(this); } } }; /** * Clean up for dependency collection. */ Watcher.prototype.afterGet = function () { Dep.target = null; var i = this.deps.length; while (i--) { var dep = this.deps[i]; if (!this.newDepIds.has(dep.id)) { dep.removeSub(this); } } var tmp = this.depIds; this.depIds = this.newDepIds; this.newDepIds = tmp; this.newDepIds.clear(); tmp = this.deps; this.deps = this.newDeps; this.newDeps = tmp; this.newDeps.length = 0; }; /** * Subscriber interface. * Will be called when a dependency changes. * * @param {Boolean} shallow */ Watcher.prototype.update = function (shallow) { if (this.lazy) { this.dirty = true; } else if (this.sync || !config.async) { this.run(); } else { // if queued, only overwrite shallow with non-shallow, // but not the other way around. this.shallow = this.queued ? shallow ? this.shallow : false : !!shallow; this.queued = true; // record before-push error stack in debug mode /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.debug) { this.prevError = new Error('[vue] async stack trace'); } pushWatcher(this); } }; /** * Batcher job interface. * Will be called by the batcher. */ Watcher.prototype.run = function () { if (this.active) { var value = this.get(); if (value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated; but only do so if this is a // non-shallow update (caused by a vm digest). (isObject(value) || this.deep) && !this.shallow) { // set new value var oldValue = this.value; this.value = value; // in debug + async mode, when a watcher callbacks // throws, we also throw the saved before-push error // so the full cross-tick stack trace is available. var prevError = this.prevError; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.debug && prevError) { this.prevError = null; try { this.cb.call(this.vm, value, oldValue); } catch (e) { nextTick(function () { throw prevError; }, 0); throw e; } } else { this.cb.call(this.vm, value, oldValue); } } this.queued = this.shallow = false; } }; /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ Watcher.prototype.evaluate = function () { // avoid overwriting another watcher that is being // collected. var current = Dep.target; this.value = this.get(); this.dirty = false; Dep.target = current; }; /** * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function () { var i = this.deps.length; while (i--) { this.deps[i].depend(); } }; /** * Remove self from all dependencies' subcriber list. */ Watcher.prototype.teardown = function () { if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed or is performing a v-for // re-render (the watcher list is then filtered by v-for). if (!this.vm._isBeingDestroyed && !this.vm._vForRemoving) { this.vm._watchers.$remove(this); } var i = this.deps.length; while (i--) { this.deps[i].removeSub(this); } this.active = false; this.vm = this.cb = this.value = null; } }; /** * Recrusively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. * * @param {*} val */ var seenObjects = new _Set(); function traverse(val, seen) { var i = undefined, keys = undefined; if (!seen) { seen = seenObjects; seen.clear(); } var isA = isArray(val); var isO = isObject(val); if (isA || isO) { if (val.__ob__) { var depId = val.__ob__.dep.id; if (seen.has(depId)) { return; } else { seen.add(depId); } } if (isA) { i = val.length; while (i--) traverse(val[i], seen); } else if (isO) { keys = Object.keys(val); i = keys.length; while (i--) traverse(val[keys[i]], seen); } } } var text$1 = { bind: function bind() { this.attr = this.el.nodeType === 3 ? 'data' : 'textContent'; }, update: function update(value) { this.el[this.attr] = _toString(value); } }; var templateCache = new Cache(1000); var idSelectorCache = new Cache(1000); var map = { efault: [0, '', ''], legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'] }; map.td = map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>']; map.option = map.optgroup = [1, '<select multiple="multiple">', '</select>']; map.thead = map.tbody = map.colgroup = map.caption = map.tfoot = [1, '<table>', '</table>']; map.g = map.defs = map.symbol = map.use = map.image = map.text = map.circle = map.ellipse = map.line = map.path = map.polygon = map.polyline = map.rect = [1, '<svg ' + 'xmlns="path_to_url" ' + 'xmlns:xlink="path_to_url" ' + 'xmlns:ev="path_to_url"' + 'version="1.1">', '</svg>']; /** * Check if a node is a supported template node with a * DocumentFragment content. * * @param {Node} node * @return {Boolean} */ function isRealTemplate(node) { return isTemplate(node) && isFragment(node.content); } var tagRE$1 = /<([\w:-]+)/; var entityRE = /&#?\w+?;/; /** * Convert a string template to a DocumentFragment. * Determines correct wrapping by tag types. Wrapping * strategy found in jQuery & component/domify. * * @param {String} templateString * @param {Boolean} raw * @return {DocumentFragment} */ function stringToFragment(templateString, raw) { // try a cache hit first var cacheKey = raw ? templateString : templateString.trim(); var hit = templateCache.get(cacheKey); if (hit) { return hit; } var frag = document.createDocumentFragment(); var tagMatch = templateString.match(tagRE$1); var entityMatch = entityRE.test(templateString); if (!tagMatch && !entityMatch) { // text only, return a single text node. frag.appendChild(document.createTextNode(templateString)); } else { var tag = tagMatch && tagMatch[1]; var wrap = map[tag] || map.efault; var depth = wrap[0]; var prefix = wrap[1]; var suffix = wrap[2]; var node = document.createElement('div'); node.innerHTML = prefix + templateString + suffix; while (depth--) { node = node.lastChild; } var child; /* eslint-disable no-cond-assign */ while (child = node.firstChild) { /* eslint-enable no-cond-assign */ frag.appendChild(child); } } if (!raw) { trimNode(frag); } templateCache.put(cacheKey, frag); return frag; } /** * Convert a template node to a DocumentFragment. * * @param {Node} node * @return {DocumentFragment} */ function nodeToFragment(node) { // if its a template tag and the browser supports it, // its content is already a document fragment. However, iOS Safari has // bug when using directly cloned template content with touch // events and can cause crashes when the nodes are removed from DOM, so we // have to treat template elements as string templates. (#2805) /* istanbul ignore if */ if (isRealTemplate(node)) { return stringToFragment(node.innerHTML); } // script template if (node.tagName === 'SCRIPT') { return stringToFragment(node.textContent); } // normal node, clone it to avoid mutating the original var clonedNode = cloneNode(node); var frag = document.createDocumentFragment(); var child; /* eslint-disable no-cond-assign */ while (child = clonedNode.firstChild) { /* eslint-enable no-cond-assign */ frag.appendChild(child); } trimNode(frag); return frag; } // Test for the presence of the Safari template cloning bug // path_to_url var hasBrokenTemplate = (function () { /* istanbul ignore else */ if (inBrowser) { var a = document.createElement('div'); a.innerHTML = '<template>1</template>'; return !a.cloneNode(true).firstChild.innerHTML; } else { return false; } })(); // Test for IE10/11 textarea placeholder clone bug var hasTextareaCloneBug = (function () { /* istanbul ignore else */ if (inBrowser) { var t = document.createElement('textarea'); t.placeholder = 't'; return t.cloneNode(true).value === 't'; } else { return false; } })(); /** * 1. Deal with Safari cloning nested <template> bug by * manually cloning all template instances. * 2. Deal with IE10/11 textarea placeholder bug by setting * the correct value after cloning. * * @param {Element|DocumentFragment} node * @return {Element|DocumentFragment} */ function cloneNode(node) { /* istanbul ignore if */ if (!node.querySelectorAll) { return node.cloneNode(); } var res = node.cloneNode(true); var i, original, cloned; /* istanbul ignore if */ if (hasBrokenTemplate) { var tempClone = res; if (isRealTemplate(node)) { node = node.content; tempClone = res.content; } original = node.querySelectorAll('template'); if (original.length) { cloned = tempClone.querySelectorAll('template'); i = cloned.length; while (i--) { cloned[i].parentNode.replaceChild(cloneNode(original[i]), cloned[i]); } } } /* istanbul ignore if */ if (hasTextareaCloneBug) { if (node.tagName === 'TEXTAREA') { res.value = node.value; } else { original = node.querySelectorAll('textarea'); if (original.length) { cloned = res.querySelectorAll('textarea'); i = cloned.length; while (i--) { cloned[i].value = original[i].value; } } } } return res; } /** * Process the template option and normalizes it into a * a DocumentFragment that can be used as a partial or a * instance template. * * @param {*} template * Possible values include: * - DocumentFragment object * - Node object of type Template * - id selector: '#some-template-id' * - template string: '<div><span>{{msg}}</span></div>' * @param {Boolean} shouldClone * @param {Boolean} raw * inline HTML interpolation. Do not check for id * selector and keep whitespace in the string. * @return {DocumentFragment|undefined} */ function parseTemplate(template, shouldClone, raw) { var node, frag; // if the template is already a document fragment, // do nothing if (isFragment(template)) { trimNode(template); return shouldClone ? cloneNode(template) : template; } if (typeof template === 'string') { // id selector if (!raw && template.charAt(0) === '#') { // id selector can be cached too frag = idSelectorCache.get(template); if (!frag) { node = document.getElementById(template.slice(1)); if (node) { frag = nodeToFragment(node); // save selector to cache idSelectorCache.put(template, frag); } } } else { // normal string template frag = stringToFragment(template, raw); } } else if (template.nodeType) { // a direct node frag = nodeToFragment(template); } return frag && shouldClone ? cloneNode(frag) : frag; } var template = Object.freeze({ cloneNode: cloneNode, parseTemplate: parseTemplate }); var html = { bind: function bind() { // a comment node means this is a binding for // {{{ inline unescaped html }}} if (this.el.nodeType === 8) { // hold nodes this.nodes = []; // replace the placeholder with proper anchor this.anchor = createAnchor('v-html'); replace(this.el, this.anchor); } }, update: function update(value) { value = _toString(value); if (this.nodes) { this.swap(value); } else { this.el.innerHTML = value; } }, swap: function swap(value) { // remove old nodes var i = this.nodes.length; while (i--) { remove(this.nodes[i]); } // convert new value to a fragment // do not attempt to retrieve from id selector var frag = parseTemplate(value, true, true); // save a reference to these nodes so we can remove later this.nodes = toArray(frag.childNodes); before(frag, this.anchor); } }; /** * Abstraction for a partially-compiled fragment. * Can optionally compile content with a child scope. * * @param {Function} linker * @param {Vue} vm * @param {DocumentFragment} frag * @param {Vue} [host] * @param {Object} [scope] * @param {Fragment} [parentFrag] */ function Fragment(linker, vm, frag, host, scope, parentFrag) { this.children = []; this.childFrags = []; this.vm = vm; this.scope = scope; this.inserted = false; this.parentFrag = parentFrag; if (parentFrag) { parentFrag.childFrags.push(this); } this.unlink = linker(vm, frag, host, scope, this); var single = this.single = frag.childNodes.length === 1 && // do not go single mode if the only node is an anchor !frag.childNodes[0].__v_anchor; if (single) { this.node = frag.childNodes[0]; this.before = singleBefore; this.remove = singleRemove; } else { this.node = createAnchor('fragment-start'); this.end = createAnchor('fragment-end'); this.frag = frag; prepend(this.node, frag); frag.appendChild(this.end); this.before = multiBefore; this.remove = multiRemove; } this.node.__v_frag = this; } /** * Call attach/detach for all components contained within * this fragment. Also do so recursively for all child * fragments. * * @param {Function} hook */ Fragment.prototype.callHook = function (hook) { var i, l; for (i = 0, l = this.childFrags.length; i < l; i++) { this.childFrags[i].callHook(hook); } for (i = 0, l = this.children.length; i < l; i++) { hook(this.children[i]); } }; /** * Insert fragment before target, single node version * * @param {Node} target * @param {Boolean} withTransition */ function singleBefore(target, withTransition) { this.inserted = true; var method = withTransition !== false ? beforeWithTransition : before; method(this.node, target, this.vm); if (inDoc(this.node)) { this.callHook(attach); } } /** * Remove fragment, single node version */ function singleRemove() { this.inserted = false; var shouldCallRemove = inDoc(this.node); var self = this; this.beforeRemove(); removeWithTransition(this.node, this.vm, function () { if (shouldCallRemove) { self.callHook(detach); } self.destroy(); }); } /** * Insert fragment before target, multi-nodes version * * @param {Node} target * @param {Boolean} withTransition */ function multiBefore(target, withTransition) { this.inserted = true; var vm = this.vm; var method = withTransition !== false ? beforeWithTransition : before; mapNodeRange(this.node, this.end, function (node) { method(node, target, vm); }); if (inDoc(this.node)) { this.callHook(attach); } } /** * Remove fragment, multi-nodes version */ function multiRemove() { this.inserted = false; var self = this; var shouldCallRemove = inDoc(this.node); this.beforeRemove(); removeNodeRange(this.node, this.end, this.vm, this.frag, function () { if (shouldCallRemove) { self.callHook(detach); } self.destroy(); }); } /** * Prepare the fragment for removal. */ Fragment.prototype.beforeRemove = function () { var i, l; for (i = 0, l = this.childFrags.length; i < l; i++) { // call the same method recursively on child // fragments, depth-first this.childFrags[i].beforeRemove(false); } for (i = 0, l = this.children.length; i < l; i++) { // Call destroy for all contained instances, // with remove:false and defer:true. // Defer is necessary because we need to // keep the children to call detach hooks // on them. this.children[i].$destroy(false, true); } var dirs = this.unlink.dirs; for (i = 0, l = dirs.length; i < l; i++) { // disable the watchers on all the directives // so that the rendered content stays the same // during removal. dirs[i]._watcher && dirs[i]._watcher.teardown(); } }; /** * Destroy the fragment. */ Fragment.prototype.destroy = function () { if (this.parentFrag) { this.parentFrag.childFrags.$remove(this); } this.node.__v_frag = null; this.unlink(); }; /** * Call attach hook for a Vue instance. * * @param {Vue} child */ function attach(child) { if (!child._isAttached && inDoc(child.$el)) { child._callHook('attached'); } } /** * Call detach hook for a Vue instance. * * @param {Vue} child */ function detach(child) { if (child._isAttached && !inDoc(child.$el)) { child._callHook('detached'); } } var linkerCache = new Cache(5000); /** * A factory that can be used to create instances of a * fragment. Caches the compiled linker if possible. * * @param {Vue} vm * @param {Element|String} el */ function FragmentFactory(vm, el) { this.vm = vm; var template; var isString = typeof el === 'string'; if (isString || isTemplate(el) && !el.hasAttribute('v-if')) { template = parseTemplate(el, true); } else { template = document.createDocumentFragment(); template.appendChild(el); } this.template = template; // linker can be cached, but only for components var linker; var cid = vm.constructor.cid; if (cid > 0) { var cacheId = cid + (isString ? el : getOuterHTML(el)); linker = linkerCache.get(cacheId); if (!linker) { linker = compile(template, vm.$options, true); linkerCache.put(cacheId, linker); } } else { linker = compile(template, vm.$options, true); } this.linker = linker; } /** * Create a fragment instance with given host and scope. * * @param {Vue} host * @param {Object} scope * @param {Fragment} parentFrag */ FragmentFactory.prototype.create = function (host, scope, parentFrag) { var frag = cloneNode(this.template); return new Fragment(this.linker, this.vm, frag, host, scope, parentFrag); }; var ON = 700; var MODEL = 800; var BIND = 850; var TRANSITION = 1100; var EL = 1500; var COMPONENT = 1500; var PARTIAL = 1750; var IF = 2100; var FOR = 2200; var SLOT = 2300; var uid$3 = 0; var vFor = { priority: FOR, terminal: true, params: ['track-by', 'stagger', 'enter-stagger', 'leave-stagger'], bind: function bind() { // support "item in/of items" syntax var inMatch = this.expression.match(/(.*) (?:in|of) (.*)/); if (inMatch) { var itMatch = inMatch[1].match(/\((.*),(.*)\)/); if (itMatch) { this.iterator = itMatch[1].trim(); this.alias = itMatch[2].trim(); } else { this.alias = inMatch[1].trim(); } this.expression = inMatch[2]; } if (!this.alias) { process.env.NODE_ENV !== 'production' && warn('Invalid v-for expression "' + this.descriptor.raw + '": ' + 'alias is required.', this.vm); return; } // uid as a cache identifier this.id = '__v-for__' + ++uid$3; // check if this is an option list, // so that we know if we need to update the <select>'s // v-model when the option list has changed. // because v-model has a lower priority than v-for, // the v-model is not bound here yet, so we have to // retrive it in the actual updateModel() function. var tag = this.el.tagName; this.isOption = (tag === 'OPTION' || tag === 'OPTGROUP') && this.el.parentNode.tagName === 'SELECT'; // setup anchor nodes this.start = createAnchor('v-for-start'); this.end = createAnchor('v-for-end'); replace(this.el, this.end); before(this.start, this.end); // cache this.cache = Object.create(null); // fragment factory this.factory = new FragmentFactory(this.vm, this.el); }, update: function update(data) { this.diff(data); this.updateRef(); this.updateModel(); }, /** * Diff, based on new data and old data, determine the * minimum amount of DOM manipulations needed to make the * DOM reflect the new data Array. * * The algorithm diffs the new data Array by storing a * hidden reference to an owner vm instance on previously * seen data. This allows us to achieve O(n) which is * better than a levenshtein distance based algorithm, * which is O(m * n). * * @param {Array} data */ diff: function diff(data) { // check if the Array was converted from an Object var item = data[0]; var convertedFromObject = this.fromObject = isObject(item) && hasOwn(item, '$key') && hasOwn(item, '$value'); var trackByKey = this.params.trackBy; var oldFrags = this.frags; var frags = this.frags = new Array(data.length); var alias = this.alias; var iterator = this.iterator; var start = this.start; var end = this.end; var inDocument = inDoc(start); var init = !oldFrags; var i, l, frag, key, value, primitive; // First pass, go through the new Array and fill up // the new frags array. If a piece of data has a cached // instance for it, we reuse it. Otherwise build a new // instance. for (i = 0, l = data.length; i < l; i++) { item = data[i]; key = convertedFromObject ? item.$key : null; value = convertedFromObject ? item.$value : item; primitive = !isObject(value); frag = !init && this.getCachedFrag(value, i, key); if (frag) { // reusable fragment frag.reused = true; // update $index frag.scope.$index = i; // update $key if (key) { frag.scope.$key = key; } // update iterator if (iterator) { frag.scope[iterator] = key !== null ? key : i; } // update data for track-by, object repeat & // primitive values. if (trackByKey || convertedFromObject || primitive) { withoutConversion(function () { frag.scope[alias] = value; }); } } else { // new isntance frag = this.create(value, alias, i, key); frag.fresh = !init; } frags[i] = frag; if (init) { frag.before(end); } } // we're done for the initial render. if (init) { return; } // Second pass, go through the old fragments and // destroy those who are not reused (and remove them // from cache) var removalIndex = 0; var totalRemoved = oldFrags.length - frags.length; // when removing a large number of fragments, watcher removal // turns out to be a perf bottleneck, so we batch the watcher // removals into a single filter call! this.vm._vForRemoving = true; for (i = 0, l = oldFrags.length; i < l; i++) { frag = oldFrags[i]; if (!frag.reused) { this.deleteCachedFrag(frag); this.remove(frag, removalIndex++, totalRemoved, inDocument); } } this.vm._vForRemoving = false; if (removalIndex) { this.vm._watchers = this.vm._watchers.filter(function (w) { return w.active; }); } // Final pass, move/insert new fragments into the // right place. var targetPrev, prevEl, currentPrev; var insertionIndex = 0; for (i = 0, l = frags.length; i < l; i++) { frag = frags[i]; // this is the frag that we should be after targetPrev = frags[i - 1]; prevEl = targetPrev ? targetPrev.staggerCb ? targetPrev.staggerAnchor : targetPrev.end || targetPrev.node : start; if (frag.reused && !frag.staggerCb) { currentPrev = findPrevFrag(frag, start, this.id); if (currentPrev !== targetPrev && (!currentPrev || // optimization for moving a single item. // thanks to suggestions by @livoras in #1807 findPrevFrag(currentPrev, start, this.id) !== targetPrev)) { this.move(frag, prevEl); } } else { // new instance, or still in stagger. // insert with updated stagger index. this.insert(frag, insertionIndex++, prevEl, inDocument); } frag.reused = frag.fresh = false; } }, /** * Create a new fragment instance. * * @param {*} value * @param {String} alias * @param {Number} index * @param {String} [key] * @return {Fragment} */ create: function create(value, alias, index, key) { var host = this._host; // create iteration scope var parentScope = this._scope || this.vm; var scope = Object.create(parentScope); // ref holder for the scope scope.$refs = Object.create(parentScope.$refs); scope.$els = Object.create(parentScope.$els); // make sure point $parent to parent scope scope.$parent = parentScope; // for two-way binding on alias scope.$forContext = this; // define scope properties // important: define the scope alias without forced conversion // so that frozen data structures remain non-reactive. withoutConversion(function () { defineReactive(scope, alias, value); }); defineReactive(scope, '$index', index); if (key) { defineReactive(scope, '$key', key); } else if (scope.$key) { // avoid accidental fallback def(scope, '$key', null); } if (this.iterator) { defineReactive(scope, this.iterator, key !== null ? key : index); } var frag = this.factory.create(host, scope, this._frag); frag.forId = this.id; this.cacheFrag(value, frag, index, key); return frag; }, /** * Update the v-ref on owner vm. */ updateRef: function updateRef() { var ref = this.descriptor.ref; if (!ref) return; var hash = (this._scope || this.vm).$refs; var refs; if (!this.fromObject) { refs = this.frags.map(findVmFromFrag); } else { refs = {}; this.frags.forEach(function (frag) { refs[frag.scope.$key] = findVmFromFrag(frag); }); } hash[ref] = refs; }, /** * For option lists, update the containing v-model on * parent <select>. */ updateModel: function updateModel() { if (this.isOption) { var parent = this.start.parentNode; var model = parent && parent.__v_model; if (model) { model.forceUpdate(); } } }, /** * Insert a fragment. Handles staggering. * * @param {Fragment} frag * @param {Number} index * @param {Node} prevEl * @param {Boolean} inDocument */ insert: function insert(frag, index, prevEl, inDocument) { if (frag.staggerCb) { frag.staggerCb.cancel(); frag.staggerCb = null; } var staggerAmount = this.getStagger(frag, index, null, 'enter'); if (inDocument && staggerAmount) { // create an anchor and insert it synchronously, // so that we can resolve the correct order without // worrying about some elements not inserted yet var anchor = frag.staggerAnchor; if (!anchor) { anchor = frag.staggerAnchor = createAnchor('stagger-anchor'); anchor.__v_frag = frag; } after(anchor, prevEl); var op = frag.staggerCb = cancellable(function () { frag.staggerCb = null; frag.before(anchor); remove(anchor); }); setTimeout(op, staggerAmount); } else { var target = prevEl.nextSibling; /* istanbul ignore if */ if (!target) { // reset end anchor position in case the position was messed up // by an external drag-n-drop library. after(this.end, prevEl); target = this.end; } frag.before(target); } }, /** * Remove a fragment. Handles staggering. * * @param {Fragment} frag * @param {Number} index * @param {Number} total * @param {Boolean} inDocument */ remove: function remove(frag, index, total, inDocument) { if (frag.staggerCb) { frag.staggerCb.cancel(); frag.staggerCb = null; // it's not possible for the same frag to be removed // twice, so if we have a pending stagger callback, // it means this frag is queued for enter but removed // before its transition started. Since it is already // destroyed, we can just leave it in detached state. return; } var staggerAmount = this.getStagger(frag, index, total, 'leave'); if (inDocument && staggerAmount) { var op = frag.staggerCb = cancellable(function () { frag.staggerCb = null; frag.remove(); }); setTimeout(op, staggerAmount); } else { frag.remove(); } }, /** * Move a fragment to a new position. * Force no transition. * * @param {Fragment} frag * @param {Node} prevEl */ move: function move(frag, prevEl) { // fix a common issue with Sortable: // if prevEl doesn't have nextSibling, this means it's // been dragged after the end anchor. Just re-position // the end anchor to the end of the container. /* istanbul ignore if */ if (!prevEl.nextSibling) { this.end.parentNode.appendChild(this.end); } frag.before(prevEl.nextSibling, false); }, /** * Cache a fragment using track-by or the object key. * * @param {*} value * @param {Fragment} frag * @param {Number} index * @param {String} [key] */ cacheFrag: function cacheFrag(value, frag, index, key) { var trackByKey = this.params.trackBy; var cache = this.cache; var primitive = !isObject(value); var id; if (key || trackByKey || primitive) { id = getTrackByKey(index, key, value, trackByKey); if (!cache[id]) { cache[id] = frag; } else if (trackByKey !== '$index') { process.env.NODE_ENV !== 'production' && this.warnDuplicate(value); } } else { id = this.id; if (hasOwn(value, id)) { if (value[id] === null) { value[id] = frag; } else { process.env.NODE_ENV !== 'production' && this.warnDuplicate(value); } } else if (Object.isExtensible(value)) { def(value, id, frag); } else if (process.env.NODE_ENV !== 'production') { warn('Frozen v-for objects cannot be automatically tracked, make sure to ' + 'provide a track-by key.'); } } frag.raw = value; }, /** * Get a cached fragment from the value/index/key * * @param {*} value * @param {Number} index * @param {String} key * @return {Fragment} */ getCachedFrag: function getCachedFrag(value, index, key) { var trackByKey = this.params.trackBy; var primitive = !isObject(value); var frag; if (key || trackByKey || primitive) { var id = getTrackByKey(index, key, value, trackByKey); frag = this.cache[id]; } else { frag = value[this.id]; } if (frag && (frag.reused || frag.fresh)) { process.env.NODE_ENV !== 'production' && this.warnDuplicate(value); } return frag; }, /** * Delete a fragment from cache. * * @param {Fragment} frag */ deleteCachedFrag: function deleteCachedFrag(frag) { var value = frag.raw; var trackByKey = this.params.trackBy; var scope = frag.scope; var index = scope.$index; // fix #948: avoid accidentally fall through to // a parent repeater which happens to have $key. var key = hasOwn(scope, '$key') && scope.$key; var primitive = !isObject(value); if (trackByKey || key || primitive) { var id = getTrackByKey(index, key, value, trackByKey); this.cache[id] = null; } else { value[this.id] = null; frag.raw = null; } }, /** * Get the stagger amount for an insertion/removal. * * @param {Fragment} frag * @param {Number} index * @param {Number} total * @param {String} type */ getStagger: function getStagger(frag, index, total, type) { type = type + 'Stagger'; var trans = frag.node.__v_trans; var hooks = trans && trans.hooks; var hook = hooks && (hooks[type] || hooks.stagger); return hook ? hook.call(frag, index, total) : index * parseInt(this.params[type] || this.params.stagger, 10); }, /** * Pre-process the value before piping it through the * filters. This is passed to and called by the watcher. */ _preProcess: function _preProcess(value) { // regardless of type, store the un-filtered raw value. this.rawValue = value; return value; }, /** * Post-process the value after it has been piped through * the filters. This is passed to and called by the watcher. * * It is necessary for this to be called during the * wathcer's dependency collection phase because we want * the v-for to update when the source Object is mutated. */ _postProcess: function _postProcess(value) { if (isArray(value)) { return value; } else if (isPlainObject(value)) { // convert plain object to array. var keys = Object.keys(value); var i = keys.length; var res = new Array(i); var key; while (i--) { key = keys[i]; res[i] = { $key: key, $value: value[key] }; } return res; } else { if (typeof value === 'number' && !isNaN(value)) { value = range(value); } return value || []; } }, unbind: function unbind() { if (this.descriptor.ref) { (this._scope || this.vm).$refs[this.descriptor.ref] = null; } if (this.frags) { var i = this.frags.length; var frag; while (i--) { frag = this.frags[i]; this.deleteCachedFrag(frag); frag.destroy(); } } } }; /** * Helper to find the previous element that is a fragment * anchor. This is necessary because a destroyed frag's * element could still be lingering in the DOM before its * leaving transition finishes, but its inserted flag * should have been set to false so we can skip them. * * If this is a block repeat, we want to make sure we only * return frag that is bound to this v-for. (see #929) * * @param {Fragment} frag * @param {Comment|Text} anchor * @param {String} id * @return {Fragment} */ function findPrevFrag(frag, anchor, id) { var el = frag.node.previousSibling; /* istanbul ignore if */ if (!el) return; frag = el.__v_frag; while ((!frag || frag.forId !== id || !frag.inserted) && el !== anchor) { el = el.previousSibling; /* istanbul ignore if */ if (!el) return; frag = el.__v_frag; } return frag; } /** * Find a vm from a fragment. * * @param {Fragment} frag * @return {Vue|undefined} */ function findVmFromFrag(frag) { var node = frag.node; // handle multi-node frag if (frag.end) { while (!node.__vue__ && node !== frag.end && node.nextSibling) { node = node.nextSibling; } } return node.__vue__; } /** * Create a range array from given number. * * @param {Number} n * @return {Array} */ function range(n) { var i = -1; var ret = new Array(Math.floor(n)); while (++i < n) { ret[i] = i; } return ret; } /** * Get the track by key for an item. * * @param {Number} index * @param {String} key * @param {*} value * @param {String} [trackByKey] */ function getTrackByKey(index, key, value, trackByKey) { return trackByKey ? trackByKey === '$index' ? index : trackByKey.charAt(0).match(/\w/) ? getPath(value, trackByKey) : value[trackByKey] : key || value; } if (process.env.NODE_ENV !== 'production') { vFor.warnDuplicate = function (value) { warn('Duplicate value found in v-for="' + this.descriptor.raw + '": ' + JSON.stringify(value) + '. Use track-by="$index" if ' + 'you are expecting duplicate values.', this.vm); }; } var vIf = { priority: IF, terminal: true, bind: function bind() { var el = this.el; if (!el.__vue__) { // check else block var next = el.nextElementSibling; if (next && getAttr(next, 'v-else') !== null) { remove(next); this.elseEl = next; } // check main block this.anchor = createAnchor('v-if'); replace(el, this.anchor); } else { process.env.NODE_ENV !== 'production' && warn('v-if="' + this.expression + '" cannot be ' + 'used on an instance root element.', this.vm); this.invalid = true; } }, update: function update(value) { if (this.invalid) return; if (value) { if (!this.frag) { this.insert(); } } else { this.remove(); } }, insert: function insert() { if (this.elseFrag) { this.elseFrag.remove(); this.elseFrag = null; } // lazy init factory if (!this.factory) { this.factory = new FragmentFactory(this.vm, this.el); } this.frag = this.factory.create(this._host, this._scope, this._frag); this.frag.before(this.anchor); }, remove: function remove() { if (this.frag) { this.frag.remove(); this.frag = null; } if (this.elseEl && !this.elseFrag) { if (!this.elseFactory) { this.elseFactory = new FragmentFactory(this.elseEl._context || this.vm, this.elseEl); } this.elseFrag = this.elseFactory.create(this._host, this._scope, this._frag); this.elseFrag.before(this.anchor); } }, unbind: function unbind() { if (this.frag) { this.frag.destroy(); } if (this.elseFrag) { this.elseFrag.destroy(); } } }; var show = { bind: function bind() { // check else block var next = this.el.nextElementSibling; if (next && getAttr(next, 'v-else') !== null) { this.elseEl = next; } }, update: function update(value) { this.apply(this.el, value); if (this.elseEl) { this.apply(this.elseEl, !value); } }, apply: function apply(el, value) { if (inDoc(el)) { applyTransition(el, value ? 1 : -1, toggle, this.vm); } else { toggle(); } function toggle() { el.style.display = value ? '' : 'none'; } } }; var text$2 = { bind: function bind() { var self = this; var el = this.el; var isRange = el.type === 'range'; var lazy = this.params.lazy; var number = this.params.number; var debounce = this.params.debounce; // handle composition events. // path_to_url // skip this for Android because it handles composition // events quite differently. Android doesn't trigger // composition events for language input methods e.g. // Chinese, but instead triggers them for spelling // suggestions... (see Discussion/#162) var composing = false; if (!isAndroid && !isRange) { this.on('compositionstart', function () { composing = true; }); this.on('compositionend', function () { composing = false; // in IE11 the "compositionend" event fires AFTER // the "input" event, so the input handler is blocked // at the end... have to call it here. // // #1327: in lazy mode this is unecessary. if (!lazy) { self.listener(); } }); } // prevent messing with the input when user is typing, // and force update on blur. this.focused = false; if (!isRange && !lazy) { this.on('focus', function () { self.focused = true; }); this.on('blur', function () { self.focused = false; // do not sync value after fragment removal (#2017) if (!self._frag || self._frag.inserted) { self.rawListener(); } }); } // Now attach the main listener this.listener = this.rawListener = function () { if (composing || !self._bound) { return; } var val = number || isRange ? toNumber(el.value) : el.value; self.set(val); // force update on next tick to avoid lock & same value // also only update when user is not typing nextTick(function () { if (self._bound && !self.focused) { self.update(self._watcher.value); } }); }; // apply debounce if (debounce) { this.listener = _debounce(this.listener, debounce); } // Support jQuery events, since jQuery.trigger() doesn't // trigger native events in some cases and some plugins // rely on $.trigger() // // We want to make sure if a listener is attached using // jQuery, it is also removed with jQuery, that's why // we do the check for each directive instance and // store that check result on itself. This also allows // easier test coverage control by unsetting the global // jQuery variable in tests. this.hasjQuery = typeof jQuery === 'function'; if (this.hasjQuery) { var method = jQuery.fn.on ? 'on' : 'bind'; jQuery(el)[method]('change', this.rawListener); if (!lazy) { jQuery(el)[method]('input', this.listener); } } else { this.on('change', this.rawListener); if (!lazy) { this.on('input', this.listener); } } // IE9 doesn't fire input event on backspace/del/cut if (!lazy && isIE9) { this.on('cut', function () { nextTick(self.listener); }); this.on('keyup', function (e) { if (e.keyCode === 46 || e.keyCode === 8) { self.listener(); } }); } // set initial value if present if (el.hasAttribute('value') || el.tagName === 'TEXTAREA' && el.value.trim()) { this.afterBind = this.listener; } }, update: function update(value) { this.el.value = _toString(value); }, unbind: function unbind() { var el = this.el; if (this.hasjQuery) { var method = jQuery.fn.off ? 'off' : 'unbind'; jQuery(el)[method]('change', this.listener); jQuery(el)[method]('input', this.listener); } } }; var radio = { bind: function bind() { var self = this; var el = this.el; this.getValue = function () { // value overwrite via v-bind:value if (el.hasOwnProperty('_value')) { return el._value; } var val = el.value; if (self.params.number) { val = toNumber(val); } return val; }; this.listener = function () { self.set(self.getValue()); }; this.on('change', this.listener); if (el.hasAttribute('checked')) { this.afterBind = this.listener; } }, update: function update(value) { this.el.checked = looseEqual(value, this.getValue()); } }; var select = { bind: function bind() { var self = this; var el = this.el; // method to force update DOM using latest value. this.forceUpdate = function () { if (self._watcher) { self.update(self._watcher.get()); } }; // check if this is a multiple select var multiple = this.multiple = el.hasAttribute('multiple'); // attach listener this.listener = function () { var value = getValue(el, multiple); value = self.params.number ? isArray(value) ? value.map(toNumber) : toNumber(value) : value; self.set(value); }; this.on('change', this.listener); // if has initial value, set afterBind var initValue = getValue(el, multiple, true); if (multiple && initValue.length || !multiple && initValue !== null) { this.afterBind = this.listener; } // All major browsers except Firefox resets // selectedIndex with value -1 to 0 when the element // is appended to a new parent, therefore we have to // force a DOM update whenever that happens... this.vm.$on('hook:attached', this.forceUpdate); }, update: function update(value) { var el = this.el; el.selectedIndex = -1; var multi = this.multiple && isArray(value); var options = el.options; var i = options.length; var op, val; while (i--) { op = options[i]; val = op.hasOwnProperty('_value') ? op._value : op.value; /* eslint-disable eqeqeq */ op.selected = multi ? indexOf$1(value, val) > -1 : looseEqual(value, val); /* eslint-enable eqeqeq */ } }, unbind: function unbind() { /* istanbul ignore next */ this.vm.$off('hook:attached', this.forceUpdate); } }; /** * Get select value * * @param {SelectElement} el * @param {Boolean} multi * @param {Boolean} init * @return {Array|*} */ function getValue(el, multi, init) { var res = multi ? [] : null; var op, val, selected; for (var i = 0, l = el.options.length; i < l; i++) { op = el.options[i]; selected = init ? op.hasAttribute('selected') : op.selected; if (selected) { val = op.hasOwnProperty('_value') ? op._value : op.value; if (multi) { res.push(val); } else { return val; } } } return res; } /** * Native Array.indexOf uses strict equal, but in this * case we need to match string/numbers with custom equal. * * @param {Array} arr * @param {*} val */ function indexOf$1(arr, val) { var i = arr.length; while (i--) { if (looseEqual(arr[i], val)) { return i; } } return -1; } var checkbox = { bind: function bind() { var self = this; var el = this.el; this.getValue = function () { return el.hasOwnProperty('_value') ? el._value : self.params.number ? toNumber(el.value) : el.value; }; function getBooleanValue() { var val = el.checked; if (val && el.hasOwnProperty('_trueValue')) { return el._trueValue; } if (!val && el.hasOwnProperty('_falseValue')) { return el._falseValue; } return val; } this.listener = function () { var model = self._watcher.value; if (isArray(model)) { var val = self.getValue(); if (el.checked) { if (indexOf(model, val) < 0) { model.push(val); } } else { model.$remove(val); } } else { self.set(getBooleanValue()); } }; this.on('change', this.listener); if (el.hasAttribute('checked')) { this.afterBind = this.listener; } }, update: function update(value) { var el = this.el; if (isArray(value)) { el.checked = indexOf(value, this.getValue()) > -1; } else { if (el.hasOwnProperty('_trueValue')) { el.checked = looseEqual(value, el._trueValue); } else { el.checked = !!value; } } } }; var handlers = { text: text$2, radio: radio, select: select, checkbox: checkbox }; var model = { priority: MODEL, twoWay: true, handlers: handlers, params: ['lazy', 'number', 'debounce'], /** * Possible elements: * <select> * <textarea> * <input type="*"> * - text * - checkbox * - radio * - number */ bind: function bind() { // friendly warning... this.checkFilters(); if (this.hasRead && !this.hasWrite) { process.env.NODE_ENV !== 'production' && warn('It seems you are using a read-only filter with ' + 'v-model="' + this.descriptor.raw + '". ' + 'You might want to use a two-way filter to ensure correct behavior.', this.vm); } var el = this.el; var tag = el.tagName; var handler; if (tag === 'INPUT') { handler = handlers[el.type] || handlers.text; } else if (tag === 'SELECT') { handler = handlers.select; } else if (tag === 'TEXTAREA') { handler = handlers.text; } else { process.env.NODE_ENV !== 'production' && warn('v-model does not support element type: ' + tag, this.vm); return; } el.__v_model = this; handler.bind.call(this); this.update = handler.update; this._unbind = handler.unbind; }, /** * Check read/write filter stats. */ checkFilters: function checkFilters() { var filters = this.filters; if (!filters) return; var i = filters.length; while (i--) { var filter = resolveAsset(this.vm.$options, 'filters', filters[i].name); if (typeof filter === 'function' || filter.read) { this.hasRead = true; } if (filter.write) { this.hasWrite = true; } } }, unbind: function unbind() { this.el.__v_model = null; this._unbind && this._unbind(); } }; // keyCode aliases var keyCodes = { esc: 27, tab: 9, enter: 13, space: 32, 'delete': [8, 46], up: 38, left: 37, right: 39, down: 40 }; function keyFilter(handler, keys) { var codes = keys.map(function (key) { var charCode = key.charCodeAt(0); if (charCode > 47 && charCode < 58) { return parseInt(key, 10); } if (key.length === 1) { charCode = key.toUpperCase().charCodeAt(0); if (charCode > 64 && charCode < 91) { return charCode; } } return keyCodes[key]; }); codes = [].concat.apply([], codes); return function keyHandler(e) { if (codes.indexOf(e.keyCode) > -1) { return handler.call(this, e); } }; } function stopFilter(handler) { return function stopHandler(e) { e.stopPropagation(); return handler.call(this, e); }; } function preventFilter(handler) { return function preventHandler(e) { e.preventDefault(); return handler.call(this, e); }; } function selfFilter(handler) { return function selfHandler(e) { if (e.target === e.currentTarget) { return handler.call(this, e); } }; } var on$1 = { priority: ON, acceptStatement: true, keyCodes: keyCodes, bind: function bind() { // deal with iframes if (this.el.tagName === 'IFRAME' && this.arg !== 'load') { var self = this; this.iframeBind = function () { on(self.el.contentWindow, self.arg, self.handler, self.modifiers.capture); }; this.on('load', this.iframeBind); } }, update: function update(handler) { // stub a noop for v-on with no value, // e.g. @mousedown.prevent if (!this.descriptor.raw) { handler = function () {}; } if (typeof handler !== 'function') { process.env.NODE_ENV !== 'production' && warn('v-on:' + this.arg + '="' + this.expression + '" expects a function value, ' + 'got ' + handler, this.vm); return; } // apply modifiers if (this.modifiers.stop) { handler = stopFilter(handler); } if (this.modifiers.prevent) { handler = preventFilter(handler); } if (this.modifiers.self) { handler = selfFilter(handler); } // key filter var keys = Object.keys(this.modifiers).filter(function (key) { return key !== 'stop' && key !== 'prevent' && key !== 'self' && key !== 'capture'; }); if (keys.length) { handler = keyFilter(handler, keys); } this.reset(); this.handler = handler; if (this.iframeBind) { this.iframeBind(); } else { on(this.el, this.arg, this.handler, this.modifiers.capture); } }, reset: function reset() { var el = this.iframeBind ? this.el.contentWindow : this.el; if (this.handler) { off(el, this.arg, this.handler); } }, unbind: function unbind() { this.reset(); } }; var prefixes = ['-webkit-', '-moz-', '-ms-']; var camelPrefixes = ['Webkit', 'Moz', 'ms']; var importantRE = /!important;?$/; var propCache = Object.create(null); var testEl = null; var style = { deep: true, update: function update(value) { if (typeof value === 'string') { this.el.style.cssText = value; } else if (isArray(value)) { this.handleObject(value.reduce(extend, {})); } else { this.handleObject(value || {}); } }, handleObject: function handleObject(value) { // cache object styles so that only changed props // are actually updated. var cache = this.cache || (this.cache = {}); var name, val; for (name in cache) { if (!(name in value)) { this.handleSingle(name, null); delete cache[name]; } } for (name in value) { val = value[name]; if (val !== cache[name]) { cache[name] = val; this.handleSingle(name, val); } } }, handleSingle: function handleSingle(prop, value) { prop = normalize(prop); if (!prop) return; // unsupported prop // cast possible numbers/booleans into strings if (value != null) value += ''; if (value) { var isImportant = importantRE.test(value) ? 'important' : ''; if (isImportant) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { warn('It\'s probably a bad idea to use !important with inline rules. ' + 'This feature will be deprecated in a future version of Vue.'); } value = value.replace(importantRE, '').trim(); this.el.style.setProperty(prop.kebab, value, isImportant); } else { this.el.style[prop.camel] = value; } } else { this.el.style[prop.camel] = ''; } } }; /** * Normalize a CSS property name. * - cache result * - auto prefix * - camelCase -> dash-case * * @param {String} prop * @return {String} */ function normalize(prop) { if (propCache[prop]) { return propCache[prop]; } var res = prefix(prop); propCache[prop] = propCache[res] = res; return res; } /** * Auto detect the appropriate prefix for a CSS property. * path_to_url * * @param {String} prop * @return {String} */ function prefix(prop) { prop = hyphenate(prop); var camel = camelize(prop); var upper = camel.charAt(0).toUpperCase() + camel.slice(1); if (!testEl) { testEl = document.createElement('div'); } var i = prefixes.length; var prefixed; if (camel !== 'filter' && camel in testEl.style) { return { kebab: prop, camel: camel }; } while (i--) { prefixed = camelPrefixes[i] + upper; if (prefixed in testEl.style) { return { kebab: prefixes[i] + prop, camel: prefixed }; } } } // xlink var xlinkNS = 'path_to_url var xlinkRE = /^xlink:/; // check for attributes that prohibit interpolations var disallowedInterpAttrRE = /^v-|^:|^@|^(?:is|transition|transition-mode|debounce|track-by|stagger|enter-stagger|leave-stagger)$/; // these attributes should also set their corresponding properties // because they only affect the initial state of the element var attrWithPropsRE = /^(?:value|checked|selected|muted)$/; // these attributes expect enumrated values of "true" or "false" // but are not boolean attributes var enumeratedAttrRE = /^(?:draggable|contenteditable|spellcheck)$/; // these attributes should set a hidden property for // binding v-model to object values var modelProps = { value: '_value', 'true-value': '_trueValue', 'false-value': '_falseValue' }; var bind$1 = { priority: BIND, bind: function bind() { var attr = this.arg; var tag = this.el.tagName; // should be deep watch on object mode if (!attr) { this.deep = true; } // handle interpolation bindings var descriptor = this.descriptor; var tokens = descriptor.interp; if (tokens) { // handle interpolations with one-time tokens if (descriptor.hasOneTime) { this.expression = tokensToExp(tokens, this._scope || this.vm); } // only allow binding on native attributes if (disallowedInterpAttrRE.test(attr) || attr === 'name' && (tag === 'PARTIAL' || tag === 'SLOT')) { process.env.NODE_ENV !== 'production' && warn(attr + '="' + descriptor.raw + '": ' + 'attribute interpolation is not allowed in Vue.js ' + 'directives and special attributes.', this.vm); this.el.removeAttribute(attr); this.invalid = true; } /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { var raw = attr + '="' + descriptor.raw + '": '; // warn src if (attr === 'src') { warn(raw + 'interpolation in "src" attribute will cause ' + 'a 404 request. Use v-bind:src instead.', this.vm); } // warn style if (attr === 'style') { warn(raw + 'interpolation in "style" attribute will cause ' + 'the attribute to be discarded in Internet Explorer. ' + 'Use v-bind:style instead.', this.vm); } } } }, update: function update(value) { if (this.invalid) { return; } var attr = this.arg; if (this.arg) { this.handleSingle(attr, value); } else { this.handleObject(value || {}); } }, // share object handler with v-bind:class handleObject: style.handleObject, handleSingle: function handleSingle(attr, value) { var el = this.el; var interp = this.descriptor.interp; if (this.modifiers.camel) { attr = camelize(attr); } if (!interp && attrWithPropsRE.test(attr) && attr in el) { var attrValue = attr === 'value' ? value == null // IE9 will set input.value to "null" for null... ? '' : value : value; if (el[attr] !== attrValue) { el[attr] = attrValue; } } // set model props var modelProp = modelProps[attr]; if (!interp && modelProp) { el[modelProp] = value; // update v-model if present var model = el.__v_model; if (model) { model.listener(); } } // do not set value attribute for textarea if (attr === 'value' && el.tagName === 'TEXTAREA') { el.removeAttribute(attr); return; } // update attribute if (enumeratedAttrRE.test(attr)) { el.setAttribute(attr, value ? 'true' : 'false'); } else if (value != null && value !== false) { if (attr === 'class') { // handle edge case #1960: // class interpolation should not overwrite Vue transition class if (el.__v_trans) { value += ' ' + el.__v_trans.id + '-transition'; } setClass(el, value); } else if (xlinkRE.test(attr)) { el.setAttributeNS(xlinkNS, attr, value === true ? '' : value); } else { el.setAttribute(attr, value === true ? '' : value); } } else { el.removeAttribute(attr); } } }; var el = { priority: EL, bind: function bind() { /* istanbul ignore if */ if (!this.arg) { return; } var id = this.id = camelize(this.arg); var refs = (this._scope || this.vm).$els; if (hasOwn(refs, id)) { refs[id] = this.el; } else { defineReactive(refs, id, this.el); } }, unbind: function unbind() { var refs = (this._scope || this.vm).$els; if (refs[this.id] === this.el) { refs[this.id] = null; } } }; var ref = { bind: function bind() { process.env.NODE_ENV !== 'production' && warn('v-ref:' + this.arg + ' must be used on a child ' + 'component. Found on <' + this.el.tagName.toLowerCase() + '>.', this.vm); } }; var cloak = { bind: function bind() { var el = this.el; this.vm.$once('pre-hook:compiled', function () { el.removeAttribute('v-cloak'); }); } }; // must export plain object var directives = { text: text$1, html: html, 'for': vFor, 'if': vIf, show: show, model: model, on: on$1, bind: bind$1, el: el, ref: ref, cloak: cloak }; var vClass = { deep: true, update: function update(value) { if (!value) { this.cleanup(); } else if (typeof value === 'string') { this.setClass(value.trim().split(/\s+/)); } else { this.setClass(normalize$1(value)); } }, setClass: function setClass(value) { this.cleanup(value); for (var i = 0, l = value.length; i < l; i++) { var val = value[i]; if (val) { apply(this.el, val, addClass); } } this.prevKeys = value; }, cleanup: function cleanup(value) { var prevKeys = this.prevKeys; if (!prevKeys) return; var i = prevKeys.length; while (i--) { var key = prevKeys[i]; if (!value || value.indexOf(key) < 0) { apply(this.el, key, removeClass); } } } }; /** * Normalize objects and arrays (potentially containing objects) * into array of strings. * * @param {Object|Array<String|Object>} value * @return {Array<String>} */ function normalize$1(value) { var res = []; if (isArray(value)) { for (var i = 0, l = value.length; i < l; i++) { var _key = value[i]; if (_key) { if (typeof _key === 'string') { res.push(_key); } else { for (var k in _key) { if (_key[k]) res.push(k); } } } } } else if (isObject(value)) { for (var key in value) { if (value[key]) res.push(key); } } return res; } /** * Add or remove a class/classes on an element * * @param {Element} el * @param {String} key The class name. This may or may not * contain a space character, in such a * case we'll deal with multiple class * names at once. * @param {Function} fn */ function apply(el, key, fn) { key = key.trim(); if (key.indexOf(' ') === -1) { fn(el, key); return; } // The key contains one or more space characters. // Since a class name doesn't accept such characters, we // treat it as multiple classes. var keys = key.split(/\s+/); for (var i = 0, l = keys.length; i < l; i++) { fn(el, keys[i]); } } var component = { priority: COMPONENT, params: ['keep-alive', 'transition-mode', 'inline-template'], /** * Setup. Two possible usages: * * - static: * <comp> or <div v-component="comp"> * * - dynamic: * <component :is="view"> */ bind: function bind() { if (!this.el.__vue__) { // keep-alive cache this.keepAlive = this.params.keepAlive; if (this.keepAlive) { this.cache = {}; } // check inline-template if (this.params.inlineTemplate) { // extract inline template as a DocumentFragment this.inlineTemplate = extractContent(this.el, true); } // component resolution related state this.pendingComponentCb = this.Component = null; // transition related state this.pendingRemovals = 0; this.pendingRemovalCb = null; // create a ref anchor this.anchor = createAnchor('v-component'); replace(this.el, this.anchor); // remove is attribute. // this is removed during compilation, but because compilation is // cached, when the component is used elsewhere this attribute // will remain at link time. this.el.removeAttribute('is'); this.el.removeAttribute(':is'); // remove ref, same as above if (this.descriptor.ref) { this.el.removeAttribute('v-ref:' + hyphenate(this.descriptor.ref)); } // if static, build right now. if (this.literal) { this.setComponent(this.expression); } } else { process.env.NODE_ENV !== 'production' && warn('cannot mount component "' + this.expression + '" ' + 'on already mounted element: ' + this.el); } }, /** * Public update, called by the watcher in the dynamic * literal scenario, e.g. <component :is="view"> */ update: function update(value) { if (!this.literal) { this.setComponent(value); } }, /** * Switch dynamic components. May resolve the component * asynchronously, and perform transition based on * specified transition mode. Accepts a few additional * arguments specifically for vue-router. * * The callback is called when the full transition is * finished. * * @param {String} value * @param {Function} [cb] */ setComponent: function setComponent(value, cb) { this.invalidatePending(); if (!value) { // just remove current this.unbuild(true); this.remove(this.childVM, cb); this.childVM = null; } else { var self = this; this.resolveComponent(value, function () { self.mountComponent(cb); }); } }, /** * Resolve the component constructor to use when creating * the child vm. * * @param {String|Function} value * @param {Function} cb */ resolveComponent: function resolveComponent(value, cb) { var self = this; this.pendingComponentCb = cancellable(function (Component) { self.ComponentName = Component.options.name || (typeof value === 'string' ? value : null); self.Component = Component; cb(); }); this.vm._resolveComponent(value, this.pendingComponentCb); }, /** * Create a new instance using the current constructor and * replace the existing instance. This method doesn't care * whether the new component and the old one are actually * the same. * * @param {Function} [cb] */ mountComponent: function mountComponent(cb) { // actual mount this.unbuild(true); var self = this; var activateHooks = this.Component.options.activate; var cached = this.getCached(); var newComponent = this.build(); if (activateHooks && !cached) { this.waitingFor = newComponent; callActivateHooks(activateHooks, newComponent, function () { if (self.waitingFor !== newComponent) { return; } self.waitingFor = null; self.transition(newComponent, cb); }); } else { // update ref for kept-alive component if (cached) { newComponent._updateRef(); } this.transition(newComponent, cb); } }, /** * When the component changes or unbinds before an async * constructor is resolved, we need to invalidate its * pending callback. */ invalidatePending: function invalidatePending() { if (this.pendingComponentCb) { this.pendingComponentCb.cancel(); this.pendingComponentCb = null; } }, /** * Instantiate/insert a new child vm. * If keep alive and has cached instance, insert that * instance; otherwise build a new one and cache it. * * @param {Object} [extraOptions] * @return {Vue} - the created instance */ build: function build(extraOptions) { var cached = this.getCached(); if (cached) { return cached; } if (this.Component) { // default options var options = { name: this.ComponentName, el: cloneNode(this.el), template: this.inlineTemplate, // make sure to add the child with correct parent // if this is a transcluded component, its parent // should be the transclusion host. parent: this._host || this.vm, // if no inline-template, then the compiled // linker can be cached for better performance. _linkerCachable: !this.inlineTemplate, _ref: this.descriptor.ref, _asComponent: true, _isRouterView: this._isRouterView, // if this is a transcluded component, context // will be the common parent vm of this instance // and its host. _context: this.vm, // if this is inside an inline v-for, the scope // will be the intermediate scope created for this // repeat fragment. this is used for linking props // and container directives. _scope: this._scope, // pass in the owner fragment of this component. // this is necessary so that the fragment can keep // track of its contained components in order to // call attach/detach hooks for them. _frag: this._frag }; // extra options // in 1.0.0 this is used by vue-router only /* istanbul ignore if */ if (extraOptions) { extend(options, extraOptions); } var child = new this.Component(options); if (this.keepAlive) { this.cache[this.Component.cid] = child; } /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && this.el.hasAttribute('transition') && child._isFragment) { warn('Transitions will not work on a fragment instance. ' + 'Template: ' + child.$options.template, child); } return child; } }, /** * Try to get a cached instance of the current component. * * @return {Vue|undefined} */ getCached: function getCached() { return this.keepAlive && this.cache[this.Component.cid]; }, /** * Teardown the current child, but defers cleanup so * that we can separate the destroy and removal steps. * * @param {Boolean} defer */ unbuild: function unbuild(defer) { if (this.waitingFor) { if (!this.keepAlive) { this.waitingFor.$destroy(); } this.waitingFor = null; } var child = this.childVM; if (!child || this.keepAlive) { if (child) { // remove ref child._inactive = true; child._updateRef(true); } return; } // the sole purpose of `deferCleanup` is so that we can // "deactivate" the vm right now and perform DOM removal // later. child.$destroy(false, defer); }, /** * Remove current destroyed child and manually do * the cleanup after removal. * * @param {Function} cb */ remove: function remove(child, cb) { var keepAlive = this.keepAlive; if (child) { // we may have a component switch when a previous // component is still being transitioned out. // we want to trigger only one lastest insertion cb // when the existing transition finishes. (#1119) this.pendingRemovals++; this.pendingRemovalCb = cb; var self = this; child.$remove(function () { self.pendingRemovals--; if (!keepAlive) child._cleanup(); if (!self.pendingRemovals && self.pendingRemovalCb) { self.pendingRemovalCb(); self.pendingRemovalCb = null; } }); } else if (cb) { cb(); } }, /** * Actually swap the components, depending on the * transition mode. Defaults to simultaneous. * * @param {Vue} target * @param {Function} [cb] */ transition: function transition(target, cb) { var self = this; var current = this.childVM; // for devtool inspection if (current) current._inactive = true; target._inactive = false; this.childVM = target; switch (self.params.transitionMode) { case 'in-out': target.$before(self.anchor, function () { self.remove(current, cb); }); break; case 'out-in': self.remove(current, function () { target.$before(self.anchor, cb); }); break; default: self.remove(current); target.$before(self.anchor, cb); } }, /** * Unbind. */ unbind: function unbind() { this.invalidatePending(); // Do not defer cleanup when unbinding this.unbuild(); // destroy all keep-alive cached instances if (this.cache) { for (var key in this.cache) { this.cache[key].$destroy(); } this.cache = null; } } }; /** * Call activate hooks in order (asynchronous) * * @param {Array} hooks * @param {Vue} vm * @param {Function} cb */ function callActivateHooks(hooks, vm, cb) { var total = hooks.length; var called = 0; hooks[0].call(vm, next); function next() { if (++called >= total) { cb(); } else { hooks[called].call(vm, next); } } } var propBindingModes = config._propBindingModes; var empty = {}; // regexes var identRE$1 = /^[$_a-zA-Z]+[\w$]*$/; var settablePathRE = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*|\[[^\[\]]+\])*$/; /** * Compile props on a root element and return * a props link function. * * @param {Element|DocumentFragment} el * @param {Array} propOptions * @param {Vue} vm * @return {Function} propsLinkFn */ function compileProps(el, propOptions, vm) { var props = []; var names = Object.keys(propOptions); var i = names.length; var options, name, attr, value, path, parsed, prop; while (i--) { name = names[i]; options = propOptions[name] || empty; if (process.env.NODE_ENV !== 'production' && name === '$data') { warn('Do not use $data as prop.', vm); continue; } // props could contain dashes, which will be // interpreted as minus calculations by the parser // so we need to camelize the path here path = camelize(name); if (!identRE$1.test(path)) { process.env.NODE_ENV !== 'production' && warn('Invalid prop key: "' + name + '". Prop keys ' + 'must be valid identifiers.', vm); continue; } prop = { name: name, path: path, options: options, mode: propBindingModes.ONE_WAY, raw: null }; attr = hyphenate(name); // first check dynamic version if ((value = getBindAttr(el, attr)) === null) { if ((value = getBindAttr(el, attr + '.sync')) !== null) { prop.mode = propBindingModes.TWO_WAY; } else if ((value = getBindAttr(el, attr + '.once')) !== null) { prop.mode = propBindingModes.ONE_TIME; } } if (value !== null) { // has dynamic binding! prop.raw = value; parsed = parseDirective(value); value = parsed.expression; prop.filters = parsed.filters; // check binding type if (isLiteral(value) && !parsed.filters) { // for expressions containing literal numbers and // booleans, there's no need to setup a prop binding, // so we can optimize them as a one-time set. prop.optimizedLiteral = true; } else { prop.dynamic = true; // check non-settable path for two-way bindings if (process.env.NODE_ENV !== 'production' && prop.mode === propBindingModes.TWO_WAY && !settablePathRE.test(value)) { prop.mode = propBindingModes.ONE_WAY; warn('Cannot bind two-way prop with non-settable ' + 'parent path: ' + value, vm); } } prop.parentPath = value; // warn required two-way if (process.env.NODE_ENV !== 'production' && options.twoWay && prop.mode !== propBindingModes.TWO_WAY) { warn('Prop "' + name + '" expects a two-way binding type.', vm); } } else if ((value = getAttr(el, attr)) !== null) { // has literal binding! prop.raw = value; } else if (process.env.NODE_ENV !== 'production') { // check possible camelCase prop usage var lowerCaseName = path.toLowerCase(); value = /[A-Z\-]/.test(name) && (el.getAttribute(lowerCaseName) || el.getAttribute(':' + lowerCaseName) || el.getAttribute('v-bind:' + lowerCaseName) || el.getAttribute(':' + lowerCaseName + '.once') || el.getAttribute('v-bind:' + lowerCaseName + '.once') || el.getAttribute(':' + lowerCaseName + '.sync') || el.getAttribute('v-bind:' + lowerCaseName + '.sync')); if (value) { warn('Possible usage error for prop `' + lowerCaseName + '` - ' + 'did you mean `' + attr + '`? HTML is case-insensitive, remember to use ' + 'kebab-case for props in templates.', vm); } else if (options.required) { // warn missing required warn('Missing required prop: ' + name, vm); } } // push prop props.push(prop); } return makePropsLinkFn(props); } /** * Build a function that applies props to a vm. * * @param {Array} props * @return {Function} propsLinkFn */ function makePropsLinkFn(props) { return function propsLinkFn(vm, scope) { // store resolved props info vm._props = {}; var inlineProps = vm.$options.propsData; var i = props.length; var prop, path, options, value, raw; while (i--) { prop = props[i]; raw = prop.raw; path = prop.path; options = prop.options; vm._props[path] = prop; if (inlineProps && hasOwn(inlineProps, path)) { initProp(vm, prop, inlineProps[path]); }if (raw === null) { // initialize absent prop initProp(vm, prop, undefined); } else if (prop.dynamic) { // dynamic prop if (prop.mode === propBindingModes.ONE_TIME) { // one time binding value = (scope || vm._context || vm).$get(prop.parentPath); initProp(vm, prop, value); } else { if (vm._context) { // dynamic binding vm._bindDir({ name: 'prop', def: propDef, prop: prop }, null, null, scope); // el, host, scope } else { // root instance initProp(vm, prop, vm.$get(prop.parentPath)); } } } else if (prop.optimizedLiteral) { // optimized literal, cast it and just set once var stripped = stripQuotes(raw); value = stripped === raw ? toBoolean(toNumber(raw)) : stripped; initProp(vm, prop, value); } else { // string literal, but we need to cater for // Boolean props with no value, or with same // literal value (e.g. disabled="disabled") // see path_to_url value = options.type === Boolean && (raw === '' || raw === hyphenate(prop.name)) ? true : raw; initProp(vm, prop, value); } } }; } /** * Process a prop with a rawValue, applying necessary coersions, * default values & assertions and call the given callback with * processed value. * * @param {Vue} vm * @param {Object} prop * @param {*} rawValue * @param {Function} fn */ function processPropValue(vm, prop, rawValue, fn) { var isSimple = prop.dynamic && isSimplePath(prop.parentPath); var value = rawValue; if (value === undefined) { value = getPropDefaultValue(vm, prop); } value = coerceProp(prop, value); var coerced = value !== rawValue; if (!assertProp(prop, value, vm)) { value = undefined; } if (isSimple && !coerced) { withoutConversion(function () { fn(value); }); } else { fn(value); } } /** * Set a prop's initial value on a vm and its data object. * * @param {Vue} vm * @param {Object} prop * @param {*} value */ function initProp(vm, prop, value) { processPropValue(vm, prop, value, function (value) { defineReactive(vm, prop.path, value); }); } /** * Update a prop's value on a vm. * * @param {Vue} vm * @param {Object} prop * @param {*} value */ function updateProp(vm, prop, value) { processPropValue(vm, prop, value, function (value) { vm[prop.path] = value; }); } /** * Get the default value of a prop. * * @param {Vue} vm * @param {Object} prop * @return {*} */ function getPropDefaultValue(vm, prop) { // no default, return undefined var options = prop.options; if (!hasOwn(options, 'default')) { // absent boolean value defaults to false return options.type === Boolean ? false : undefined; } var def = options['default']; // warn against non-factory defaults for Object & Array if (isObject(def)) { process.env.NODE_ENV !== 'production' && warn('Invalid default value for prop "' + prop.name + '": ' + 'Props with type Object/Array must use a factory function ' + 'to return the default value.', vm); } // call factory function for non-Function types return typeof def === 'function' && options.type !== Function ? def.call(vm) : def; } /** * Assert whether a prop is valid. * * @param {Object} prop * @param {*} value * @param {Vue} vm */ function assertProp(prop, value, vm) { if (!prop.options.required && ( // non-required prop.raw === null || // abscent value == null) // null or undefined ) { return true; } var options = prop.options; var type = options.type; var valid = !type; var expectedTypes = []; if (type) { if (!isArray(type)) { type = [type]; } for (var i = 0; i < type.length && !valid; i++) { var assertedType = assertType(value, type[i]); expectedTypes.push(assertedType.expectedType); valid = assertedType.valid; } } if (!valid) { if (process.env.NODE_ENV !== 'production') { warn('Invalid prop: type check failed for prop "' + prop.name + '".' + ' Expected ' + expectedTypes.map(formatType).join(', ') + ', got ' + formatValue(value) + '.', vm); } return false; } var validator = options.validator; if (validator) { if (!validator(value)) { process.env.NODE_ENV !== 'production' && warn('Invalid prop: custom validator check failed for prop "' + prop.name + '".', vm); return false; } } return true; } /** * Force parsing value with coerce option. * * @param {*} value * @param {Object} options * @return {*} */ function coerceProp(prop, value) { var coerce = prop.options.coerce; if (!coerce) { return value; } // coerce is a function return coerce(value); } /** * Assert the type of a value * * @param {*} value * @param {Function} type * @return {Object} */ function assertType(value, type) { var valid; var expectedType; if (type === String) { expectedType = 'string'; valid = typeof value === expectedType; } else if (type === Number) { expectedType = 'number'; valid = typeof value === expectedType; } else if (type === Boolean) { expectedType = 'boolean'; valid = typeof value === expectedType; } else if (type === Function) { expectedType = 'function'; valid = typeof value === expectedType; } else if (type === Object) { expectedType = 'object'; valid = isPlainObject(value); } else if (type === Array) { expectedType = 'array'; valid = isArray(value); } else { valid = value instanceof type; } return { valid: valid, expectedType: expectedType }; } /** * Format type for output * * @param {String} type * @return {String} */ function formatType(type) { return type ? type.charAt(0).toUpperCase() + type.slice(1) : 'custom type'; } /** * Format value * * @param {*} value * @return {String} */ function formatValue(val) { return Object.prototype.toString.call(val).slice(8, -1); } var bindingModes = config._propBindingModes; var propDef = { bind: function bind() { var child = this.vm; var parent = child._context; // passed in from compiler directly var prop = this.descriptor.prop; var childKey = prop.path; var parentKey = prop.parentPath; var twoWay = prop.mode === bindingModes.TWO_WAY; var parentWatcher = this.parentWatcher = new Watcher(parent, parentKey, function (val) { updateProp(child, prop, val); }, { twoWay: twoWay, filters: prop.filters, // important: props need to be observed on the // v-for scope if present scope: this._scope }); // set the child initial value. initProp(child, prop, parentWatcher.value); // setup two-way binding if (twoWay) { // important: defer the child watcher creation until // the created hook (after data observation) var self = this; child.$once('pre-hook:created', function () { self.childWatcher = new Watcher(child, childKey, function (val) { parentWatcher.set(val); }, { // ensure sync upward before parent sync down. // this is necessary in cases e.g. the child // mutates a prop array, then replaces it. (#1683) sync: true }); }); } }, unbind: function unbind() { this.parentWatcher.teardown(); if (this.childWatcher) { this.childWatcher.teardown(); } } }; var queue$1 = []; var queued = false; /** * Push a job into the queue. * * @param {Function} job */ function pushJob(job) { queue$1.push(job); if (!queued) { queued = true; nextTick(flush); } } /** * Flush the queue, and do one forced reflow before * triggering transitions. */ function flush() { // Force layout var f = document.documentElement.offsetHeight; for (var i = 0; i < queue$1.length; i++) { queue$1[i](); } queue$1 = []; queued = false; // dummy return, so js linters don't complain about // unused variable f return f; } var TYPE_TRANSITION = 'transition'; var TYPE_ANIMATION = 'animation'; var transDurationProp = transitionProp + 'Duration'; var animDurationProp = animationProp + 'Duration'; /** * If a just-entered element is applied the * leave class while its enter transition hasn't started yet, * and the transitioned property has the same value for both * enter/leave, then the leave transition will be skipped and * the transitionend event never fires. This function ensures * its callback to be called after a transition has started * by waiting for double raf. * * It falls back to setTimeout on devices that support CSS * transitions but not raf (e.g. Android 4.2 browser) - since * these environments are usually slow, we are giving it a * relatively large timeout. */ var raf = inBrowser && window.requestAnimationFrame; var waitForTransitionStart = raf /* istanbul ignore next */ ? function (fn) { raf(function () { raf(fn); }); } : function (fn) { setTimeout(fn, 50); }; /** * A Transition object that encapsulates the state and logic * of the transition. * * @param {Element} el * @param {String} id * @param {Object} hooks * @param {Vue} vm */ function Transition(el, id, hooks, vm) { this.id = id; this.el = el; this.enterClass = hooks && hooks.enterClass || id + '-enter'; this.leaveClass = hooks && hooks.leaveClass || id + '-leave'; this.hooks = hooks; this.vm = vm; // async state this.pendingCssEvent = this.pendingCssCb = this.cancel = this.pendingJsCb = this.op = this.cb = null; this.justEntered = false; this.entered = this.left = false; this.typeCache = {}; // check css transition type this.type = hooks && hooks.type; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { if (this.type && this.type !== TYPE_TRANSITION && this.type !== TYPE_ANIMATION) { warn('invalid CSS transition type for transition="' + this.id + '": ' + this.type, vm); } } // bind var self = this;['enterNextTick', 'enterDone', 'leaveNextTick', 'leaveDone'].forEach(function (m) { self[m] = bind(self[m], self); }); } var p$1 = Transition.prototype; /** * Start an entering transition. * * 1. enter transition triggered * 2. call beforeEnter hook * 3. add enter class * 4. insert/show element * 5. call enter hook (with possible explicit js callback) * 6. reflow * 7. based on transition type: * - transition: * remove class now, wait for transitionend, * then done if there's no explicit js callback. * - animation: * wait for animationend, remove class, * then done if there's no explicit js callback. * - no css transition: * done now if there's no explicit js callback. * 8. wait for either done or js callback, then call * afterEnter hook. * * @param {Function} op - insert/show the element * @param {Function} [cb] */ p$1.enter = function (op, cb) { this.cancelPending(); this.callHook('beforeEnter'); this.cb = cb; addClass(this.el, this.enterClass); op(); this.entered = false; this.callHookWithCb('enter'); if (this.entered) { return; // user called done synchronously. } this.cancel = this.hooks && this.hooks.enterCancelled; pushJob(this.enterNextTick); }; /** * The "nextTick" phase of an entering transition, which is * to be pushed into a queue and executed after a reflow so * that removing the class can trigger a CSS transition. */ p$1.enterNextTick = function () { var _this = this; // prevent transition skipping this.justEntered = true; waitForTransitionStart(function () { _this.justEntered = false; }); var enterDone = this.enterDone; var type = this.getCssTransitionType(this.enterClass); if (!this.pendingJsCb) { if (type === TYPE_TRANSITION) { // trigger transition by removing enter class now removeClass(this.el, this.enterClass); this.setupCssCb(transitionEndEvent, enterDone); } else if (type === TYPE_ANIMATION) { this.setupCssCb(animationEndEvent, enterDone); } else { enterDone(); } } else if (type === TYPE_TRANSITION) { removeClass(this.el, this.enterClass); } }; /** * The "cleanup" phase of an entering transition. */ p$1.enterDone = function () { this.entered = true; this.cancel = this.pendingJsCb = null; removeClass(this.el, this.enterClass); this.callHook('afterEnter'); if (this.cb) this.cb(); }; /** * Start a leaving transition. * * 1. leave transition triggered. * 2. call beforeLeave hook * 3. add leave class (trigger css transition) * 4. call leave hook (with possible explicit js callback) * 5. reflow if no explicit js callback is provided * 6. based on transition type: * - transition or animation: * wait for end event, remove class, then done if * there's no explicit js callback. * - no css transition: * done if there's no explicit js callback. * 7. wait for either done or js callback, then call * afterLeave hook. * * @param {Function} op - remove/hide the element * @param {Function} [cb] */ p$1.leave = function (op, cb) { this.cancelPending(); this.callHook('beforeLeave'); this.op = op; this.cb = cb; addClass(this.el, this.leaveClass); this.left = false; this.callHookWithCb('leave'); if (this.left) { return; // user called done synchronously. } this.cancel = this.hooks && this.hooks.leaveCancelled; // only need to handle leaveDone if // 1. the transition is already done (synchronously called // by the user, which causes this.op set to null) // 2. there's no explicit js callback if (this.op && !this.pendingJsCb) { // if a CSS transition leaves immediately after enter, // the transitionend event never fires. therefore we // detect such cases and end the leave immediately. if (this.justEntered) { this.leaveDone(); } else { pushJob(this.leaveNextTick); } } }; /** * The "nextTick" phase of a leaving transition. */ p$1.leaveNextTick = function () { var type = this.getCssTransitionType(this.leaveClass); if (type) { var event = type === TYPE_TRANSITION ? transitionEndEvent : animationEndEvent; this.setupCssCb(event, this.leaveDone); } else { this.leaveDone(); } }; /** * The "cleanup" phase of a leaving transition. */ p$1.leaveDone = function () { this.left = true; this.cancel = this.pendingJsCb = null; this.op(); removeClass(this.el, this.leaveClass); this.callHook('afterLeave'); if (this.cb) this.cb(); this.op = null; }; /** * Cancel any pending callbacks from a previously running * but not finished transition. */ p$1.cancelPending = function () { this.op = this.cb = null; var hasPending = false; if (this.pendingCssCb) { hasPending = true; off(this.el, this.pendingCssEvent, this.pendingCssCb); this.pendingCssEvent = this.pendingCssCb = null; } if (this.pendingJsCb) { hasPending = true; this.pendingJsCb.cancel(); this.pendingJsCb = null; } if (hasPending) { removeClass(this.el, this.enterClass); removeClass(this.el, this.leaveClass); } if (this.cancel) { this.cancel.call(this.vm, this.el); this.cancel = null; } }; /** * Call a user-provided synchronous hook function. * * @param {String} type */ p$1.callHook = function (type) { if (this.hooks && this.hooks[type]) { this.hooks[type].call(this.vm, this.el); } }; /** * Call a user-provided, potentially-async hook function. * We check for the length of arguments to see if the hook * expects a `done` callback. If true, the transition's end * will be determined by when the user calls that callback; * otherwise, the end is determined by the CSS transition or * animation. * * @param {String} type */ p$1.callHookWithCb = function (type) { var hook = this.hooks && this.hooks[type]; if (hook) { if (hook.length > 1) { this.pendingJsCb = cancellable(this[type + 'Done']); } hook.call(this.vm, this.el, this.pendingJsCb); } }; /** * Get an element's transition type based on the * calculated styles. * * @param {String} className * @return {Number} */ p$1.getCssTransitionType = function (className) { /* istanbul ignore if */ if (!transitionEndEvent || // skip CSS transitions if page is not visible - // this solves the issue of transitionend events not // firing until the page is visible again. // pageVisibility API is supported in IE10+, same as // CSS transitions. document.hidden || // explicit js-only transition this.hooks && this.hooks.css === false || // element is hidden isHidden(this.el)) { return; } var type = this.type || this.typeCache[className]; if (type) return type; var inlineStyles = this.el.style; var computedStyles = window.getComputedStyle(this.el); var transDuration = inlineStyles[transDurationProp] || computedStyles[transDurationProp]; if (transDuration && transDuration !== '0s') { type = TYPE_TRANSITION; } else { var animDuration = inlineStyles[animDurationProp] || computedStyles[animDurationProp]; if (animDuration && animDuration !== '0s') { type = TYPE_ANIMATION; } } if (type) { this.typeCache[className] = type; } return type; }; /** * Setup a CSS transitionend/animationend callback. * * @param {String} event * @param {Function} cb */ p$1.setupCssCb = function (event, cb) { this.pendingCssEvent = event; var self = this; var el = this.el; var onEnd = this.pendingCssCb = function (e) { if (e.target === el) { off(el, event, onEnd); self.pendingCssEvent = self.pendingCssCb = null; if (!self.pendingJsCb && cb) { cb(); } } }; on(el, event, onEnd); }; /** * Check if an element is hidden - in that case we can just * skip the transition alltogether. * * @param {Element} el * @return {Boolean} */ function isHidden(el) { if (/svg$/.test(el.namespaceURI)) { // SVG elements do not have offset(Width|Height) // so we need to check the client rect var rect = el.getBoundingClientRect(); return !(rect.width || rect.height); } else { return !(el.offsetWidth || el.offsetHeight || el.getClientRects().length); } } var transition$1 = { priority: TRANSITION, update: function update(id, oldId) { var el = this.el; // resolve on owner vm var hooks = resolveAsset(this.vm.$options, 'transitions', id); id = id || 'v'; el.__v_trans = new Transition(el, id, hooks, this.vm); if (oldId) { removeClass(el, oldId + '-transition'); } addClass(el, id + '-transition'); } }; var internalDirectives = { style: style, 'class': vClass, component: component, prop: propDef, transition: transition$1 }; // special binding prefixes var bindRE = /^v-bind:|^:/; var onRE = /^v-on:|^@/; var dirAttrRE = /^v-([^:]+)(?:$|:(.*)$)/; var modifierRE = /\.[^\.]+/g; var transitionRE = /^(v-bind:|:)?transition$/; // default directive priority var DEFAULT_PRIORITY = 1000; var DEFAULT_TERMINAL_PRIORITY = 2000; /** * Compile a template and return a reusable composite link * function, which recursively contains more link functions * inside. This top level compile function would normally * be called on instance root nodes, but can also be used * for partial compilation if the partial argument is true. * * The returned composite link function, when called, will * return an unlink function that tearsdown all directives * created during the linking phase. * * @param {Element|DocumentFragment} el * @param {Object} options * @param {Boolean} partial * @return {Function} */ function compile(el, options, partial) { // link function for the node itself. var nodeLinkFn = partial || !options._asComponent ? compileNode(el, options) : null; // link function for the childNodes var childLinkFn = !(nodeLinkFn && nodeLinkFn.terminal) && !isScript(el) && el.hasChildNodes() ? compileNodeList(el.childNodes, options) : null; /** * A composite linker function to be called on a already * compiled piece of DOM, which instantiates all directive * instances. * * @param {Vue} vm * @param {Element|DocumentFragment} el * @param {Vue} [host] - host vm of transcluded content * @param {Object} [scope] - v-for scope * @param {Fragment} [frag] - link context fragment * @return {Function|undefined} */ return function compositeLinkFn(vm, el, host, scope, frag) { // cache childNodes before linking parent, fix #657 var childNodes = toArray(el.childNodes); // link var dirs = linkAndCapture(function compositeLinkCapturer() { if (nodeLinkFn) nodeLinkFn(vm, el, host, scope, frag); if (childLinkFn) childLinkFn(vm, childNodes, host, scope, frag); }, vm); return makeUnlinkFn(vm, dirs); }; } /** * Apply a linker to a vm/element pair and capture the * directives created during the process. * * @param {Function} linker * @param {Vue} vm */ function linkAndCapture(linker, vm) { /* istanbul ignore if */ if (process.env.NODE_ENV === 'production') { // reset directives before every capture in production // mode, so that when unlinking we don't need to splice // them out (which turns out to be a perf hit). // they are kept in development mode because they are // useful for Vue's own tests. vm._directives = []; } var originalDirCount = vm._directives.length; linker(); var dirs = vm._directives.slice(originalDirCount); dirs.sort(directiveComparator); for (var i = 0, l = dirs.length; i < l; i++) { dirs[i]._bind(); } return dirs; } /** * Directive priority sort comparator * * @param {Object} a * @param {Object} b */ function directiveComparator(a, b) { a = a.descriptor.def.priority || DEFAULT_PRIORITY; b = b.descriptor.def.priority || DEFAULT_PRIORITY; return a > b ? -1 : a === b ? 0 : 1; } /** * Linker functions return an unlink function that * tearsdown all directives instances generated during * the process. * * We create unlink functions with only the necessary * information to avoid retaining additional closures. * * @param {Vue} vm * @param {Array} dirs * @param {Vue} [context] * @param {Array} [contextDirs] * @return {Function} */ function makeUnlinkFn(vm, dirs, context, contextDirs) { function unlink(destroying) { teardownDirs(vm, dirs, destroying); if (context && contextDirs) { teardownDirs(context, contextDirs); } } // expose linked directives unlink.dirs = dirs; return unlink; } /** * Teardown partial linked directives. * * @param {Vue} vm * @param {Array} dirs * @param {Boolean} destroying */ function teardownDirs(vm, dirs, destroying) { var i = dirs.length; while (i--) { dirs[i]._teardown(); if (process.env.NODE_ENV !== 'production' && !destroying) { vm._directives.$remove(dirs[i]); } } } /** * Compile link props on an instance. * * @param {Vue} vm * @param {Element} el * @param {Object} props * @param {Object} [scope] * @return {Function} */ function compileAndLinkProps(vm, el, props, scope) { var propsLinkFn = compileProps(el, props, vm); var propDirs = linkAndCapture(function () { propsLinkFn(vm, scope); }, vm); return makeUnlinkFn(vm, propDirs); } /** * Compile the root element of an instance. * * 1. attrs on context container (context scope) * 2. attrs on the component template root node, if * replace:true (child scope) * * If this is a fragment instance, we only need to compile 1. * * @param {Element} el * @param {Object} options * @param {Object} contextOptions * @return {Function} */ function compileRoot(el, options, contextOptions) { var containerAttrs = options._containerAttrs; var replacerAttrs = options._replacerAttrs; var contextLinkFn, replacerLinkFn; // only need to compile other attributes for // non-fragment instances if (el.nodeType !== 11) { // for components, container and replacer need to be // compiled separately and linked in different scopes. if (options._asComponent) { // 2. container attributes if (containerAttrs && contextOptions) { contextLinkFn = compileDirectives(containerAttrs, contextOptions); } if (replacerAttrs) { // 3. replacer attributes replacerLinkFn = compileDirectives(replacerAttrs, options); } } else { // non-component, just compile as a normal element. replacerLinkFn = compileDirectives(el.attributes, options); } } else if (process.env.NODE_ENV !== 'production' && containerAttrs) { // warn container directives for fragment instances var names = containerAttrs.filter(function (attr) { // allow vue-loader/vueify scoped css attributes return attr.name.indexOf('_v-') < 0 && // allow event listeners !onRE.test(attr.name) && // allow slots attr.name !== 'slot'; }).map(function (attr) { return '"' + attr.name + '"'; }); if (names.length) { var plural = names.length > 1; warn('Attribute' + (plural ? 's ' : ' ') + names.join(', ') + (plural ? ' are' : ' is') + ' ignored on component ' + '<' + options.el.tagName.toLowerCase() + '> because ' + 'the component is a fragment instance: ' + 'path_to_url#Fragment-Instance'); } } options._containerAttrs = options._replacerAttrs = null; return function rootLinkFn(vm, el, scope) { // link context scope dirs var context = vm._context; var contextDirs; if (context && contextLinkFn) { contextDirs = linkAndCapture(function () { contextLinkFn(context, el, null, scope); }, context); } // link self var selfDirs = linkAndCapture(function () { if (replacerLinkFn) replacerLinkFn(vm, el); }, vm); // return the unlink function that tearsdown context // container directives. return makeUnlinkFn(vm, selfDirs, context, contextDirs); }; } /** * Compile a node and return a nodeLinkFn based on the * node type. * * @param {Node} node * @param {Object} options * @return {Function|null} */ function compileNode(node, options) { var type = node.nodeType; if (type === 1 && !isScript(node)) { return compileElement(node, options); } else if (type === 3 && node.data.trim()) { return compileTextNode(node, options); } else { return null; } } /** * Compile an element and return a nodeLinkFn. * * @param {Element} el * @param {Object} options * @return {Function|null} */ function compileElement(el, options) { // preprocess textareas. // textarea treats its text content as the initial value. // just bind it as an attr directive for value. if (el.tagName === 'TEXTAREA') { var tokens = parseText(el.value); if (tokens) { el.setAttribute(':value', tokensToExp(tokens)); el.value = ''; } } var linkFn; var hasAttrs = el.hasAttributes(); var attrs = hasAttrs && toArray(el.attributes); // check terminal directives (for & if) if (hasAttrs) { linkFn = checkTerminalDirectives(el, attrs, options); } // check element directives if (!linkFn) { linkFn = checkElementDirectives(el, options); } // check component if (!linkFn) { linkFn = checkComponent(el, options); } // normal directives if (!linkFn && hasAttrs) { linkFn = compileDirectives(attrs, options); } return linkFn; } /** * Compile a textNode and return a nodeLinkFn. * * @param {TextNode} node * @param {Object} options * @return {Function|null} textNodeLinkFn */ function compileTextNode(node, options) { // skip marked text nodes if (node._skip) { return removeText; } var tokens = parseText(node.wholeText); if (!tokens) { return null; } // mark adjacent text nodes as skipped, // because we are using node.wholeText to compile // all adjacent text nodes together. This fixes // issues in IE where sometimes it splits up a single // text node into multiple ones. var next = node.nextSibling; while (next && next.nodeType === 3) { next._skip = true; next = next.nextSibling; } var frag = document.createDocumentFragment(); var el, token; for (var i = 0, l = tokens.length; i < l; i++) { token = tokens[i]; el = token.tag ? processTextToken(token, options) : document.createTextNode(token.value); frag.appendChild(el); } return makeTextNodeLinkFn(tokens, frag, options); } /** * Linker for an skipped text node. * * @param {Vue} vm * @param {Text} node */ function removeText(vm, node) { remove(node); } /** * Process a single text token. * * @param {Object} token * @param {Object} options * @return {Node} */ function processTextToken(token, options) { var el; if (token.oneTime) { el = document.createTextNode(token.value); } else { if (token.html) { el = document.createComment('v-html'); setTokenType('html'); } else { // IE will clean up empty textNodes during // frag.cloneNode(true), so we have to give it // something here... el = document.createTextNode(' '); setTokenType('text'); } } function setTokenType(type) { if (token.descriptor) return; var parsed = parseDirective(token.value); token.descriptor = { name: type, def: directives[type], expression: parsed.expression, filters: parsed.filters }; } return el; } /** * Build a function that processes a textNode. * * @param {Array<Object>} tokens * @param {DocumentFragment} frag */ function makeTextNodeLinkFn(tokens, frag) { return function textNodeLinkFn(vm, el, host, scope) { var fragClone = frag.cloneNode(true); var childNodes = toArray(fragClone.childNodes); var token, value, node; for (var i = 0, l = tokens.length; i < l; i++) { token = tokens[i]; value = token.value; if (token.tag) { node = childNodes[i]; if (token.oneTime) { value = (scope || vm).$eval(value); if (token.html) { replace(node, parseTemplate(value, true)); } else { node.data = value; } } else { vm._bindDir(token.descriptor, node, host, scope); } } } replace(el, fragClone); }; } /** * Compile a node list and return a childLinkFn. * * @param {NodeList} nodeList * @param {Object} options * @return {Function|undefined} */ function compileNodeList(nodeList, options) { var linkFns = []; var nodeLinkFn, childLinkFn, node; for (var i = 0, l = nodeList.length; i < l; i++) { node = nodeList[i]; nodeLinkFn = compileNode(node, options); childLinkFn = !(nodeLinkFn && nodeLinkFn.terminal) && node.tagName !== 'SCRIPT' && node.hasChildNodes() ? compileNodeList(node.childNodes, options) : null; linkFns.push(nodeLinkFn, childLinkFn); } return linkFns.length ? makeChildLinkFn(linkFns) : null; } /** * Make a child link function for a node's childNodes. * * @param {Array<Function>} linkFns * @return {Function} childLinkFn */ function makeChildLinkFn(linkFns) { return function childLinkFn(vm, nodes, host, scope, frag) { var node, nodeLinkFn, childrenLinkFn; for (var i = 0, n = 0, l = linkFns.length; i < l; n++) { node = nodes[n]; nodeLinkFn = linkFns[i++]; childrenLinkFn = linkFns[i++]; // cache childNodes before linking parent, fix #657 var childNodes = toArray(node.childNodes); if (nodeLinkFn) { nodeLinkFn(vm, node, host, scope, frag); } if (childrenLinkFn) { childrenLinkFn(vm, childNodes, host, scope, frag); } } }; } /** * Check for element directives (custom elements that should * be resovled as terminal directives). * * @param {Element} el * @param {Object} options */ function checkElementDirectives(el, options) { var tag = el.tagName.toLowerCase(); if (commonTagRE.test(tag)) { return; } var def = resolveAsset(options, 'elementDirectives', tag); if (def) { return makeTerminalNodeLinkFn(el, tag, '', options, def); } } /** * Check if an element is a component. If yes, return * a component link function. * * @param {Element} el * @param {Object} options * @return {Function|undefined} */ function checkComponent(el, options) { var component = checkComponentAttr(el, options); if (component) { var ref = findRef(el); var descriptor = { name: 'component', ref: ref, expression: component.id, def: internalDirectives.component, modifiers: { literal: !component.dynamic } }; var componentLinkFn = function componentLinkFn(vm, el, host, scope, frag) { if (ref) { defineReactive((scope || vm).$refs, ref, null); } vm._bindDir(descriptor, el, host, scope, frag); }; componentLinkFn.terminal = true; return componentLinkFn; } } /** * Check an element for terminal directives in fixed order. * If it finds one, return a terminal link function. * * @param {Element} el * @param {Array} attrs * @param {Object} options * @return {Function} terminalLinkFn */ function checkTerminalDirectives(el, attrs, options) { // skip v-pre if (getAttr(el, 'v-pre') !== null) { return skip; } // skip v-else block, but only if following v-if if (el.hasAttribute('v-else')) { var prev = el.previousElementSibling; if (prev && prev.hasAttribute('v-if')) { return skip; } } var attr, name, value, modifiers, matched, dirName, rawName, arg, def, termDef; for (var i = 0, j = attrs.length; i < j; i++) { attr = attrs[i]; name = attr.name.replace(modifierRE, ''); if (matched = name.match(dirAttrRE)) { def = resolveAsset(options, 'directives', matched[1]); if (def && def.terminal) { if (!termDef || (def.priority || DEFAULT_TERMINAL_PRIORITY) > termDef.priority) { termDef = def; rawName = attr.name; modifiers = parseModifiers(attr.name); value = attr.value; dirName = matched[1]; arg = matched[2]; } } } } if (termDef) { return makeTerminalNodeLinkFn(el, dirName, value, options, termDef, rawName, arg, modifiers); } } function skip() {} skip.terminal = true; /** * Build a node link function for a terminal directive. * A terminal link function terminates the current * compilation recursion and handles compilation of the * subtree in the directive. * * @param {Element} el * @param {String} dirName * @param {String} value * @param {Object} options * @param {Object} def * @param {String} [rawName] * @param {String} [arg] * @param {Object} [modifiers] * @return {Function} terminalLinkFn */ function makeTerminalNodeLinkFn(el, dirName, value, options, def, rawName, arg, modifiers) { var parsed = parseDirective(value); var descriptor = { name: dirName, arg: arg, expression: parsed.expression, filters: parsed.filters, raw: value, attr: rawName, modifiers: modifiers, def: def }; // check ref for v-for and router-view if (dirName === 'for' || dirName === 'router-view') { descriptor.ref = findRef(el); } var fn = function terminalNodeLinkFn(vm, el, host, scope, frag) { if (descriptor.ref) { defineReactive((scope || vm).$refs, descriptor.ref, null); } vm._bindDir(descriptor, el, host, scope, frag); }; fn.terminal = true; return fn; } /** * Compile the directives on an element and return a linker. * * @param {Array|NamedNodeMap} attrs * @param {Object} options * @return {Function} */ function compileDirectives(attrs, options) { var i = attrs.length; var dirs = []; var attr, name, value, rawName, rawValue, dirName, arg, modifiers, dirDef, tokens, matched; while (i--) { attr = attrs[i]; name = rawName = attr.name; value = rawValue = attr.value; tokens = parseText(value); // reset arg arg = null; // check modifiers modifiers = parseModifiers(name); name = name.replace(modifierRE, ''); // attribute interpolations if (tokens) { value = tokensToExp(tokens); arg = name; pushDir('bind', directives.bind, tokens); // warn against mixing mustaches with v-bind if (process.env.NODE_ENV !== 'production') { if (name === 'class' && Array.prototype.some.call(attrs, function (attr) { return attr.name === ':class' || attr.name === 'v-bind:class'; })) { warn('class="' + rawValue + '": Do not mix mustache interpolation ' + 'and v-bind for "class" on the same element. Use one or the other.', options); } } } else // special attribute: transition if (transitionRE.test(name)) { modifiers.literal = !bindRE.test(name); pushDir('transition', internalDirectives.transition); } else // event handlers if (onRE.test(name)) { arg = name.replace(onRE, ''); pushDir('on', directives.on); } else // attribute bindings if (bindRE.test(name)) { dirName = name.replace(bindRE, ''); if (dirName === 'style' || dirName === 'class') { pushDir(dirName, internalDirectives[dirName]); } else { arg = dirName; pushDir('bind', directives.bind); } } else // normal directives if (matched = name.match(dirAttrRE)) { dirName = matched[1]; arg = matched[2]; // skip v-else (when used with v-show) if (dirName === 'else') { continue; } dirDef = resolveAsset(options, 'directives', dirName, true); if (dirDef) { pushDir(dirName, dirDef); } } } /** * Push a directive. * * @param {String} dirName * @param {Object|Function} def * @param {Array} [interpTokens] */ function pushDir(dirName, def, interpTokens) { var hasOneTimeToken = interpTokens && hasOneTime(interpTokens); var parsed = !hasOneTimeToken && parseDirective(value); dirs.push({ name: dirName, attr: rawName, raw: rawValue, def: def, arg: arg, modifiers: modifiers, // conversion from interpolation strings with one-time token // to expression is differed until directive bind time so that we // have access to the actual vm context for one-time bindings. expression: parsed && parsed.expression, filters: parsed && parsed.filters, interp: interpTokens, hasOneTime: hasOneTimeToken }); } if (dirs.length) { return makeNodeLinkFn(dirs); } } /** * Parse modifiers from directive attribute name. * * @param {String} name * @return {Object} */ function parseModifiers(name) { var res = Object.create(null); var match = name.match(modifierRE); if (match) { var i = match.length; while (i--) { res[match[i].slice(1)] = true; } } return res; } /** * Build a link function for all directives on a single node. * * @param {Array} directives * @return {Function} directivesLinkFn */ function makeNodeLinkFn(directives) { return function nodeLinkFn(vm, el, host, scope, frag) { // reverse apply because it's sorted low to high var i = directives.length; while (i--) { vm._bindDir(directives[i], el, host, scope, frag); } }; } /** * Check if an interpolation string contains one-time tokens. * * @param {Array} tokens * @return {Boolean} */ function hasOneTime(tokens) { var i = tokens.length; while (i--) { if (tokens[i].oneTime) return true; } } function isScript(el) { return el.tagName === 'SCRIPT' && (!el.hasAttribute('type') || el.getAttribute('type') === 'text/javascript'); } var specialCharRE = /[^\w\-:\.]/; /** * Process an element or a DocumentFragment based on a * instance option object. This allows us to transclude * a template node/fragment before the instance is created, * so the processed fragment can then be cloned and reused * in v-for. * * @param {Element} el * @param {Object} options * @return {Element|DocumentFragment} */ function transclude(el, options) { // extract container attributes to pass them down // to compiler, because they need to be compiled in // parent scope. we are mutating the options object here // assuming the same object will be used for compile // right after this. if (options) { options._containerAttrs = extractAttrs(el); } // for template tags, what we want is its content as // a documentFragment (for fragment instances) if (isTemplate(el)) { el = parseTemplate(el); } if (options) { if (options._asComponent && !options.template) { options.template = '<slot></slot>'; } if (options.template) { options._content = extractContent(el); el = transcludeTemplate(el, options); } } if (isFragment(el)) { // anchors for fragment instance // passing in `persist: true` to avoid them being // discarded by IE during template cloning prepend(createAnchor('v-start', true), el); el.appendChild(createAnchor('v-end', true)); } return el; } /** * Process the template option. * If the replace option is true this will swap the $el. * * @param {Element} el * @param {Object} options * @return {Element|DocumentFragment} */ function transcludeTemplate(el, options) { var template = options.template; var frag = parseTemplate(template, true); if (frag) { var replacer = frag.firstChild; var tag = replacer.tagName && replacer.tagName.toLowerCase(); if (options.replace) { /* istanbul ignore if */ if (el === document.body) { process.env.NODE_ENV !== 'production' && warn('You are mounting an instance with a template to ' + '<body>. This will replace <body> entirely. You ' + 'should probably use `replace: false` here.'); } // there are many cases where the instance must // become a fragment instance: basically anything that // can create more than 1 root nodes. if ( // multi-children template frag.childNodes.length > 1 || // non-element template replacer.nodeType !== 1 || // single nested component tag === 'component' || resolveAsset(options, 'components', tag) || hasBindAttr(replacer, 'is') || // element directive resolveAsset(options, 'elementDirectives', tag) || // for block replacer.hasAttribute('v-for') || // if block replacer.hasAttribute('v-if')) { return frag; } else { options._replacerAttrs = extractAttrs(replacer); mergeAttrs(el, replacer); return replacer; } } else { el.appendChild(frag); return el; } } else { process.env.NODE_ENV !== 'production' && warn('Invalid template option: ' + template); } } /** * Helper to extract a component container's attributes * into a plain object array. * * @param {Element} el * @return {Array} */ function extractAttrs(el) { if (el.nodeType === 1 && el.hasAttributes()) { return toArray(el.attributes); } } /** * Merge the attributes of two elements, and make sure * the class names are merged properly. * * @param {Element} from * @param {Element} to */ function mergeAttrs(from, to) { var attrs = from.attributes; var i = attrs.length; var name, value; while (i--) { name = attrs[i].name; value = attrs[i].value; if (!to.hasAttribute(name) && !specialCharRE.test(name)) { to.setAttribute(name, value); } else if (name === 'class' && !parseText(value) && (value = value.trim())) { value.split(/\s+/).forEach(function (cls) { addClass(to, cls); }); } } } /** * Scan and determine slot content distribution. * We do this during transclusion instead at compile time so that * the distribution is decoupled from the compilation order of * the slots. * * @param {Element|DocumentFragment} template * @param {Element} content * @param {Vue} vm */ function resolveSlots(vm, content) { if (!content) { return; } var contents = vm._slotContents = Object.create(null); var el, name; for (var i = 0, l = content.children.length; i < l; i++) { el = content.children[i]; /* eslint-disable no-cond-assign */ if (name = el.getAttribute('slot')) { (contents[name] || (contents[name] = [])).push(el); } /* eslint-enable no-cond-assign */ if (process.env.NODE_ENV !== 'production' && getBindAttr(el, 'slot')) { warn('The "slot" attribute must be static.', vm.$parent); } } for (name in contents) { contents[name] = extractFragment(contents[name], content); } if (content.hasChildNodes()) { var nodes = content.childNodes; if (nodes.length === 1 && nodes[0].nodeType === 3 && !nodes[0].data.trim()) { return; } contents['default'] = extractFragment(content.childNodes, content); } } /** * Extract qualified content nodes from a node list. * * @param {NodeList} nodes * @return {DocumentFragment} */ function extractFragment(nodes, parent) { var frag = document.createDocumentFragment(); nodes = toArray(nodes); for (var i = 0, l = nodes.length; i < l; i++) { var node = nodes[i]; if (isTemplate(node) && !node.hasAttribute('v-if') && !node.hasAttribute('v-for')) { parent.removeChild(node); node = parseTemplate(node, true); } frag.appendChild(node); } return frag; } var compiler = Object.freeze({ compile: compile, compileAndLinkProps: compileAndLinkProps, compileRoot: compileRoot, transclude: transclude, resolveSlots: resolveSlots }); function stateMixin (Vue) { /** * Accessor for `$data` property, since setting $data * requires observing the new object and updating * proxied properties. */ Object.defineProperty(Vue.prototype, '$data', { get: function get() { return this._data; }, set: function set(newData) { if (newData !== this._data) { this._setData(newData); } } }); /** * Setup the scope of an instance, which contains: * - observed data * - computed properties * - user methods * - meta properties */ Vue.prototype._initState = function () { this._initProps(); this._initMeta(); this._initMethods(); this._initData(); this._initComputed(); }; /** * Initialize props. */ Vue.prototype._initProps = function () { var options = this.$options; var el = options.el; var props = options.props; if (props && !el) { process.env.NODE_ENV !== 'production' && warn('Props will not be compiled if no `el` option is ' + 'provided at instantiation.', this); } // make sure to convert string selectors into element now el = options.el = query(el); this._propsUnlinkFn = el && el.nodeType === 1 && props // props must be linked in proper scope if inside v-for ? compileAndLinkProps(this, el, props, this._scope) : null; }; /** * Initialize the data. */ Vue.prototype._initData = function () { var dataFn = this.$options.data; var data = this._data = dataFn ? dataFn() : {}; if (!isPlainObject(data)) { data = {}; process.env.NODE_ENV !== 'production' && warn('data functions should return an object.', this); } var props = this._props; // proxy data on instance var keys = Object.keys(data); var i, key; i = keys.length; while (i--) { key = keys[i]; // there are two scenarios where we can proxy a data key: // 1. it's not already defined as a prop // 2. it's provided via a instantiation option AND there are no // template prop present if (!props || !hasOwn(props, key)) { this._proxy(key); } else if (process.env.NODE_ENV !== 'production') { warn('Data field "' + key + '" is already defined ' + 'as a prop. To provide default value for a prop, use the "default" ' + 'prop option; if you want to pass prop values to an instantiation ' + 'call, use the "propsData" option.', this); } } // observe data observe(data, this); }; /** * Swap the instance's $data. Called in $data's setter. * * @param {Object} newData */ Vue.prototype._setData = function (newData) { newData = newData || {}; var oldData = this._data; this._data = newData; var keys, key, i; // unproxy keys not present in new data keys = Object.keys(oldData); i = keys.length; while (i--) { key = keys[i]; if (!(key in newData)) { this._unproxy(key); } } // proxy keys not already proxied, // and trigger change for changed values keys = Object.keys(newData); i = keys.length; while (i--) { key = keys[i]; if (!hasOwn(this, key)) { // new property this._proxy(key); } } oldData.__ob__.removeVm(this); observe(newData, this); this._digest(); }; /** * Proxy a property, so that * vm.prop === vm._data.prop * * @param {String} key */ Vue.prototype._proxy = function (key) { if (!isReserved(key)) { // need to store ref to self here // because these getter/setters might // be called by child scopes via // prototype inheritance. var self = this; Object.defineProperty(self, key, { configurable: true, enumerable: true, get: function proxyGetter() { return self._data[key]; }, set: function proxySetter(val) { self._data[key] = val; } }); } }; /** * Unproxy a property. * * @param {String} key */ Vue.prototype._unproxy = function (key) { if (!isReserved(key)) { delete this[key]; } }; /** * Force update on every watcher in scope. */ Vue.prototype._digest = function () { for (var i = 0, l = this._watchers.length; i < l; i++) { this._watchers[i].update(true); // shallow updates } }; /** * Setup computed properties. They are essentially * special getter/setters */ function noop() {} Vue.prototype._initComputed = function () { var computed = this.$options.computed; if (computed) { for (var key in computed) { var userDef = computed[key]; var def = { enumerable: true, configurable: true }; if (typeof userDef === 'function') { def.get = makeComputedGetter(userDef, this); def.set = noop; } else { def.get = userDef.get ? userDef.cache !== false ? makeComputedGetter(userDef.get, this) : bind(userDef.get, this) : noop; def.set = userDef.set ? bind(userDef.set, this) : noop; } Object.defineProperty(this, key, def); } } }; function makeComputedGetter(getter, owner) { var watcher = new Watcher(owner, getter, null, { lazy: true }); return function computedGetter() { if (watcher.dirty) { watcher.evaluate(); } if (Dep.target) { watcher.depend(); } return watcher.value; }; } /** * Setup instance methods. Methods must be bound to the * instance since they might be passed down as a prop to * child components. */ Vue.prototype._initMethods = function () { var methods = this.$options.methods; if (methods) { for (var key in methods) { this[key] = bind(methods[key], this); } } }; /** * Initialize meta information like $index, $key & $value. */ Vue.prototype._initMeta = function () { var metas = this.$options._meta; if (metas) { for (var key in metas) { defineReactive(this, key, metas[key]); } } }; } var eventRE = /^v-on:|^@/; function eventsMixin (Vue) { /** * Setup the instance's option events & watchers. * If the value is a string, we pull it from the * instance's methods by name. */ Vue.prototype._initEvents = function () { var options = this.$options; if (options._asComponent) { registerComponentEvents(this, options.el); } registerCallbacks(this, '$on', options.events); registerCallbacks(this, '$watch', options.watch); }; /** * Register v-on events on a child component * * @param {Vue} vm * @param {Element} el */ function registerComponentEvents(vm, el) { var attrs = el.attributes; var name, value, handler; for (var i = 0, l = attrs.length; i < l; i++) { name = attrs[i].name; if (eventRE.test(name)) { name = name.replace(eventRE, ''); // force the expression into a statement so that // it always dynamically resolves the method to call (#2670) // kinda ugly hack, but does the job. value = attrs[i].value; if (isSimplePath(value)) { value += '.apply(this, $arguments)'; } handler = (vm._scope || vm._context).$eval(value, true); handler._fromParent = true; vm.$on(name.replace(eventRE), handler); } } } /** * Register callbacks for option events and watchers. * * @param {Vue} vm * @param {String} action * @param {Object} hash */ function registerCallbacks(vm, action, hash) { if (!hash) return; var handlers, key, i, j; for (key in hash) { handlers = hash[key]; if (isArray(handlers)) { for (i = 0, j = handlers.length; i < j; i++) { register(vm, action, key, handlers[i]); } } else { register(vm, action, key, handlers); } } } /** * Helper to register an event/watch callback. * * @param {Vue} vm * @param {String} action * @param {String} key * @param {Function|String|Object} handler * @param {Object} [options] */ function register(vm, action, key, handler, options) { var type = typeof handler; if (type === 'function') { vm[action](key, handler, options); } else if (type === 'string') { var methods = vm.$options.methods; var method = methods && methods[handler]; if (method) { vm[action](key, method, options); } else { process.env.NODE_ENV !== 'production' && warn('Unknown method: "' + handler + '" when ' + 'registering callback for ' + action + ': "' + key + '".', vm); } } else if (handler && type === 'object') { register(vm, action, key, handler.handler, handler); } } /** * Setup recursive attached/detached calls */ Vue.prototype._initDOMHooks = function () { this.$on('hook:attached', onAttached); this.$on('hook:detached', onDetached); }; /** * Callback to recursively call attached hook on children */ function onAttached() { if (!this._isAttached) { this._isAttached = true; this.$children.forEach(callAttach); } } /** * Iterator to call attached hook * * @param {Vue} child */ function callAttach(child) { if (!child._isAttached && inDoc(child.$el)) { child._callHook('attached'); } } /** * Callback to recursively call detached hook on children */ function onDetached() { if (this._isAttached) { this._isAttached = false; this.$children.forEach(callDetach); } } /** * Iterator to call detached hook * * @param {Vue} child */ function callDetach(child) { if (child._isAttached && !inDoc(child.$el)) { child._callHook('detached'); } } /** * Trigger all handlers for a hook * * @param {String} hook */ Vue.prototype._callHook = function (hook) { this.$emit('pre-hook:' + hook); var handlers = this.$options[hook]; if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { handlers[i].call(this); } } this.$emit('hook:' + hook); }; } function noop() {} /** * A directive links a DOM element with a piece of data, * which is the result of evaluating an expression. * It registers a watcher with the expression and calls * the DOM update function when a change is triggered. * * @param {Object} descriptor * - {String} name * - {Object} def * - {String} expression * - {Array<Object>} [filters] * - {Object} [modifiers] * - {Boolean} literal * - {String} attr * - {String} arg * - {String} raw * - {String} [ref] * - {Array<Object>} [interp] * - {Boolean} [hasOneTime] * @param {Vue} vm * @param {Node} el * @param {Vue} [host] - transclusion host component * @param {Object} [scope] - v-for scope * @param {Fragment} [frag] - owner fragment * @constructor */ function Directive(descriptor, vm, el, host, scope, frag) { this.vm = vm; this.el = el; // copy descriptor properties this.descriptor = descriptor; this.name = descriptor.name; this.expression = descriptor.expression; this.arg = descriptor.arg; this.modifiers = descriptor.modifiers; this.filters = descriptor.filters; this.literal = this.modifiers && this.modifiers.literal; // private this._locked = false; this._bound = false; this._listeners = null; // link context this._host = host; this._scope = scope; this._frag = frag; // store directives on node in dev mode if (process.env.NODE_ENV !== 'production' && this.el) { this.el._vue_directives = this.el._vue_directives || []; this.el._vue_directives.push(this); } } /** * Initialize the directive, mixin definition properties, * setup the watcher, call definition bind() and update() * if present. */ Directive.prototype._bind = function () { var name = this.name; var descriptor = this.descriptor; // remove attribute if ((name !== 'cloak' || this.vm._isCompiled) && this.el && this.el.removeAttribute) { var attr = descriptor.attr || 'v-' + name; this.el.removeAttribute(attr); } // copy def properties var def = descriptor.def; if (typeof def === 'function') { this.update = def; } else { extend(this, def); } // setup directive params this._setupParams(); // initial bind if (this.bind) { this.bind(); } this._bound = true; if (this.literal) { this.update && this.update(descriptor.raw); } else if ((this.expression || this.modifiers) && (this.update || this.twoWay) && !this._checkStatement()) { // wrapped updater for context var dir = this; if (this.update) { this._update = function (val, oldVal) { if (!dir._locked) { dir.update(val, oldVal); } }; } else { this._update = noop; } var preProcess = this._preProcess ? bind(this._preProcess, this) : null; var postProcess = this._postProcess ? bind(this._postProcess, this) : null; var watcher = this._watcher = new Watcher(this.vm, this.expression, this._update, // callback { filters: this.filters, twoWay: this.twoWay, deep: this.deep, preProcess: preProcess, postProcess: postProcess, scope: this._scope }); // v-model with inital inline value need to sync back to // model instead of update to DOM on init. They would // set the afterBind hook to indicate that. if (this.afterBind) { this.afterBind(); } else if (this.update) { this.update(watcher.value); } } }; /** * Setup all param attributes, e.g. track-by, * transition-mode, etc... */ Directive.prototype._setupParams = function () { if (!this.params) { return; } var params = this.params; // swap the params array with a fresh object. this.params = Object.create(null); var i = params.length; var key, val, mappedKey; while (i--) { key = hyphenate(params[i]); mappedKey = camelize(key); val = getBindAttr(this.el, key); if (val != null) { // dynamic this._setupParamWatcher(mappedKey, val); } else { // static val = getAttr(this.el, key); if (val != null) { this.params[mappedKey] = val === '' ? true : val; } } } }; /** * Setup a watcher for a dynamic param. * * @param {String} key * @param {String} expression */ Directive.prototype._setupParamWatcher = function (key, expression) { var self = this; var called = false; var unwatch = (this._scope || this.vm).$watch(expression, function (val, oldVal) { self.params[key] = val; // since we are in immediate mode, // only call the param change callbacks if this is not the first update. if (called) { var cb = self.paramWatchers && self.paramWatchers[key]; if (cb) { cb.call(self, val, oldVal); } } else { called = true; } }, { immediate: true, user: false });(this._paramUnwatchFns || (this._paramUnwatchFns = [])).push(unwatch); }; /** * Check if the directive is a function caller * and if the expression is a callable one. If both true, * we wrap up the expression and use it as the event * handler. * * e.g. on-click="a++" * * @return {Boolean} */ Directive.prototype._checkStatement = function () { var expression = this.expression; if (expression && this.acceptStatement && !isSimplePath(expression)) { var fn = parseExpression(expression).get; var scope = this._scope || this.vm; var handler = function handler(e) { scope.$event = e; fn.call(scope, scope); scope.$event = null; }; if (this.filters) { handler = scope._applyFilters(handler, null, this.filters); } this.update(handler); return true; } }; /** * Set the corresponding value with the setter. * This should only be used in two-way directives * e.g. v-model. * * @param {*} value * @public */ Directive.prototype.set = function (value) { /* istanbul ignore else */ if (this.twoWay) { this._withLock(function () { this._watcher.set(value); }); } else if (process.env.NODE_ENV !== 'production') { warn('Directive.set() can only be used inside twoWay' + 'directives.'); } }; /** * Execute a function while preventing that function from * triggering updates on this directive instance. * * @param {Function} fn */ Directive.prototype._withLock = function (fn) { var self = this; self._locked = true; fn.call(self); nextTick(function () { self._locked = false; }); }; /** * Convenience method that attaches a DOM event listener * to the directive element and autometically tears it down * during unbind. * * @param {String} event * @param {Function} handler * @param {Boolean} [useCapture] */ Directive.prototype.on = function (event, handler, useCapture) { on(this.el, event, handler, useCapture);(this._listeners || (this._listeners = [])).push([event, handler]); }; /** * Teardown the watcher and call unbind. */ Directive.prototype._teardown = function () { if (this._bound) { this._bound = false; if (this.unbind) { this.unbind(); } if (this._watcher) { this._watcher.teardown(); } var listeners = this._listeners; var i; if (listeners) { i = listeners.length; while (i--) { off(this.el, listeners[i][0], listeners[i][1]); } } var unwatchFns = this._paramUnwatchFns; if (unwatchFns) { i = unwatchFns.length; while (i--) { unwatchFns[i](); } } if (process.env.NODE_ENV !== 'production' && this.el) { this.el._vue_directives.$remove(this); } this.vm = this.el = this._watcher = this._listeners = null; } }; function lifecycleMixin (Vue) { /** * Update v-ref for component. * * @param {Boolean} remove */ Vue.prototype._updateRef = function (remove) { var ref = this.$options._ref; if (ref) { var refs = (this._scope || this._context).$refs; if (remove) { if (refs[ref] === this) { refs[ref] = null; } } else { refs[ref] = this; } } }; /** * Transclude, compile and link element. * * If a pre-compiled linker is available, that means the * passed in element will be pre-transcluded and compiled * as well - all we need to do is to call the linker. * * Otherwise we need to call transclude/compile/link here. * * @param {Element} el */ Vue.prototype._compile = function (el) { var options = this.$options; // transclude and init element // transclude can potentially replace original // so we need to keep reference; this step also injects // the template and caches the original attributes // on the container node and replacer node. var original = el; el = transclude(el, options); this._initElement(el); // handle v-pre on root node (#2026) if (el.nodeType === 1 && getAttr(el, 'v-pre') !== null) { return; } // root is always compiled per-instance, because // container attrs and props can be different every time. var contextOptions = this._context && this._context.$options; var rootLinker = compileRoot(el, options, contextOptions); // resolve slot distribution resolveSlots(this, options._content); // compile and link the rest var contentLinkFn; var ctor = this.constructor; // component compilation can be cached // as long as it's not using inline-template if (options._linkerCachable) { contentLinkFn = ctor.linker; if (!contentLinkFn) { contentLinkFn = ctor.linker = compile(el, options); } } // link phase // make sure to link root with prop scope! var rootUnlinkFn = rootLinker(this, el, this._scope); var contentUnlinkFn = contentLinkFn ? contentLinkFn(this, el) : compile(el, options)(this, el); // register composite unlink function // to be called during instance destruction this._unlinkFn = function () { rootUnlinkFn(); // passing destroying: true to avoid searching and // splicing the directives contentUnlinkFn(true); }; // finally replace original if (options.replace) { replace(original, el); } this._isCompiled = true; this._callHook('compiled'); }; /** * Initialize instance element. Called in the public * $mount() method. * * @param {Element} el */ Vue.prototype._initElement = function (el) { if (isFragment(el)) { this._isFragment = true; this.$el = this._fragmentStart = el.firstChild; this._fragmentEnd = el.lastChild; // set persisted text anchors to empty if (this._fragmentStart.nodeType === 3) { this._fragmentStart.data = this._fragmentEnd.data = ''; } this._fragment = el; } else { this.$el = el; } this.$el.__vue__ = this; this._callHook('beforeCompile'); }; /** * Create and bind a directive to an element. * * @param {Object} descriptor - parsed directive descriptor * @param {Node} node - target node * @param {Vue} [host] - transclusion host component * @param {Object} [scope] - v-for scope * @param {Fragment} [frag] - owner fragment */ Vue.prototype._bindDir = function (descriptor, node, host, scope, frag) { this._directives.push(new Directive(descriptor, this, node, host, scope, frag)); }; /** * Teardown an instance, unobserves the data, unbind all the * directives, turn off all the event listeners, etc. * * @param {Boolean} remove - whether to remove the DOM node. * @param {Boolean} deferCleanup - if true, defer cleanup to * be called later */ Vue.prototype._destroy = function (remove, deferCleanup) { if (this._isBeingDestroyed) { if (!deferCleanup) { this._cleanup(); } return; } var destroyReady; var pendingRemoval; var self = this; // Cleanup should be called either synchronously or asynchronoysly as // callback of this.$remove(), or if remove and deferCleanup are false. // In any case it should be called after all other removing, unbinding and // turning of is done var cleanupIfPossible = function cleanupIfPossible() { if (destroyReady && !pendingRemoval && !deferCleanup) { self._cleanup(); } }; // remove DOM element if (remove && this.$el) { pendingRemoval = true; this.$remove(function () { pendingRemoval = false; cleanupIfPossible(); }); } this._callHook('beforeDestroy'); this._isBeingDestroyed = true; var i; // remove self from parent. only necessary // if parent is not being destroyed as well. var parent = this.$parent; if (parent && !parent._isBeingDestroyed) { parent.$children.$remove(this); // unregister ref (remove: true) this._updateRef(true); } // destroy all children. i = this.$children.length; while (i--) { this.$children[i].$destroy(); } // teardown props if (this._propsUnlinkFn) { this._propsUnlinkFn(); } // teardown all directives. this also tearsdown all // directive-owned watchers. if (this._unlinkFn) { this._unlinkFn(); } i = this._watchers.length; while (i--) { this._watchers[i].teardown(); } // remove reference to self on $el if (this.$el) { this.$el.__vue__ = null; } destroyReady = true; cleanupIfPossible(); }; /** * Clean up to ensure garbage collection. * This is called after the leave transition if there * is any. */ Vue.prototype._cleanup = function () { if (this._isDestroyed) { return; } // remove self from owner fragment // do it in cleanup so that we can call $destroy with // defer right when a fragment is about to be removed. if (this._frag) { this._frag.children.$remove(this); } // remove reference from data ob // frozen object may not have observer. if (this._data && this._data.__ob__) { this._data.__ob__.removeVm(this); } // Clean up references to private properties and other // instances. preserve reference to _data so that proxy // accessors still work. The only potential side effect // here is that mutating the instance after it's destroyed // may affect the state of other components that are still // observing the same object, but that seems to be a // reasonable responsibility for the user rather than // always throwing an error on them. this.$el = this.$parent = this.$root = this.$children = this._watchers = this._context = this._scope = this._directives = null; // call the last hook... this._isDestroyed = true; this._callHook('destroyed'); // turn off all instance listeners. this.$off(); }; } function miscMixin (Vue) { /** * Apply a list of filter (descriptors) to a value. * Using plain for loops here because this will be called in * the getter of any watcher with filters so it is very * performance sensitive. * * @param {*} value * @param {*} [oldValue] * @param {Array} filters * @param {Boolean} write * @return {*} */ Vue.prototype._applyFilters = function (value, oldValue, filters, write) { var filter, fn, args, arg, offset, i, l, j, k; for (i = 0, l = filters.length; i < l; i++) { filter = filters[write ? l - i - 1 : i]; fn = resolveAsset(this.$options, 'filters', filter.name, true); if (!fn) continue; fn = write ? fn.write : fn.read || fn; if (typeof fn !== 'function') continue; args = write ? [value, oldValue] : [value]; offset = write ? 2 : 1; if (filter.args) { for (j = 0, k = filter.args.length; j < k; j++) { arg = filter.args[j]; args[j + offset] = arg.dynamic ? this.$get(arg.value) : arg.value; } } value = fn.apply(this, args); } return value; }; /** * Resolve a component, depending on whether the component * is defined normally or using an async factory function. * Resolves synchronously if already resolved, otherwise * resolves asynchronously and caches the resolved * constructor on the factory. * * @param {String|Function} value * @param {Function} cb */ Vue.prototype._resolveComponent = function (value, cb) { var factory; if (typeof value === 'function') { factory = value; } else { factory = resolveAsset(this.$options, 'components', value, true); } /* istanbul ignore if */ if (!factory) { return; } // async component factory if (!factory.options) { if (factory.resolved) { // cached cb(factory.resolved); } else if (factory.requested) { // pool callbacks factory.pendingCallbacks.push(cb); } else { factory.requested = true; var cbs = factory.pendingCallbacks = [cb]; factory.call(this, function resolve(res) { if (isPlainObject(res)) { res = Vue.extend(res); } // cache resolved factory.resolved = res; // invoke callbacks for (var i = 0, l = cbs.length; i < l; i++) { cbs[i](res); } }, function reject(reason) { process.env.NODE_ENV !== 'production' && warn('Failed to resolve async component' + (typeof value === 'string' ? ': ' + value : '') + '. ' + (reason ? '\nReason: ' + reason : '')); }); } } else { // normal component cb(factory); } }; } var filterRE$1 = /[^|]\|[^|]/; function dataAPI (Vue) { /** * Get the value from an expression on this vm. * * @param {String} exp * @param {Boolean} [asStatement] * @return {*} */ Vue.prototype.$get = function (exp, asStatement) { var res = parseExpression(exp); if (res) { if (asStatement) { var self = this; return function statementHandler() { self.$arguments = toArray(arguments); var result = res.get.call(self, self); self.$arguments = null; return result; }; } else { try { return res.get.call(this, this); } catch (e) {} } } }; /** * Set the value from an expression on this vm. * The expression must be a valid left-hand * expression in an assignment. * * @param {String} exp * @param {*} val */ Vue.prototype.$set = function (exp, val) { var res = parseExpression(exp, true); if (res && res.set) { res.set.call(this, this, val); } }; /** * Delete a property on the VM * * @param {String} key */ Vue.prototype.$delete = function (key) { del(this._data, key); }; /** * Watch an expression, trigger callback when its * value changes. * * @param {String|Function} expOrFn * @param {Function} cb * @param {Object} [options] * - {Boolean} deep * - {Boolean} immediate * @return {Function} - unwatchFn */ Vue.prototype.$watch = function (expOrFn, cb, options) { var vm = this; var parsed; if (typeof expOrFn === 'string') { parsed = parseDirective(expOrFn); expOrFn = parsed.expression; } var watcher = new Watcher(vm, expOrFn, cb, { deep: options && options.deep, sync: options && options.sync, filters: parsed && parsed.filters, user: !options || options.user !== false }); if (options && options.immediate) { cb.call(vm, watcher.value); } return function unwatchFn() { watcher.teardown(); }; }; /** * Evaluate a text directive, including filters. * * @param {String} text * @param {Boolean} [asStatement] * @return {String} */ Vue.prototype.$eval = function (text, asStatement) { // check for filters. if (filterRE$1.test(text)) { var dir = parseDirective(text); // the filter regex check might give false positive // for pipes inside strings, so it's possible that // we don't get any filters here var val = this.$get(dir.expression, asStatement); return dir.filters ? this._applyFilters(val, null, dir.filters) : val; } else { // no filter return this.$get(text, asStatement); } }; /** * Interpolate a piece of template text. * * @param {String} text * @return {String} */ Vue.prototype.$interpolate = function (text) { var tokens = parseText(text); var vm = this; if (tokens) { if (tokens.length === 1) { return vm.$eval(tokens[0].value) + ''; } else { return tokens.map(function (token) { return token.tag ? vm.$eval(token.value) : token.value; }).join(''); } } else { return text; } }; /** * Log instance data as a plain JS object * so that it is easier to inspect in console. * This method assumes console is available. * * @param {String} [path] */ Vue.prototype.$log = function (path) { var data = path ? getPath(this._data, path) : this._data; if (data) { data = clean(data); } // include computed fields if (!path) { var key; for (key in this.$options.computed) { data[key] = clean(this[key]); } if (this._props) { for (key in this._props) { data[key] = clean(this[key]); } } } console.log(data); }; /** * "clean" a getter/setter converted object into a plain * object copy. * * @param {Object} - obj * @return {Object} */ function clean(obj) { return JSON.parse(JSON.stringify(obj)); } } function domAPI (Vue) { /** * Convenience on-instance nextTick. The callback is * auto-bound to the instance, and this avoids component * modules having to rely on the global Vue. * * @param {Function} fn */ Vue.prototype.$nextTick = function (fn) { nextTick(fn, this); }; /** * Append instance to target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$appendTo = function (target, cb, withTransition) { return insert(this, target, cb, withTransition, append, appendWithTransition); }; /** * Prepend instance to target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$prependTo = function (target, cb, withTransition) { target = query(target); if (target.hasChildNodes()) { this.$before(target.firstChild, cb, withTransition); } else { this.$appendTo(target, cb, withTransition); } return this; }; /** * Insert instance before target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$before = function (target, cb, withTransition) { return insert(this, target, cb, withTransition, beforeWithCb, beforeWithTransition); }; /** * Insert instance after target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$after = function (target, cb, withTransition) { target = query(target); if (target.nextSibling) { this.$before(target.nextSibling, cb, withTransition); } else { this.$appendTo(target.parentNode, cb, withTransition); } return this; }; /** * Remove instance from DOM * * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$remove = function (cb, withTransition) { if (!this.$el.parentNode) { return cb && cb(); } var inDocument = this._isAttached && inDoc(this.$el); // if we are not in document, no need to check // for transitions if (!inDocument) withTransition = false; var self = this; var realCb = function realCb() { if (inDocument) self._callHook('detached'); if (cb) cb(); }; if (this._isFragment) { removeNodeRange(this._fragmentStart, this._fragmentEnd, this, this._fragment, realCb); } else { var op = withTransition === false ? removeWithCb : removeWithTransition; op(this.$el, this, realCb); } return this; }; /** * Shared DOM insertion function. * * @param {Vue} vm * @param {Element} target * @param {Function} [cb] * @param {Boolean} [withTransition] * @param {Function} op1 - op for non-transition insert * @param {Function} op2 - op for transition insert * @return vm */ function insert(vm, target, cb, withTransition, op1, op2) { target = query(target); var targetIsDetached = !inDoc(target); var op = withTransition === false || targetIsDetached ? op1 : op2; var shouldCallHook = !targetIsDetached && !vm._isAttached && !inDoc(vm.$el); if (vm._isFragment) { mapNodeRange(vm._fragmentStart, vm._fragmentEnd, function (node) { op(node, target, vm); }); cb && cb(); } else { op(vm.$el, target, vm, cb); } if (shouldCallHook) { vm._callHook('attached'); } return vm; } /** * Check for selectors * * @param {String|Element} el */ function query(el) { return typeof el === 'string' ? document.querySelector(el) : el; } /** * Append operation that takes a callback. * * @param {Node} el * @param {Node} target * @param {Vue} vm - unused * @param {Function} [cb] */ function append(el, target, vm, cb) { target.appendChild(el); if (cb) cb(); } /** * InsertBefore operation that takes a callback. * * @param {Node} el * @param {Node} target * @param {Vue} vm - unused * @param {Function} [cb] */ function beforeWithCb(el, target, vm, cb) { before(el, target); if (cb) cb(); } /** * Remove operation that takes a callback. * * @param {Node} el * @param {Vue} vm - unused * @param {Function} [cb] */ function removeWithCb(el, vm, cb) { remove(el); if (cb) cb(); } } function eventsAPI (Vue) { /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn */ Vue.prototype.$on = function (event, fn) { (this._events[event] || (this._events[event] = [])).push(fn); modifyListenerCount(this, event, 1); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn */ Vue.prototype.$once = function (event, fn) { var self = this; function on() { self.$off(event, on); fn.apply(this, arguments); } on.fn = fn; this.$on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn */ Vue.prototype.$off = function (event, fn) { var cbs; // all if (!arguments.length) { if (this.$parent) { for (event in this._events) { cbs = this._events[event]; if (cbs) { modifyListenerCount(this, event, -cbs.length); } } } this._events = {}; return this; } // specific event cbs = this._events[event]; if (!cbs) { return this; } if (arguments.length === 1) { modifyListenerCount(this, event, -cbs.length); this._events[event] = null; return this; } // specific handler var cb; var i = cbs.length; while (i--) { cb = cbs[i]; if (cb === fn || cb.fn === fn) { modifyListenerCount(this, event, -1); cbs.splice(i, 1); break; } } return this; }; /** * Trigger an event on self. * * @param {String|Object} event * @return {Boolean} shouldPropagate */ Vue.prototype.$emit = function (event) { var isSource = typeof event === 'string'; event = isSource ? event : event.name; var cbs = this._events[event]; var shouldPropagate = isSource || !cbs; if (cbs) { cbs = cbs.length > 1 ? toArray(cbs) : cbs; // this is a somewhat hacky solution to the question raised // in #2102: for an inline component listener like <comp @test="doThis">, // the propagation handling is somewhat broken. Therefore we // need to treat these inline callbacks differently. var hasParentCbs = isSource && cbs.some(function (cb) { return cb._fromParent; }); if (hasParentCbs) { shouldPropagate = false; } var args = toArray(arguments, 1); for (var i = 0, l = cbs.length; i < l; i++) { var cb = cbs[i]; var res = cb.apply(this, args); if (res === true && (!hasParentCbs || cb._fromParent)) { shouldPropagate = true; } } } return shouldPropagate; }; /** * Recursively broadcast an event to all children instances. * * @param {String|Object} event * @param {...*} additional arguments */ Vue.prototype.$broadcast = function (event) { var isSource = typeof event === 'string'; event = isSource ? event : event.name; // if no child has registered for this event, // then there's no need to broadcast. if (!this._eventsCount[event]) return; var children = this.$children; var args = toArray(arguments); if (isSource) { // use object event to indicate non-source emit // on children args[0] = { name: event, source: this }; } for (var i = 0, l = children.length; i < l; i++) { var child = children[i]; var shouldPropagate = child.$emit.apply(child, args); if (shouldPropagate) { child.$broadcast.apply(child, args); } } return this; }; /** * Recursively propagate an event up the parent chain. * * @param {String} event * @param {...*} additional arguments */ Vue.prototype.$dispatch = function (event) { var shouldPropagate = this.$emit.apply(this, arguments); if (!shouldPropagate) return; var parent = this.$parent; var args = toArray(arguments); // use object event to indicate non-source emit // on parents args[0] = { name: event, source: this }; while (parent) { shouldPropagate = parent.$emit.apply(parent, args); parent = shouldPropagate ? parent.$parent : null; } return this; }; /** * Modify the listener counts on all parents. * This bookkeeping allows $broadcast to return early when * no child has listened to a certain event. * * @param {Vue} vm * @param {String} event * @param {Number} count */ var hookRE = /^hook:/; function modifyListenerCount(vm, event, count) { var parent = vm.$parent; // hooks do not get broadcasted so no need // to do bookkeeping for them if (!parent || !count || hookRE.test(event)) return; while (parent) { parent._eventsCount[event] = (parent._eventsCount[event] || 0) + count; parent = parent.$parent; } } } function lifecycleAPI (Vue) { /** * Set instance target element and kick off the compilation * process. The passed in `el` can be a selector string, an * existing Element, or a DocumentFragment (for block * instances). * * @param {Element|DocumentFragment|string} el * @public */ Vue.prototype.$mount = function (el) { if (this._isCompiled) { process.env.NODE_ENV !== 'production' && warn('$mount() should be called only once.', this); return; } el = query(el); if (!el) { el = document.createElement('div'); } this._compile(el); this._initDOMHooks(); if (inDoc(this.$el)) { this._callHook('attached'); ready.call(this); } else { this.$once('hook:attached', ready); } return this; }; /** * Mark an instance as ready. */ function ready() { this._isAttached = true; this._isReady = true; this._callHook('ready'); } /** * Teardown the instance, simply delegate to the internal * _destroy. * * @param {Boolean} remove * @param {Boolean} deferCleanup */ Vue.prototype.$destroy = function (remove, deferCleanup) { this._destroy(remove, deferCleanup); }; /** * Partially compile a piece of DOM and return a * decompile function. * * @param {Element|DocumentFragment} el * @param {Vue} [host] * @param {Object} [scope] * @param {Fragment} [frag] * @return {Function} */ Vue.prototype.$compile = function (el, host, scope, frag) { return compile(el, this.$options, true)(this, el, host, scope, frag); }; } /** * The exposed Vue constructor. * * API conventions: * - public API methods/properties are prefixed with `$` * - internal methods/properties are prefixed with `_` * - non-prefixed properties are assumed to be proxied user * data. * * @constructor * @param {Object} [options] * @public */ function Vue(options) { this._init(options); } // install internals initMixin(Vue); stateMixin(Vue); eventsMixin(Vue); lifecycleMixin(Vue); miscMixin(Vue); // install instance APIs dataAPI(Vue); domAPI(Vue); eventsAPI(Vue); lifecycleAPI(Vue); var slot = { priority: SLOT, params: ['name'], bind: function bind() { // this was resolved during component transclusion var name = this.params.name || 'default'; var content = this.vm._slotContents && this.vm._slotContents[name]; if (!content || !content.hasChildNodes()) { this.fallback(); } else { this.compile(content.cloneNode(true), this.vm._context, this.vm); } }, compile: function compile(content, context, host) { if (content && context) { if (this.el.hasChildNodes() && content.childNodes.length === 1 && content.childNodes[0].nodeType === 1 && content.childNodes[0].hasAttribute('v-if')) { // if the inserted slot has v-if // inject fallback content as the v-else var elseBlock = document.createElement('template'); elseBlock.setAttribute('v-else', ''); elseBlock.innerHTML = this.el.innerHTML; // the else block should be compiled in child scope elseBlock._context = this.vm; content.appendChild(elseBlock); } var scope = host ? host._scope : this._scope; this.unlink = context.$compile(content, host, scope, this._frag); } if (content) { replace(this.el, content); } else { remove(this.el); } }, fallback: function fallback() { this.compile(extractContent(this.el, true), this.vm); }, unbind: function unbind() { if (this.unlink) { this.unlink(); } } }; var partial = { priority: PARTIAL, params: ['name'], // watch changes to name for dynamic partials paramWatchers: { name: function name(value) { vIf.remove.call(this); if (value) { this.insert(value); } } }, bind: function bind() { this.anchor = createAnchor('v-partial'); replace(this.el, this.anchor); this.insert(this.params.name); }, insert: function insert(id) { var partial = resolveAsset(this.vm.$options, 'partials', id, true); if (partial) { this.factory = new FragmentFactory(this.vm, partial); vIf.insert.call(this); } }, unbind: function unbind() { if (this.frag) { this.frag.destroy(); } } }; var elementDirectives = { slot: slot, partial: partial }; var convertArray = vFor._postProcess; /** * Limit filter for arrays * * @param {Number} n * @param {Number} offset (Decimal expected) */ function limitBy(arr, n, offset) { offset = offset ? parseInt(offset, 10) : 0; n = toNumber(n); return typeof n === 'number' ? arr.slice(offset, offset + n) : arr; } /** * Filter filter for arrays * * @param {String} search * @param {String} [delimiter] * @param {String} ...dataKeys */ function filterBy(arr, search, delimiter) { arr = convertArray(arr); if (search == null) { return arr; } if (typeof search === 'function') { return arr.filter(search); } // cast to lowercase string search = ('' + search).toLowerCase(); // allow optional `in` delimiter // because why not var n = delimiter === 'in' ? 3 : 2; // extract and flatten keys var keys = Array.prototype.concat.apply([], toArray(arguments, n)); var res = []; var item, key, val, j; for (var i = 0, l = arr.length; i < l; i++) { item = arr[i]; val = item && item.$value || item; j = keys.length; if (j) { while (j--) { key = keys[j]; if (key === '$key' && contains(item.$key, search) || contains(getPath(val, key), search)) { res.push(item); break; } } } else if (contains(item, search)) { res.push(item); } } return res; } /** * Filter filter for arrays * * @param {String|Array<String>|Function} ...sortKeys * @param {Number} [order] */ function orderBy(arr) { var comparator = null; var sortKeys = undefined; arr = convertArray(arr); // determine order (last argument) var args = toArray(arguments, 1); var order = args[args.length - 1]; if (typeof order === 'number') { order = order < 0 ? -1 : 1; args = args.length > 1 ? args.slice(0, -1) : args; } else { order = 1; } // determine sortKeys & comparator var firstArg = args[0]; if (!firstArg) { return arr; } else if (typeof firstArg === 'function') { // custom comparator comparator = function (a, b) { return firstArg(a, b) * order; }; } else { // string keys. flatten first sortKeys = Array.prototype.concat.apply([], args); comparator = function (a, b, i) { i = i || 0; return i >= sortKeys.length - 1 ? baseCompare(a, b, i) : baseCompare(a, b, i) || comparator(a, b, i + 1); }; } function baseCompare(a, b, sortKeyIndex) { var sortKey = sortKeys[sortKeyIndex]; if (sortKey) { if (sortKey !== '$key') { if (isObject(a) && '$value' in a) a = a.$value; if (isObject(b) && '$value' in b) b = b.$value; } a = isObject(a) ? getPath(a, sortKey) : a; b = isObject(b) ? getPath(b, sortKey) : b; } return a === b ? 0 : a > b ? order : -order; } // sort on a copy to avoid mutating original array return arr.slice().sort(comparator); } /** * String contain helper * * @param {*} val * @param {String} search */ function contains(val, search) { var i; if (isPlainObject(val)) { var keys = Object.keys(val); i = keys.length; while (i--) { if (contains(val[keys[i]], search)) { return true; } } } else if (isArray(val)) { i = val.length; while (i--) { if (contains(val[i], search)) { return true; } } } else if (val != null) { return val.toString().toLowerCase().indexOf(search) > -1; } } var digitsRE = /(\d{3})(?=\d)/g; // asset collections must be a plain object. var filters = { orderBy: orderBy, filterBy: filterBy, limitBy: limitBy, /** * Stringify value. * * @param {Number} indent */ json: { read: function read(value, indent) { return typeof value === 'string' ? value : JSON.stringify(value, null, Number(indent) || 2); }, write: function write(value) { try { return JSON.parse(value); } catch (e) { return value; } } }, /** * 'abc' => 'Abc' */ capitalize: function capitalize(value) { if (!value && value !== 0) return ''; value = value.toString(); return value.charAt(0).toUpperCase() + value.slice(1); }, /** * 'abc' => 'ABC' */ uppercase: function uppercase(value) { return value || value === 0 ? value.toString().toUpperCase() : ''; }, /** * 'AbC' => 'abc' */ lowercase: function lowercase(value) { return value || value === 0 ? value.toString().toLowerCase() : ''; }, /** * 12345 => $12,345.00 * * @param {String} sign * @param {Number} decimals Decimal places */ currency: function currency(value, _currency, decimals) { value = parseFloat(value); if (!isFinite(value) || !value && value !== 0) return ''; _currency = _currency != null ? _currency : '$'; decimals = decimals != null ? decimals : 2; var stringified = Math.abs(value).toFixed(decimals); var _int = decimals ? stringified.slice(0, -1 - decimals) : stringified; var i = _int.length % 3; var head = i > 0 ? _int.slice(0, i) + (_int.length > 3 ? ',' : '') : ''; var _float = decimals ? stringified.slice(-1 - decimals) : ''; var sign = value < 0 ? '-' : ''; return sign + _currency + head + _int.slice(i).replace(digitsRE, '$1,') + _float; }, /** * 'item' => 'items' * * @params * an array of strings corresponding to * the single, double, triple ... forms of the word to * be pluralized. When the number to be pluralized * exceeds the length of the args, it will use the last * entry in the array. * * e.g. ['single', 'double', 'triple', 'multiple'] */ pluralize: function pluralize(value) { var args = toArray(arguments, 1); return args.length > 1 ? args[value % 10 - 1] || args[args.length - 1] : args[0] + (value === 1 ? '' : 's'); }, /** * Debounce a handler function. * * @param {Function} handler * @param {Number} delay = 300 * @return {Function} */ debounce: function debounce(handler, delay) { if (!handler) return; if (!delay) { delay = 300; } return _debounce(handler, delay); } }; function installGlobalAPI (Vue) { /** * Vue and every constructor that extends Vue has an * associated options object, which can be accessed during * compilation steps as `this.constructor.options`. * * These can be seen as the default options of every * Vue instance. */ Vue.options = { directives: directives, elementDirectives: elementDirectives, filters: filters, transitions: {}, components: {}, partials: {}, replace: true }; /** * Expose useful internals */ Vue.util = util; Vue.config = config; Vue.set = set; Vue['delete'] = del; Vue.nextTick = nextTick; /** * The following are exposed for advanced usage / plugins */ Vue.compiler = compiler; Vue.FragmentFactory = FragmentFactory; Vue.internalDirectives = internalDirectives; Vue.parsers = { path: path, text: text, template: template, directive: directive, expression: expression }; /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ Vue.cid = 0; var cid = 1; /** * Class inheritance * * @param {Object} extendOptions */ Vue.extend = function (extendOptions) { extendOptions = extendOptions || {}; var Super = this; var isFirstExtend = Super.cid === 0; if (isFirstExtend && extendOptions._Ctor) { return extendOptions._Ctor; } var name = extendOptions.name || Super.options.name; if (process.env.NODE_ENV !== 'production') { if (!/^[a-zA-Z][\w-]*$/.test(name)) { warn('Invalid component name: "' + name + '". Component names ' + 'can only contain alphanumeric characaters and the hyphen.'); name = null; } } var Sub = createClass(name || 'VueComponent'); Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub; Sub.cid = cid++; Sub.options = mergeOptions(Super.options, extendOptions); Sub['super'] = Super; // allow further extension Sub.extend = Super.extend; // create asset registers, so extended classes // can have their private assets too. config._assetTypes.forEach(function (type) { Sub[type] = Super[type]; }); // enable recursive self-lookup if (name) { Sub.options.components[name] = Sub; } // cache constructor if (isFirstExtend) { extendOptions._Ctor = Sub; } return Sub; }; /** * A function that returns a sub-class constructor with the * given name. This gives us much nicer output when * logging instances in the console. * * @param {String} name * @return {Function} */ function createClass(name) { /* eslint-disable no-new-func */ return new Function('return function ' + classify(name) + ' (options) { this._init(options) }')(); /* eslint-enable no-new-func */ } /** * Plugin system * * @param {Object} plugin */ Vue.use = function (plugin) { /* istanbul ignore if */ if (plugin.installed) { return; } // additional parameters var args = toArray(arguments, 1); args.unshift(this); if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args); } else { plugin.apply(null, args); } plugin.installed = true; return this; }; /** * Apply a global mixin by merging it into the default * options. */ Vue.mixin = function (mixin) { Vue.options = mergeOptions(Vue.options, mixin); }; /** * Create asset registration methods with the following * signature: * * @param {String} id * @param {*} definition */ config._assetTypes.forEach(function (type) { Vue[type] = function (id, definition) { if (!definition) { return this.options[type + 's'][id]; } else { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { if (type === 'component' && (commonTagRE.test(id) || reservedTagRE.test(id))) { warn('Do not use built-in or reserved HTML elements as component ' + 'id: ' + id); } } if (type === 'component' && isPlainObject(definition)) { definition.name = id; definition = Vue.extend(definition); } this.options[type + 's'][id] = definition; return definition; } }; }); // expose internal transition API extend(Vue.transition, transition); } installGlobalAPI(Vue); Vue.version = '1.0.24'; // devtools global hook /* istanbul ignore next */ setTimeout(function () { if (config.devtools) { if (devtools) { devtools.emit('init', Vue); } else if (process.env.NODE_ENV !== 'production' && inBrowser && /Chrome\/\d+/.test(window.navigator.userAgent)) { console.log('Download the Vue Devtools for a better development experience:\n' + 'path_to_url } } }, 0); module.exports = Vue; ```
/content/code_sandbox/public/vendor/vue/dist/vue.common.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
65,906
```javascript /*! * Vue.js v1.0.24 * (c) 2016 Evan You */ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.Vue=e()}(this,function(){"use strict";function t(e,n,r){if(i(e,n))return void(e[n]=r);if(e._isVue)return void t(e._data,n,r);var s=e.__ob__;if(!s)return void(e[n]=r);if(s.convert(n,r),s.dep.notify(),s.vms)for(var o=s.vms.length;o--;){var a=s.vms[o];a._proxy(n),a._digest()}return r}function e(t,e){if(i(t,e)){delete t[e];var n=t.__ob__;if(!n)return void(t._isVue&&(delete t._data[e],t._digest()));if(n.dep.notify(),n.vms)for(var r=n.vms.length;r--;){var s=n.vms[r];s._unproxy(e),s._digest()}}}function i(t,e){return Ai.call(t,e)}function n(t){return Oi.test(t)}function r(t){var e=(t+"").charCodeAt(0);return 36===e||95===e}function s(t){return null==t?"":t.toString()}function o(t){if("string"!=typeof t)return t;var e=Number(t);return isNaN(e)?t:e}function a(t){return"true"===t?!0:"false"===t?!1:t}function h(t){var e=t.charCodeAt(0),i=t.charCodeAt(t.length-1);return e!==i||34!==e&&39!==e?t:t.slice(1,-1)}function l(t){return t.replace(Ti,c)}function c(t,e){return e?e.toUpperCase():""}function u(t){return t.replace(Ni,"$1-$2").toLowerCase()}function f(t){return t.replace(ji,c)}function p(t,e){return function(i){var n=arguments.length;return n?n>1?t.apply(e,arguments):t.call(e,i):t.call(e)}}function d(t,e){e=e||0;for(var i=t.length-e,n=new Array(i);i--;)n[i]=t[i+e];return n}function v(t,e){for(var i=Object.keys(e),n=i.length;n--;)t[i[n]]=e[i[n]];return t}function m(t){return null!==t&&"object"==typeof t}function g(t){return Ei.call(t)===Si}function _(t,e,i,n){Object.defineProperty(t,e,{value:i,enumerable:!!n,writable:!0,configurable:!0})}function y(t,e){var i,n,r,s,o,a=function h(){var a=Date.now()-s;e>a&&a>=0?i=setTimeout(h,e-a):(i=null,o=t.apply(r,n),i||(r=n=null))};return function(){return r=this,n=arguments,s=Date.now(),i||(i=setTimeout(a,e)),o}}function b(t,e){for(var i=t.length;i--;)if(t[i]===e)return i;return-1}function w(t){var e=function i(){return i.cancelled?void 0:t.apply(this,arguments)};return e.cancel=function(){e.cancelled=!0},e}function C(t,e){return t==e||(m(t)&&m(e)?JSON.stringify(t)===JSON.stringify(e):!1)}function $(t){this.size=0,this.limit=t,this.head=this.tail=void 0,this._keymap=Object.create(null)}function k(){var t,e=Xi.slice(rn,en).trim();if(e){t={};var i=e.match(un);t.name=i[0],i.length>1&&(t.args=i.slice(1).map(x))}t&&(Yi.filters=Yi.filters||[]).push(t),rn=en+1}function x(t){if(fn.test(t))return{value:o(t),dynamic:!1};var e=h(t),i=e===t;return{value:i?t:e,dynamic:i}}function A(t){var e=cn.get(t);if(e)return e;for(Xi=t,sn=on=!1,an=hn=ln=0,rn=0,Yi={},en=0,nn=Xi.length;nn>en;en++)if(tn=Ki,Ki=Xi.charCodeAt(en),sn)39===Ki&&92!==tn&&(sn=!sn);else if(on)34===Ki&&92!==tn&&(on=!on);else if(124===Ki&&124!==Xi.charCodeAt(en+1)&&124!==Xi.charCodeAt(en-1))null==Yi.expression?(rn=en+1,Yi.expression=Xi.slice(0,en).trim()):k();else switch(Ki){case 34:on=!0;break;case 39:sn=!0;break;case 40:ln++;break;case 41:ln--;break;case 91:hn++;break;case 93:hn--;break;case 123:an++;break;case 125:an--}return null==Yi.expression?Yi.expression=Xi.slice(0,en).trim():0!==rn&&k(),cn.put(t,Yi),Yi}function O(t){return t.replace(dn,"\\$&")}function T(){var t=O(Cn.delimiters[0]),e=O(Cn.delimiters[1]),i=O(Cn.unsafeDelimiters[0]),n=O(Cn.unsafeDelimiters[1]);mn=new RegExp(i+"((?:.|\\n)+?)"+n+"|"+t+"((?:.|\\n)+?)"+e,"g"),gn=new RegExp("^"+i+".*"+n+"$"),vn=new $(1e3)}function N(t){vn||T();var e=vn.get(t);if(e)return e;if(!mn.test(t))return null;for(var i,n,r,s,o,a,h=[],l=mn.lastIndex=0;i=mn.exec(t);)n=i.index,n>l&&h.push({value:t.slice(l,n)}),r=gn.test(i[0]),s=r?i[1]:i[2],o=s.charCodeAt(0),a=42===o,s=a?s.slice(1):s,h.push({tag:!0,value:s.trim(),html:r,oneTime:a}),l=n+i[0].length;return l<t.length&&h.push({value:t.slice(l)}),vn.put(t,h),h}function j(t,e){return t.length>1?t.map(function(t){return E(t,e)}).join("+"):E(t[0],e,!0)}function E(t,e,i){return t.tag?t.oneTime&&e?'"'+e.$eval(t.value)+'"':S(t.value,i):'"'+t.value+'"'}function S(t,e){if(_n.test(t)){var i=A(t);return i.filters?"this._applyFilters("+i.expression+",null,"+JSON.stringify(i.filters)+",false)":"("+t+")"}return e?t:"("+t+")"}function F(t,e,i,n){R(t,1,function(){e.appendChild(t)},i,n)}function D(t,e,i,n){R(t,1,function(){V(t,e)},i,n)}function P(t,e,i){R(t,-1,function(){z(t)},e,i)}function R(t,e,i,n,r){var s=t.__v_trans;if(!s||!s.hooks&&!Bi||!n._isCompiled||n.$parent&&!n.$parent._isCompiled)return i(),void(r&&r());var o=e>0?"enter":"leave";s[o](i,r)}function L(t){if("string"==typeof t){t=document.querySelector(t)}return t}function H(t){if(!t)return!1;var e=t.ownerDocument.documentElement,i=t.parentNode;return e===t||e===i||!(!i||1!==i.nodeType||!e.contains(i))}function I(t,e){var i=t.getAttribute(e);return null!==i&&t.removeAttribute(e),i}function M(t,e){var i=I(t,":"+e);return null===i&&(i=I(t,"v-bind:"+e)),i}function W(t,e){return t.hasAttribute(e)||t.hasAttribute(":"+e)||t.hasAttribute("v-bind:"+e)}function V(t,e){e.parentNode.insertBefore(t,e)}function B(t,e){e.nextSibling?V(t,e.nextSibling):e.parentNode.appendChild(t)}function z(t){t.parentNode.removeChild(t)}function U(t,e){e.firstChild?V(t,e.firstChild):e.appendChild(t)}function J(t,e){var i=t.parentNode;i&&i.replaceChild(e,t)}function q(t,e,i,n){t.addEventListener(e,i,n)}function Q(t,e,i){t.removeEventListener(e,i)}function G(t){var e=t.className;return"object"==typeof e&&(e=e.baseVal||""),e}function Z(t,e){Hi&&!/svg$/.test(t.namespaceURI)?t.className=e:t.setAttribute("class",e)}function X(t,e){if(t.classList)t.classList.add(e);else{var i=" "+G(t)+" ";i.indexOf(" "+e+" ")<0&&Z(t,(i+e).trim())}}function Y(t,e){if(t.classList)t.classList.remove(e);else{for(var i=" "+G(t)+" ",n=" "+e+" ";i.indexOf(n)>=0;)i=i.replace(n," ");Z(t,i.trim())}t.className||t.removeAttribute("class")}function K(t,e){var i,n;if(it(t)&&at(t.content)&&(t=t.content),t.hasChildNodes())for(tt(t),n=e?document.createDocumentFragment():document.createElement("div");i=t.firstChild;)n.appendChild(i);return n}function tt(t){for(var e;e=t.firstChild,et(e);)t.removeChild(e);for(;e=t.lastChild,et(e);)t.removeChild(e)}function et(t){return t&&(3===t.nodeType&&!t.data.trim()||8===t.nodeType)}function it(t){return t.tagName&&"template"===t.tagName.toLowerCase()}function nt(t,e){var i=Cn.debug?document.createComment(t):document.createTextNode(e?" ":"");return i.__v_anchor=!0,i}function rt(t){if(t.hasAttributes())for(var e=t.attributes,i=0,n=e.length;n>i;i++){var r=e[i].name;if(xn.test(r))return l(r.replace(xn,""))}}function st(t,e,i){for(var n;t!==e;)n=t.nextSibling,i(t),t=n;i(e)}function ot(t,e,i,n,r){function s(){if(a++,o&&a>=h.length){for(var t=0;t<h.length;t++)n.appendChild(h[t]);r&&r()}}var o=!1,a=0,h=[];st(t,e,function(t){t===e&&(o=!0),h.push(t),P(t,i,s)})}function at(t){return t&&11===t.nodeType}function ht(t){if(t.outerHTML)return t.outerHTML;var e=document.createElement("div");return e.appendChild(t.cloneNode(!0)),e.innerHTML}function lt(t,e){var i=t.tagName.toLowerCase(),n=t.hasAttributes();if(An.test(i)||On.test(i)){if(n)return ct(t,e)}else{if(gt(e,"components",i))return{id:i};var r=n&&ct(t,e);if(r)return r}}function ct(t,e){var i=t.getAttribute("is");if(null!=i){if(gt(e,"components",i))return t.removeAttribute("is"),{id:i}}else if(i=M(t,"is"),null!=i)return{id:i,dynamic:!0}}function ut(e,n){var r,s,o;for(r in n)s=e[r],o=n[r],i(e,r)?m(s)&&m(o)&&ut(s,o):t(e,r,o);return e}function ft(t,e){var i=Object.create(t||null);return e?v(i,vt(e)):i}function pt(t){if(t.components)for(var e,i=t.components=vt(t.components),n=Object.keys(i),r=0,s=n.length;s>r;r++){var o=n[r];An.test(o)||On.test(o)||(e=i[o],g(e)&&(i[o]=bi.extend(e)))}}function dt(t){var e,i,n=t.props;if(Fi(n))for(t.props={},e=n.length;e--;)i=n[e],"string"==typeof i?t.props[i]=null:i.name&&(t.props[i.name]=i);else if(g(n)){var r=Object.keys(n);for(e=r.length;e--;)i=n[r[e]],"function"==typeof i&&(n[r[e]]={type:i})}}function vt(t){if(Fi(t)){for(var e,i={},n=t.length;n--;){e=t[n];var r="function"==typeof e?e.options&&e.options.name||e.id:e.name||e.id;r&&(i[r]=e)}return i}return t}function mt(t,e,n){function r(i){var r=Tn[i]||Nn;o[i]=r(t[i],e[i],n,i)}pt(e),dt(e);var s,o={};if(e["extends"]&&(t="function"==typeof e["extends"]?mt(t,e["extends"].options,n):mt(t,e["extends"],n)),e.mixins)for(var a=0,h=e.mixins.length;h>a;a++)t=mt(t,e.mixins[a],n);for(s in t)r(s);for(s in e)i(t,s)||r(s);return o}function gt(t,e,i,n){if("string"==typeof i){var r,s=t[e],o=s[i]||s[r=l(i)]||s[r.charAt(0).toUpperCase()+r.slice(1)];return o}}function _t(){this.id=jn++,this.subs=[]}function yt(t){Dn=!1,t(),Dn=!0}function bt(t){if(this.value=t,this.dep=new _t,_(t,"__ob__",this),Fi(t)){var e=Di?wt:Ct;e(t,Sn,Fn),this.observeArray(t)}else this.walk(t)}function wt(t,e){t.__proto__=e}function Ct(t,e,i){for(var n=0,r=i.length;r>n;n++){var s=i[n];_(t,s,e[s])}}function $t(t,e){if(t&&"object"==typeof t){var n;return i(t,"__ob__")&&t.__ob__ instanceof bt?n=t.__ob__:Dn&&(Fi(t)||g(t))&&Object.isExtensible(t)&&!t._isVue&&(n=new bt(t)),n&&e&&n.addVm(e),n}}function kt(t,e,i){var n=new _t,r=Object.getOwnPropertyDescriptor(t,e);if(!r||r.configurable!==!1){var s=r&&r.get,o=r&&r.set,a=$t(i);Object.defineProperty(t,e,{enumerable:!0,configurable:!0,get:function(){var e=s?s.call(t):i;if(_t.target&&(n.depend(),a&&a.dep.depend(),Fi(e)))for(var r,o=0,h=e.length;h>o;o++)r=e[o],r&&r.__ob__&&r.__ob__.dep.depend();return e},set:function(e){var r=s?s.call(t):i;e!==r&&(o?o.call(t,e):i=e,a=$t(e),n.notify())}})}}function xt(t){t.prototype._init=function(t){t=t||{},this.$el=null,this.$parent=t.parent,this.$root=this.$parent?this.$parent.$root:this,this.$children=[],this.$refs={},this.$els={},this._watchers=[],this._directives=[],this._uid=Rn++,this._isVue=!0,this._events={},this._eventsCount={},this._isFragment=!1,this._fragment=this._fragmentStart=this._fragmentEnd=null,this._isCompiled=this._isDestroyed=this._isReady=this._isAttached=this._isBeingDestroyed=this._vForRemoving=!1,this._unlinkFn=null,this._context=t._context||this.$parent,this._scope=t._scope,this._frag=t._frag,this._frag&&this._frag.children.push(this),this.$parent&&this.$parent.$children.push(this),t=this.$options=mt(this.constructor.options,t,this),this._updateRef(),this._data={},this._callHook("init"),this._initState(),this._initEvents(),this._callHook("created"),t.el&&this.$mount(t.el)}}function At(t){if(void 0===t)return"eof";var e=t.charCodeAt(0);switch(e){case 91:case 93:case 46:case 34:case 39:case 48:return t;case 95:case 36:return"ident";case 32:case 9:case 10:case 13:case 160:case 65279:case 8232:case 8233:return"ws"}return e>=97&&122>=e||e>=65&&90>=e?"ident":e>=49&&57>=e?"number":"else"}function Ot(t){var e=t.trim();return"0"===t.charAt(0)&&isNaN(t)?!1:n(e)?h(e):"*"+e}function Tt(t){function e(){var e=t[c+1];return u===qn&&"'"===e||u===Qn&&'"'===e?(c++,n="\\"+e,p[Hn](),!0):void 0}var i,n,r,s,o,a,h,l=[],c=-1,u=Vn,f=0,p=[];for(p[In]=function(){void 0!==r&&(l.push(r),r=void 0)},p[Hn]=function(){void 0===r?r=n:r+=n},p[Mn]=function(){p[Hn](),f++},p[Wn]=function(){if(f>0)f--,u=Jn,p[Hn]();else{if(f=0,r=Ot(r),r===!1)return!1;p[In]()}};null!=u;)if(c++,i=t[c],"\\"!==i||!e()){if(s=At(i),h=Xn[u],o=h[s]||h["else"]||Zn,o===Zn)return;if(u=o[0],a=p[o[1]],a&&(n=o[2],n=void 0===n?i:n,a()===!1))return;if(u===Gn)return l.raw=t,l}}function Nt(t){var e=Ln.get(t);return e||(e=Tt(t),e&&Ln.put(t,e)),e}function jt(t,e){return Ht(e).get(t)}function Et(e,i,n){var r=e;if("string"==typeof i&&(i=Tt(i)),!i||!m(e))return!1;for(var s,o,a=0,h=i.length;h>a;a++)s=e,o=i[a],"*"===o.charAt(0)&&(o=Ht(o.slice(1)).get.call(r,r)),h-1>a?(e=e[o],m(e)||(e={},t(s,o,e))):Fi(e)?e.$set(o,n):o in e?e[o]=n:t(e,o,n);return!0}function St(t,e){var i=ur.length;return ur[i]=e?t.replace(sr,"\\n"):t,'"'+i+'"'}function Ft(t){var e=t.charAt(0),i=t.slice(1);return er.test(i)?t:(i=i.indexOf('"')>-1?i.replace(ar,Dt):i,e+"scope."+i)}function Dt(t,e){return ur[e]}function Pt(t){nr.test(t),ur.length=0;var e=t.replace(or,St).replace(rr,"");return e=(" "+e).replace(lr,Ft).replace(ar,Dt),Rt(e)}function Rt(t){try{return new Function("scope","return "+t+";")}catch(e){}}function Lt(t){var e=Nt(t);return e?function(t,i){Et(t,e,i)}:void 0}function Ht(t,e){t=t.trim();var i=Kn.get(t);if(i)return e&&!i.set&&(i.set=Lt(i.exp)),i;var n={exp:t};return n.get=It(t)&&t.indexOf("[")<0?Rt("scope."+t):Pt(t),e&&(n.set=Lt(t)),Kn.put(t,n),n}function It(t){return hr.test(t)&&!cr.test(t)&&"Math."!==t.slice(0,5)}function Mt(){pr.length=0,dr.length=0,vr={},mr={},gr=!1}function Wt(){for(var t=!0;t;)t=!1,Vt(pr),Vt(dr),pr.length?t=!0:(Ri&&Cn.devtools&&Ri.emit("flush"),Mt())}function Vt(t){for(var e=0;e<t.length;e++){var i=t[e],n=i.id;vr[n]=null,i.run()}t.length=0}function Bt(t){var e=t.id;if(null==vr[e]){var i=t.user?dr:pr;vr[e]=i.length,i.push(t),gr||(gr=!0,Qi(Wt))}}function zt(t,e,i,n){n&&v(this,n);var r="function"==typeof e;if(this.vm=t,t._watchers.push(this),this.expression=e,this.cb=i,this.id=++_r,this.active=!0,this.dirty=this.lazy,this.deps=[],this.newDeps=[],this.depIds=new Gi,this.newDepIds=new Gi,this.prevError=null,r)this.getter=e,this.setter=void 0;else{var s=Ht(e,this.twoWay);this.getter=s.get,this.setter=s.set}this.value=this.lazy?void 0:this.get(),this.queued=this.shallow=!1}function Ut(t,e){var i=void 0,n=void 0;e||(e=yr,e.clear());var r=Fi(t),s=m(t);if(r||s){if(t.__ob__){var o=t.__ob__.dep.id;if(e.has(o))return;e.add(o)}if(r)for(i=t.length;i--;)Ut(t[i],e);else if(s)for(n=Object.keys(t),i=n.length;i--;)Ut(t[n[i]],e)}}function Jt(t){return it(t)&&at(t.content)}function qt(t,e){var i=e?t:t.trim(),n=wr.get(i);if(n)return n;var r=document.createDocumentFragment(),s=t.match(kr),o=xr.test(t);if(s||o){var a=s&&s[1],h=$r[a]||$r.efault,l=h[0],c=h[1],u=h[2],f=document.createElement("div");for(f.innerHTML=c+t+u;l--;)f=f.lastChild;for(var p;p=f.firstChild;)r.appendChild(p)}else r.appendChild(document.createTextNode(t));return e||tt(r),wr.put(i,r),r}function Qt(t){if(Jt(t))return qt(t.innerHTML);if("SCRIPT"===t.tagName)return qt(t.textContent);for(var e,i=Gt(t),n=document.createDocumentFragment();e=i.firstChild;)n.appendChild(e);return tt(n),n}function Gt(t){if(!t.querySelectorAll)return t.cloneNode();var e,i,n,r=t.cloneNode(!0);if(Ar){var s=r;if(Jt(t)&&(t=t.content,s=r.content),i=t.querySelectorAll("template"),i.length)for(n=s.querySelectorAll("template"),e=n.length;e--;)n[e].parentNode.replaceChild(Gt(i[e]),n[e])}if(Or)if("TEXTAREA"===t.tagName)r.value=t.value;else if(i=t.querySelectorAll("textarea"),i.length)for(n=r.querySelectorAll("textarea"),e=n.length;e--;)n[e].value=i[e].value;return r}function Zt(t,e,i){var n,r;return at(t)?(tt(t),e?Gt(t):t):("string"==typeof t?i||"#"!==t.charAt(0)?r=qt(t,i):(r=Cr.get(t),r||(n=document.getElementById(t.slice(1)),n&&(r=Qt(n),Cr.put(t,r)))):t.nodeType&&(r=Qt(t)),r&&e?Gt(r):r)}function Xt(t,e,i,n,r,s){this.children=[],this.childFrags=[],this.vm=e,this.scope=r,this.inserted=!1,this.parentFrag=s,s&&s.childFrags.push(this),this.unlink=t(e,i,n,r,this);var o=this.single=1===i.childNodes.length&&!i.childNodes[0].__v_anchor;o?(this.node=i.childNodes[0],this.before=Yt,this.remove=Kt):(this.node=nt("fragment-start"),this.end=nt("fragment-end"),this.frag=i,U(this.node,i),i.appendChild(this.end),this.before=te,this.remove=ee),this.node.__v_frag=this}function Yt(t,e){this.inserted=!0;var i=e!==!1?D:V;i(this.node,t,this.vm),H(this.node)&&this.callHook(ie)}function Kt(){this.inserted=!1;var t=H(this.node),e=this;this.beforeRemove(),P(this.node,this.vm,function(){t&&e.callHook(ne),e.destroy()})}function te(t,e){this.inserted=!0;var i=this.vm,n=e!==!1?D:V;st(this.node,this.end,function(e){n(e,t,i)}),H(this.node)&&this.callHook(ie)}function ee(){this.inserted=!1;var t=this,e=H(this.node);this.beforeRemove(),ot(this.node,this.end,this.vm,this.frag,function(){e&&t.callHook(ne),t.destroy()})}function ie(t){!t._isAttached&&H(t.$el)&&t._callHook("attached")}function ne(t){t._isAttached&&!H(t.$el)&&t._callHook("detached")}function re(t,e){this.vm=t;var i,n="string"==typeof e;n||it(e)&&!e.hasAttribute("v-if")?i=Zt(e,!0):(i=document.createDocumentFragment(),i.appendChild(e)),this.template=i;var r,s=t.constructor.cid;if(s>0){var o=s+(n?e:ht(e));r=jr.get(o),r||(r=Fe(i,t.$options,!0),jr.put(o,r))}else r=Fe(i,t.$options,!0);this.linker=r}function se(t,e,i){var n=t.node.previousSibling;if(n){for(t=n.__v_frag;!(t&&t.forId===i&&t.inserted||n===e);){if(n=n.previousSibling,!n)return;t=n.__v_frag}return t}}function oe(t){var e=t.node;if(t.end)for(;!e.__vue__&&e!==t.end&&e.nextSibling;)e=e.nextSibling;return e.__vue__}function ae(t){for(var e=-1,i=new Array(Math.floor(t));++e<t;)i[e]=e;return i}function he(t,e,i,n){return n?"$index"===n?t:n.charAt(0).match(/\w/)?jt(i,n):i[n]:e||i}function le(t,e,i){for(var n,r,s,o=e?[]:null,a=0,h=t.options.length;h>a;a++)if(n=t.options[a],s=i?n.hasAttribute("selected"):n.selected){if(r=n.hasOwnProperty("_value")?n._value:n.value,!e)return r;o.push(r)}return o}function ce(t,e){for(var i=t.length;i--;)if(C(t[i],e))return i;return-1}function ue(t,e){var i=e.map(function(t){var e=t.charCodeAt(0);return e>47&&58>e?parseInt(t,10):1===t.length&&(e=t.toUpperCase().charCodeAt(0),e>64&&91>e)?e:Xr[t]});return i=[].concat.apply([],i),function(e){return i.indexOf(e.keyCode)>-1?t.call(this,e):void 0}}function fe(t){return function(e){return e.stopPropagation(),t.call(this,e)}}function pe(t){return function(e){return e.preventDefault(),t.call(this,e)}}function de(t){return function(e){return e.target===e.currentTarget?t.call(this,e):void 0}}function ve(t){if(is[t])return is[t];var e=me(t);return is[t]=is[e]=e,e}function me(t){t=u(t);var e=l(t),i=e.charAt(0).toUpperCase()+e.slice(1);ns||(ns=document.createElement("div"));var n,r=Kr.length;if("filter"!==e&&e in ns.style)return{kebab:t,camel:e};for(;r--;)if(n=ts[r]+i,n in ns.style)return{kebab:Kr[r]+t,camel:n}}function ge(t){var e=[];if(Fi(t))for(var i=0,n=t.length;n>i;i++){var r=t[i];if(r)if("string"==typeof r)e.push(r);else for(var s in r)r[s]&&e.push(s)}else if(m(t))for(var o in t)t[o]&&e.push(o);return e}function _e(t,e,i){if(e=e.trim(),-1===e.indexOf(" "))return void i(t,e);for(var n=e.split(/\s+/),r=0,s=n.length;s>r;r++)i(t,n[r])}function ye(t,e,i){function n(){++s>=r?i():t[s].call(e,n)}var r=t.length,s=0;t[0].call(e,n)}function be(t,e,i){for(var r,s,o,a,h,c,f,p=[],d=Object.keys(e),v=d.length;v--;)s=d[v],r=e[s]||ys,h=l(s),bs.test(h)&&(f={name:s,path:h,options:r,mode:_s.ONE_WAY,raw:null},o=u(s),null===(a=M(t,o))&&(null!==(a=M(t,o+".sync"))?f.mode=_s.TWO_WAY:null!==(a=M(t,o+".once"))&&(f.mode=_s.ONE_TIME)),null!==a?(f.raw=a,c=A(a),a=c.expression,f.filters=c.filters,n(a)&&!c.filters?f.optimizedLiteral=!0:f.dynamic=!0,f.parentPath=a):null!==(a=I(t,o))&&(f.raw=a),p.push(f));return we(p)}function we(t){return function(e,n){e._props={};for(var r,s,l,c,f,p=e.$options.propsData,d=t.length;d--;)if(r=t[d],f=r.raw,s=r.path,l=r.options,e._props[s]=r,p&&i(p,s)&&$e(e,r,p[s]),null===f)$e(e,r,void 0);else if(r.dynamic)r.mode===_s.ONE_TIME?(c=(n||e._context||e).$get(r.parentPath),$e(e,r,c)):e._context?e._bindDir({name:"prop",def:Cs,prop:r},null,null,n):$e(e,r,e.$get(r.parentPath));else if(r.optimizedLiteral){var v=h(f);c=v===f?a(o(f)):v,$e(e,r,c)}else c=l.type!==Boolean||""!==f&&f!==u(r.name)?f:!0,$e(e,r,c)}}function Ce(t,e,i,n){var r=e.dynamic&&It(e.parentPath),s=i;void 0===s&&(s=xe(t,e)),s=Oe(e,s);var o=s!==i;Ae(e,s,t)||(s=void 0),r&&!o?yt(function(){n(s)}):n(s)}function $e(t,e,i){Ce(t,e,i,function(i){kt(t,e.path,i)})}function ke(t,e,i){Ce(t,e,i,function(i){t[e.path]=i})}function xe(t,e){var n=e.options;if(!i(n,"default"))return n.type===Boolean?!1:void 0;var r=n["default"];return m(r),"function"==typeof r&&n.type!==Function?r.call(t):r}function Ae(t,e,i){if(!t.options.required&&(null===t.raw||null==e))return!0;var n=t.options,r=n.type,s=!r,o=[];if(r){Fi(r)||(r=[r]);for(var a=0;a<r.length&&!s;a++){var h=Te(e,r[a]);o.push(h.expectedType),s=h.valid}}if(!s)return!1;var l=n.validator;return!l||l(e)}function Oe(t,e){var i=t.options.coerce;return i?i(e):e}function Te(t,e){var i,n;return e===String?(n="string",i=typeof t===n):e===Number?(n="number",i=typeof t===n):e===Boolean?(n="boolean",i=typeof t===n):e===Function?(n="function",i=typeof t===n):e===Object?(n="object",i=g(t)):e===Array?(n="array",i=Fi(t)):i=t instanceof e,{valid:i,expectedType:n}}function Ne(t){$s.push(t),ks||(ks=!0,Qi(je))}function je(){for(var t=document.documentElement.offsetHeight,e=0;e<$s.length;e++)$s[e]();return $s=[],ks=!1,t}function Ee(t,e,i,n){this.id=e,this.el=t,this.enterClass=i&&i.enterClass||e+"-enter",this.leaveClass=i&&i.leaveClass||e+"-leave",this.hooks=i,this.vm=n,this.pendingCssEvent=this.pendingCssCb=this.cancel=this.pendingJsCb=this.op=this.cb=null,this.justEntered=!1,this.entered=this.left=!1,this.typeCache={},this.type=i&&i.type;var r=this;["enterNextTick","enterDone","leaveNextTick","leaveDone"].forEach(function(t){r[t]=p(r[t],r)})}function Se(t){if(/svg$/.test(t.namespaceURI)){var e=t.getBoundingClientRect();return!(e.width||e.height)}return!(t.offsetWidth||t.offsetHeight||t.getClientRects().length)}function Fe(t,e,i){var n=i||!e._asComponent?Me(t,e):null,r=n&&n.terminal||ni(t)||!t.hasChildNodes()?null:Je(t.childNodes,e);return function(t,e,i,s,o){var a=d(e.childNodes),h=De(function(){n&&n(t,e,i,s,o),r&&r(t,a,i,s,o)},t);return Re(t,h)}}function De(t,e){e._directives=[];var i=e._directives.length;t();var n=e._directives.slice(i);n.sort(Pe);for(var r=0,s=n.length;s>r;r++)n[r]._bind();return n}function Pe(t,e){return t=t.descriptor.def.priority||Is,e=e.descriptor.def.priority||Is,t>e?-1:t===e?0:1}function Re(t,e,i,n){function r(r){Le(t,e,r),i&&n&&Le(i,n)}return r.dirs=e,r}function Le(t,e,i){for(var n=e.length;n--;)e[n]._teardown()}function He(t,e,i,n){var r=be(e,i,t),s=De(function(){r(t,n)},t);return Re(t,s)}function Ie(t,e,i){var n,r,s=e._containerAttrs,o=e._replacerAttrs;return 11!==t.nodeType&&(e._asComponent?(s&&i&&(n=Ke(s,i)),o&&(r=Ke(o,e))):r=Ke(t.attributes,e)),e._containerAttrs=e._replacerAttrs=null,function(t,e,i){var s,o=t._context;o&&n&&(s=De(function(){n(o,e,null,i)},o));var a=De(function(){r&&r(t,e)},t);return Re(t,a,o,s)}}function Me(t,e){var i=t.nodeType;return 1!==i||ni(t)?3===i&&t.data.trim()?Ve(t,e):null:We(t,e)}function We(t,e){if("TEXTAREA"===t.tagName){var i=N(t.value);i&&(t.setAttribute(":value",j(i)),t.value="")}var n,r=t.hasAttributes(),s=r&&d(t.attributes);return r&&(n=Ze(t,s,e)),n||(n=Qe(t,e)),n||(n=Ge(t,e)),!n&&r&&(n=Ke(s,e)),n}function Ve(t,e){if(t._skip)return Be;var i=N(t.wholeText);if(!i)return null;for(var n=t.nextSibling;n&&3===n.nodeType;)n._skip=!0,n=n.nextSibling;for(var r,s,o=document.createDocumentFragment(),a=0,h=i.length;h>a;a++)s=i[a],r=s.tag?ze(s,e):document.createTextNode(s.value),o.appendChild(r);return Ue(i,o,e)}function Be(t,e){z(e)}function ze(t,e){function i(e){if(!t.descriptor){var i=A(t.value);t.descriptor={name:e,def:vs[e],expression:i.expression,filters:i.filters}}}var n;return t.oneTime?n=document.createTextNode(t.value):t.html?(n=document.createComment("v-html"),i("html")):(n=document.createTextNode(" "),i("text")),n}function Ue(t,e){return function(i,n,r,s){for(var o,a,h,l=e.cloneNode(!0),c=d(l.childNodes),u=0,f=t.length;f>u;u++)o=t[u],a=o.value,o.tag&&(h=c[u],o.oneTime?(a=(s||i).$eval(a),o.html?J(h,Zt(a,!0)):h.data=a):i._bindDir(o.descriptor,h,r,s));J(n,l)}}function Je(t,e){for(var i,n,r,s=[],o=0,a=t.length;a>o;o++)r=t[o],i=Me(r,e),n=i&&i.terminal||"SCRIPT"===r.tagName||!r.hasChildNodes()?null:Je(r.childNodes,e),s.push(i,n);return s.length?qe(s):null}function qe(t){return function(e,i,n,r,s){for(var o,a,h,l=0,c=0,u=t.length;u>l;c++){o=i[c],a=t[l++],h=t[l++];var f=d(o.childNodes);a&&a(e,o,n,r,s),h&&h(e,f,n,r,s)}}}function Qe(t,e){var i=t.tagName.toLowerCase();if(!An.test(i)){var n=gt(e,"elementDirectives",i);return n?Ye(t,i,"",e,n):void 0}}function Ge(t,e){var i=lt(t,e);if(i){var n=rt(t),r={name:"component",ref:n,expression:i.id,def:Fs.component,modifiers:{literal:!i.dynamic}},s=function(t,e,i,s,o){n&&kt((s||t).$refs,n,null),t._bindDir(r,e,i,s,o)};return s.terminal=!0,s}}function Ze(t,e,i){if(null!==I(t,"v-pre"))return Xe;if(t.hasAttribute("v-else")){var n=t.previousElementSibling;if(n&&n.hasAttribute("v-if"))return Xe}for(var r,s,o,a,h,l,c,u,f,p,d=0,v=e.length;v>d;d++)r=e[d],s=r.name.replace(Ls,""),(h=s.match(Rs))&&(f=gt(i,"directives",h[1]),f&&f.terminal&&(!p||(f.priority||Ms)>p.priority)&&(p=f,c=r.name,a=ti(r.name),o=r.value,l=h[1],u=h[2]));return p?Ye(t,l,o,i,p,c,u,a):void 0}function Xe(){}function Ye(t,e,i,n,r,s,o,a){var h=A(i),l={name:e,arg:o,expression:h.expression,filters:h.filters,raw:i,attr:s,modifiers:a,def:r};"for"!==e&&"router-view"!==e||(l.ref=rt(t));var c=function(t,e,i,n,r){l.ref&&kt((n||t).$refs,l.ref,null),t._bindDir(l,e,i,n,r)};return c.terminal=!0,c}function Ke(t,e){function i(t,e,i){var n=i&&ii(i),r=!n&&A(s);v.push({name:t,attr:o,raw:a,def:e,arg:l,modifiers:c,expression:r&&r.expression,filters:r&&r.filters,interp:i,hasOneTime:n})}for(var n,r,s,o,a,h,l,c,u,f,p,d=t.length,v=[];d--;)if(n=t[d],r=o=n.name,s=a=n.value,f=N(s),l=null,c=ti(r),r=r.replace(Ls,""),f)s=j(f),l=r,i("bind",vs.bind,f);else if(Hs.test(r))c.literal=!Ds.test(r),i("transition",Fs.transition);else if(Ps.test(r))l=r.replace(Ps,""),i("on",vs.on);else if(Ds.test(r))h=r.replace(Ds,""),"style"===h||"class"===h?i(h,Fs[h]):(l=h,i("bind",vs.bind));else if(p=r.match(Rs)){if(h=p[1],l=p[2],"else"===h)continue;u=gt(e,"directives",h,!0),u&&i(h,u)}return v.length?ei(v):void 0}function ti(t){var e=Object.create(null),i=t.match(Ls);if(i)for(var n=i.length;n--;)e[i[n].slice(1)]=!0;return e}function ei(t){return function(e,i,n,r,s){for(var o=t.length;o--;)e._bindDir(t[o],i,n,r,s)}}function ii(t){for(var e=t.length;e--;)if(t[e].oneTime)return!0}function ni(t){return"SCRIPT"===t.tagName&&(!t.hasAttribute("type")||"text/javascript"===t.getAttribute("type"))}function ri(t,e){return e&&(e._containerAttrs=oi(t)),it(t)&&(t=Zt(t)),e&&(e._asComponent&&!e.template&&(e.template="<slot></slot>"),e.template&&(e._content=K(t),t=si(t,e))),at(t)&&(U(nt("v-start",!0),t),t.appendChild(nt("v-end",!0))),t}function si(t,e){var i=e.template,n=Zt(i,!0);if(n){var r=n.firstChild,s=r.tagName&&r.tagName.toLowerCase();return e.replace?(t===document.body,n.childNodes.length>1||1!==r.nodeType||"component"===s||gt(e,"components",s)||W(r,"is")||gt(e,"elementDirectives",s)||r.hasAttribute("v-for")||r.hasAttribute("v-if")?n:(e._replacerAttrs=oi(r),ai(t,r),r)):(t.appendChild(n),t)}}function oi(t){return 1===t.nodeType&&t.hasAttributes()?d(t.attributes):void 0}function ai(t,e){for(var i,n,r=t.attributes,s=r.length;s--;)i=r[s].name,n=r[s].value,e.hasAttribute(i)||Ws.test(i)?"class"===i&&!N(n)&&(n=n.trim())&&n.split(/\s+/).forEach(function(t){X(e,t)}):e.setAttribute(i,n)}function hi(t,e){if(e){for(var i,n,r=t._slotContents=Object.create(null),s=0,o=e.children.length;o>s;s++)i=e.children[s],(n=i.getAttribute("slot"))&&(r[n]||(r[n]=[])).push(i);for(n in r)r[n]=li(r[n],e);if(e.hasChildNodes()){var a=e.childNodes;if(1===a.length&&3===a[0].nodeType&&!a[0].data.trim())return;r["default"]=li(e.childNodes,e)}}}function li(t,e){var i=document.createDocumentFragment();t=d(t);for(var n=0,r=t.length;r>n;n++){var s=t[n];!it(s)||s.hasAttribute("v-if")||s.hasAttribute("v-for")||(e.removeChild(s),s=Zt(s,!0)),i.appendChild(s)}return i}function ci(t){function e(){}function n(t,e){var i=new zt(e,t,null,{lazy:!0});return function(){return i.dirty&&i.evaluate(),_t.target&&i.depend(),i.value}}Object.defineProperty(t.prototype,"$data",{get:function(){return this._data},set:function(t){t!==this._data&&this._setData(t)}}),t.prototype._initState=function(){this._initProps(),this._initMeta(),this._initMethods(),this._initData(),this._initComputed()},t.prototype._initProps=function(){var t=this.$options,e=t.el,i=t.props;e=t.el=L(e),this._propsUnlinkFn=e&&1===e.nodeType&&i?He(this,e,i,this._scope):null},t.prototype._initData=function(){var t=this.$options.data,e=this._data=t?t():{};g(e)||(e={});var n,r,s=this._props,o=Object.keys(e);for(n=o.length;n--;)r=o[n],s&&i(s,r)||this._proxy(r);$t(e,this)},t.prototype._setData=function(t){t=t||{};var e=this._data;this._data=t;var n,r,s;for(n=Object.keys(e),s=n.length;s--;)r=n[s],r in t||this._unproxy(r);for(n=Object.keys(t),s=n.length;s--;)r=n[s],i(this,r)||this._proxy(r);e.__ob__.removeVm(this),$t(t,this),this._digest()},t.prototype._proxy=function(t){if(!r(t)){var e=this;Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get:function(){return e._data[t]},set:function(i){e._data[t]=i}})}},t.prototype._unproxy=function(t){r(t)||delete this[t]},t.prototype._digest=function(){for(var t=0,e=this._watchers.length;e>t;t++)this._watchers[t].update(!0)},t.prototype._initComputed=function(){var t=this.$options.computed;if(t)for(var i in t){var r=t[i],s={enumerable:!0,configurable:!0};"function"==typeof r?(s.get=n(r,this),s.set=e):(s.get=r.get?r.cache!==!1?n(r.get,this):p(r.get,this):e,s.set=r.set?p(r.set,this):e),Object.defineProperty(this,i,s)}},t.prototype._initMethods=function(){var t=this.$options.methods;if(t)for(var e in t)this[e]=p(t[e],this)},t.prototype._initMeta=function(){var t=this.$options._meta;if(t)for(var e in t)kt(this,e,t[e])}}function ui(t){function e(t,e){for(var i,n,r,s=e.attributes,o=0,a=s.length;a>o;o++)i=s[o].name,Bs.test(i)&&(i=i.replace(Bs,""),n=s[o].value,It(n)&&(n+=".apply(this, $arguments)"),r=(t._scope||t._context).$eval(n,!0),r._fromParent=!0,t.$on(i.replace(Bs),r))}function i(t,e,i){if(i){var r,s,o,a;for(s in i)if(r=i[s],Fi(r))for(o=0,a=r.length;a>o;o++)n(t,e,s,r[o]);else n(t,e,s,r)}}function n(t,e,i,r,s){var o=typeof r;if("function"===o)t[e](i,r,s);else if("string"===o){var a=t.$options.methods,h=a&&a[r];h&&t[e](i,h,s)}else r&&"object"===o&&n(t,e,i,r.handler,r)}function r(){this._isAttached||(this._isAttached=!0,this.$children.forEach(s))}function s(t){!t._isAttached&&H(t.$el)&&t._callHook("attached")}function o(){this._isAttached&&(this._isAttached=!1,this.$children.forEach(a))}function a(t){t._isAttached&&!H(t.$el)&&t._callHook("detached")}t.prototype._initEvents=function(){var t=this.$options;t._asComponent&&e(this,t.el),i(this,"$on",t.events),i(this,"$watch",t.watch)},t.prototype._initDOMHooks=function(){this.$on("hook:attached",r),this.$on("hook:detached",o)},t.prototype._callHook=function(t){this.$emit("pre-hook:"+t);var e=this.$options[t];if(e)for(var i=0,n=e.length;n>i;i++)e[i].call(this);this.$emit("hook:"+t)}}function fi(){}function pi(t,e,i,n,r,s){this.vm=e,this.el=i,this.descriptor=t,this.name=t.name,this.expression=t.expression,this.arg=t.arg,this.modifiers=t.modifiers,this.filters=t.filters,this.literal=this.modifiers&&this.modifiers.literal,this._locked=!1,this._bound=!1,this._listeners=null,this._host=n,this._scope=r,this._frag=s}function di(t){t.prototype._updateRef=function(t){var e=this.$options._ref;if(e){var i=(this._scope||this._context).$refs;t?i[e]===this&&(i[e]=null):i[e]=this}},t.prototype._compile=function(t){var e=this.$options,i=t;if(t=ri(t,e),this._initElement(t),1!==t.nodeType||null===I(t,"v-pre")){var n=this._context&&this._context.$options,r=Ie(t,e,n);hi(this,e._content);var s,o=this.constructor;e._linkerCachable&&(s=o.linker,s||(s=o.linker=Fe(t,e)));var a=r(this,t,this._scope),h=s?s(this,t):Fe(t,e)(this,t);this._unlinkFn=function(){a(),h(!0)},e.replace&&J(i,t),this._isCompiled=!0,this._callHook("compiled")}},t.prototype._initElement=function(t){at(t)?(this._isFragment=!0,this.$el=this._fragmentStart=t.firstChild,this._fragmentEnd=t.lastChild,3===this._fragmentStart.nodeType&&(this._fragmentStart.data=this._fragmentEnd.data=""),this._fragment=t):this.$el=t,this.$el.__vue__=this,this._callHook("beforeCompile")},t.prototype._bindDir=function(t,e,i,n,r){this._directives.push(new pi(t,this,e,i,n,r))},t.prototype._destroy=function(t,e){if(this._isBeingDestroyed)return void(e||this._cleanup());var i,n,r=this,s=function(){!i||n||e||r._cleanup()};t&&this.$el&&(n=!0,this.$remove(function(){n=!1,s()})),this._callHook("beforeDestroy"),this._isBeingDestroyed=!0;var o,a=this.$parent;for(a&&!a._isBeingDestroyed&&(a.$children.$remove(this), this._updateRef(!0)),o=this.$children.length;o--;)this.$children[o].$destroy();for(this._propsUnlinkFn&&this._propsUnlinkFn(),this._unlinkFn&&this._unlinkFn(),o=this._watchers.length;o--;)this._watchers[o].teardown();this.$el&&(this.$el.__vue__=null),i=!0,s()},t.prototype._cleanup=function(){this._isDestroyed||(this._frag&&this._frag.children.$remove(this),this._data&&this._data.__ob__&&this._data.__ob__.removeVm(this),this.$el=this.$parent=this.$root=this.$children=this._watchers=this._context=this._scope=this._directives=null,this._isDestroyed=!0,this._callHook("destroyed"),this.$off())}}function vi(t){t.prototype._applyFilters=function(t,e,i,n){var r,s,o,a,h,l,c,u,f;for(l=0,c=i.length;c>l;l++)if(r=i[n?c-l-1:l],s=gt(this.$options,"filters",r.name,!0),s&&(s=n?s.write:s.read||s,"function"==typeof s)){if(o=n?[t,e]:[t],h=n?2:1,r.args)for(u=0,f=r.args.length;f>u;u++)a=r.args[u],o[u+h]=a.dynamic?this.$get(a.value):a.value;t=s.apply(this,o)}return t},t.prototype._resolveComponent=function(e,i){var n;if(n="function"==typeof e?e:gt(this.$options,"components",e,!0))if(n.options)i(n);else if(n.resolved)i(n.resolved);else if(n.requested)n.pendingCallbacks.push(i);else{n.requested=!0;var r=n.pendingCallbacks=[i];n.call(this,function(e){g(e)&&(e=t.extend(e)),n.resolved=e;for(var i=0,s=r.length;s>i;i++)r[i](e)},function(t){})}}}function mi(t){function i(t){return JSON.parse(JSON.stringify(t))}t.prototype.$get=function(t,e){var i=Ht(t);if(i){if(e){var n=this;return function(){n.$arguments=d(arguments);var t=i.get.call(n,n);return n.$arguments=null,t}}try{return i.get.call(this,this)}catch(r){}}},t.prototype.$set=function(t,e){var i=Ht(t,!0);i&&i.set&&i.set.call(this,this,e)},t.prototype.$delete=function(t){e(this._data,t)},t.prototype.$watch=function(t,e,i){var n,r=this;"string"==typeof t&&(n=A(t),t=n.expression);var s=new zt(r,t,e,{deep:i&&i.deep,sync:i&&i.sync,filters:n&&n.filters,user:!i||i.user!==!1});return i&&i.immediate&&e.call(r,s.value),function(){s.teardown()}},t.prototype.$eval=function(t,e){if(zs.test(t)){var i=A(t),n=this.$get(i.expression,e);return i.filters?this._applyFilters(n,null,i.filters):n}return this.$get(t,e)},t.prototype.$interpolate=function(t){var e=N(t),i=this;return e?1===e.length?i.$eval(e[0].value)+"":e.map(function(t){return t.tag?i.$eval(t.value):t.value}).join(""):t},t.prototype.$log=function(t){var e=t?jt(this._data,t):this._data;if(e&&(e=i(e)),!t){var n;for(n in this.$options.computed)e[n]=i(this[n]);if(this._props)for(n in this._props)e[n]=i(this[n])}console.log(e)}}function gi(t){function e(t,e,n,r,s,o){e=i(e);var a=!H(e),h=r===!1||a?s:o,l=!a&&!t._isAttached&&!H(t.$el);return t._isFragment?(st(t._fragmentStart,t._fragmentEnd,function(i){h(i,e,t)}),n&&n()):h(t.$el,e,t,n),l&&t._callHook("attached"),t}function i(t){return"string"==typeof t?document.querySelector(t):t}function n(t,e,i,n){e.appendChild(t),n&&n()}function r(t,e,i,n){V(t,e),n&&n()}function s(t,e,i){z(t),i&&i()}t.prototype.$nextTick=function(t){Qi(t,this)},t.prototype.$appendTo=function(t,i,r){return e(this,t,i,r,n,F)},t.prototype.$prependTo=function(t,e,n){return t=i(t),t.hasChildNodes()?this.$before(t.firstChild,e,n):this.$appendTo(t,e,n),this},t.prototype.$before=function(t,i,n){return e(this,t,i,n,r,D)},t.prototype.$after=function(t,e,n){return t=i(t),t.nextSibling?this.$before(t.nextSibling,e,n):this.$appendTo(t.parentNode,e,n),this},t.prototype.$remove=function(t,e){if(!this.$el.parentNode)return t&&t();var i=this._isAttached&&H(this.$el);i||(e=!1);var n=this,r=function(){i&&n._callHook("detached"),t&&t()};if(this._isFragment)ot(this._fragmentStart,this._fragmentEnd,this,this._fragment,r);else{var o=e===!1?s:P;o(this.$el,this,r)}return this}}function _i(t){function e(t,e,n){var r=t.$parent;if(r&&n&&!i.test(e))for(;r;)r._eventsCount[e]=(r._eventsCount[e]||0)+n,r=r.$parent}t.prototype.$on=function(t,i){return(this._events[t]||(this._events[t]=[])).push(i),e(this,t,1),this},t.prototype.$once=function(t,e){function i(){n.$off(t,i),e.apply(this,arguments)}var n=this;return i.fn=e,this.$on(t,i),this},t.prototype.$off=function(t,i){var n;if(!arguments.length){if(this.$parent)for(t in this._events)n=this._events[t],n&&e(this,t,-n.length);return this._events={},this}if(n=this._events[t],!n)return this;if(1===arguments.length)return e(this,t,-n.length),this._events[t]=null,this;for(var r,s=n.length;s--;)if(r=n[s],r===i||r.fn===i){e(this,t,-1),n.splice(s,1);break}return this},t.prototype.$emit=function(t){var e="string"==typeof t;t=e?t:t.name;var i=this._events[t],n=e||!i;if(i){i=i.length>1?d(i):i;var r=e&&i.some(function(t){return t._fromParent});r&&(n=!1);for(var s=d(arguments,1),o=0,a=i.length;a>o;o++){var h=i[o],l=h.apply(this,s);l!==!0||r&&!h._fromParent||(n=!0)}}return n},t.prototype.$broadcast=function(t){var e="string"==typeof t;if(t=e?t:t.name,this._eventsCount[t]){var i=this.$children,n=d(arguments);e&&(n[0]={name:t,source:this});for(var r=0,s=i.length;s>r;r++){var o=i[r],a=o.$emit.apply(o,n);a&&o.$broadcast.apply(o,n)}return this}},t.prototype.$dispatch=function(t){var e=this.$emit.apply(this,arguments);if(e){var i=this.$parent,n=d(arguments);for(n[0]={name:t,source:this};i;)e=i.$emit.apply(i,n),i=e?i.$parent:null;return this}};var i=/^hook:/}function yi(t){function e(){this._isAttached=!0,this._isReady=!0,this._callHook("ready")}t.prototype.$mount=function(t){return this._isCompiled?void 0:(t=L(t),t||(t=document.createElement("div")),this._compile(t),this._initDOMHooks(),H(this.$el)?(this._callHook("attached"),e.call(this)):this.$once("hook:attached",e),this)},t.prototype.$destroy=function(t,e){this._destroy(t,e)},t.prototype.$compile=function(t,e,i,n){return Fe(t,this.$options,!0)(this,t,e,i,n)}}function bi(t){this._init(t)}function wi(t,e,i){return i=i?parseInt(i,10):0,e=o(e),"number"==typeof e?t.slice(i,i+e):t}function Ci(t,e,i){if(t=Qs(t),null==e)return t;if("function"==typeof e)return t.filter(e);e=(""+e).toLowerCase();for(var n,r,s,o,a="in"===i?3:2,h=Array.prototype.concat.apply([],d(arguments,a)),l=[],c=0,u=t.length;u>c;c++)if(n=t[c],s=n&&n.$value||n,o=h.length){for(;o--;)if(r=h[o],"$key"===r&&ki(n.$key,e)||ki(jt(s,r),e)){l.push(n);break}}else ki(n,e)&&l.push(n);return l}function $i(t){function e(t,e,i){var r=n[i];return r&&("$key"!==r&&(m(t)&&"$value"in t&&(t=t.$value),m(e)&&"$value"in e&&(e=e.$value)),t=m(t)?jt(t,r):t,e=m(e)?jt(e,r):e),t===e?0:t>e?s:-s}var i=null,n=void 0;t=Qs(t);var r=d(arguments,1),s=r[r.length-1];"number"==typeof s?(s=0>s?-1:1,r=r.length>1?r.slice(0,-1):r):s=1;var o=r[0];return o?("function"==typeof o?i=function(t,e){return o(t,e)*s}:(n=Array.prototype.concat.apply([],r),i=function(t,r,s){return s=s||0,s>=n.length-1?e(t,r,s):e(t,r,s)||i(t,r,s+1)}),t.slice().sort(i)):t}function ki(t,e){var i;if(g(t)){var n=Object.keys(t);for(i=n.length;i--;)if(ki(t[n[i]],e))return!0}else if(Fi(t)){for(i=t.length;i--;)if(ki(t[i],e))return!0}else if(null!=t)return t.toString().toLowerCase().indexOf(e)>-1}function xi(i){function n(t){return new Function("return function "+f(t)+" (options) { this._init(options) }")()}i.options={directives:vs,elementDirectives:qs,filters:Zs,transitions:{},components:{},partials:{},replace:!0},i.util=Pn,i.config=Cn,i.set=t,i["delete"]=e,i.nextTick=Qi,i.compiler=Vs,i.FragmentFactory=re,i.internalDirectives=Fs,i.parsers={path:Yn,text:yn,template:Tr,directive:pn,expression:fr},i.cid=0;var r=1;i.extend=function(t){t=t||{};var e=this,i=0===e.cid;if(i&&t._Ctor)return t._Ctor;var s=t.name||e.options.name,o=n(s||"VueComponent");return o.prototype=Object.create(e.prototype),o.prototype.constructor=o,o.cid=r++,o.options=mt(e.options,t),o["super"]=e,o.extend=e.extend,Cn._assetTypes.forEach(function(t){o[t]=e[t]}),s&&(o.options.components[s]=o),i&&(t._Ctor=o),o},i.use=function(t){if(!t.installed){var e=d(arguments,1);return e.unshift(this),"function"==typeof t.install?t.install.apply(t,e):t.apply(null,e),t.installed=!0,this}},i.mixin=function(t){i.options=mt(i.options,t)},Cn._assetTypes.forEach(function(t){i[t]=function(e,n){return n?("component"===t&&g(n)&&(n.name=e,n=i.extend(n)),this.options[t+"s"][e]=n,n):this.options[t+"s"][e]}}),v(i.transition,kn)}var Ai=Object.prototype.hasOwnProperty,Oi=/^\s?(true|false|-?[\d\.]+|'[^']*'|"[^"]*")\s?$/,Ti=/-(\w)/g,Ni=/([a-z\d])([A-Z])/g,ji=/(?:^|[-_\/])(\w)/g,Ei=Object.prototype.toString,Si="[object Object]",Fi=Array.isArray,Di="__proto__"in{},Pi="undefined"!=typeof window&&"[object Object]"!==Object.prototype.toString.call(window),Ri=Pi&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__,Li=Pi&&window.navigator.userAgent.toLowerCase(),Hi=Li&&Li.indexOf("msie 9.0")>0,Ii=Li&&Li.indexOf("android")>0,Mi=Li&&/(iphone|ipad|ipod|ios)/i.test(Li),Wi=Li&&Li.indexOf("micromessenger")>0,Vi=void 0,Bi=void 0,zi=void 0,Ui=void 0;if(Pi&&!Hi){var Ji=void 0===window.ontransitionend&&void 0!==window.onwebkittransitionend,qi=void 0===window.onanimationend&&void 0!==window.onwebkitanimationend;Vi=Ji?"WebkitTransition":"transition",Bi=Ji?"webkitTransitionEnd":"transitionend",zi=qi?"WebkitAnimation":"animation",Ui=qi?"webkitAnimationEnd":"animationend"}var Qi=function(){function t(){n=!1;var t=i.slice(0);i=[];for(var e=0;e<t.length;e++)t[e]()}var e,i=[],n=!1;if("undefined"==typeof MutationObserver||Wi&&Mi){var r=Pi?window:"undefined"!=typeof global?global:{};e=r.setImmediate||setTimeout}else{var s=1,o=new MutationObserver(t),a=document.createTextNode(s);o.observe(a,{characterData:!0}),e=function(){s=(s+1)%2,a.data=s}}return function(r,s){var o=s?function(){r.call(s)}:r;i.push(o),n||(n=!0,e(t,0))}}(),Gi=void 0;"undefined"!=typeof Set&&Set.toString().match(/native code/)?Gi=Set:(Gi=function(){this.set=Object.create(null)},Gi.prototype.has=function(t){return void 0!==this.set[t]},Gi.prototype.add=function(t){this.set[t]=1},Gi.prototype.clear=function(){this.set=Object.create(null)});var Zi=$.prototype;Zi.put=function(t,e){var i;this.size===this.limit&&(i=this.shift());var n=this.get(t,!0);return n||(n={key:t},this._keymap[t]=n,this.tail?(this.tail.newer=n,n.older=this.tail):this.head=n,this.tail=n,this.size++),n.value=e,i},Zi.shift=function(){var t=this.head;return t&&(this.head=this.head.newer,this.head.older=void 0,t.newer=t.older=void 0,this._keymap[t.key]=void 0,this.size--),t},Zi.get=function(t,e){var i=this._keymap[t];if(void 0!==i)return i===this.tail?e?i:i.value:(i.newer&&(i===this.head&&(this.head=i.newer),i.newer.older=i.older),i.older&&(i.older.newer=i.newer),i.newer=void 0,i.older=this.tail,this.tail&&(this.tail.newer=i),this.tail=i,e?i:i.value)};var Xi,Yi,Ki,tn,en,nn,rn,sn,on,an,hn,ln,cn=new $(1e3),un=/[^\s'"]+|'[^']*'|"[^"]*"/g,fn=/^in$|^-?\d+/,pn=Object.freeze({parseDirective:A}),dn=/[-.*+?^${}()|[\]\/\\]/g,vn=void 0,mn=void 0,gn=void 0,_n=/[^|]\|[^|]/,yn=Object.freeze({compileRegex:T,parseText:N,tokensToExp:j}),bn=["{{","}}"],wn=["{{{","}}}"],Cn=Object.defineProperties({debug:!1,silent:!1,async:!0,warnExpressionErrors:!0,devtools:!1,_delimitersChanged:!0,_assetTypes:["component","directive","elementDirective","filter","transition","partial"],_propBindingModes:{ONE_WAY:0,TWO_WAY:1,ONE_TIME:2},_maxUpdateCount:100},{delimiters:{get:function(){return bn},set:function(t){bn=t,T()},configurable:!0,enumerable:!0},unsafeDelimiters:{get:function(){return wn},set:function(t){wn=t,T()},configurable:!0,enumerable:!0}}),$n=void 0,kn=Object.freeze({appendWithTransition:F,beforeWithTransition:D,removeWithTransition:P,applyTransition:R}),xn=/^v-ref:/,An=/^(div|p|span|img|a|b|i|br|ul|ol|li|h1|h2|h3|h4|h5|h6|code|pre|table|th|td|tr|form|label|input|select|option|nav|article|section|header|footer)$/i,On=/^(slot|partial|component)$/i,Tn=Cn.optionMergeStrategies=Object.create(null);Tn.data=function(t,e,i){return i?t||e?function(){var n="function"==typeof e?e.call(i):e,r="function"==typeof t?t.call(i):void 0;return n?ut(n,r):r}:void 0:e?"function"!=typeof e?t:t?function(){return ut(e.call(this),t.call(this))}:e:t},Tn.el=function(t,e,i){if(i||!e||"function"==typeof e){var n=e||t;return i&&"function"==typeof n?n.call(i):n}},Tn.init=Tn.created=Tn.ready=Tn.attached=Tn.detached=Tn.beforeCompile=Tn.compiled=Tn.beforeDestroy=Tn.destroyed=Tn.activate=function(t,e){return e?t?t.concat(e):Fi(e)?e:[e]:t},Cn._assetTypes.forEach(function(t){Tn[t+"s"]=ft}),Tn.watch=Tn.events=function(t,e){if(!e)return t;if(!t)return e;var i={};v(i,t);for(var n in e){var r=i[n],s=e[n];r&&!Fi(r)&&(r=[r]),i[n]=r?r.concat(s):[s]}return i},Tn.props=Tn.methods=Tn.computed=function(t,e){if(!e)return t;if(!t)return e;var i=Object.create(null);return v(i,t),v(i,e),i};var Nn=function(t,e){return void 0===e?t:e},jn=0;_t.target=null,_t.prototype.addSub=function(t){this.subs.push(t)},_t.prototype.removeSub=function(t){this.subs.$remove(t)},_t.prototype.depend=function(){_t.target.addDep(this)},_t.prototype.notify=function(){for(var t=d(this.subs),e=0,i=t.length;i>e;e++)t[e].update()};var En=Array.prototype,Sn=Object.create(En);["push","pop","shift","unshift","splice","sort","reverse"].forEach(function(t){var e=En[t];_(Sn,t,function(){for(var i=arguments.length,n=new Array(i);i--;)n[i]=arguments[i];var r,s=e.apply(this,n),o=this.__ob__;switch(t){case"push":r=n;break;case"unshift":r=n;break;case"splice":r=n.slice(2)}return r&&o.observeArray(r),o.dep.notify(),s})}),_(En,"$set",function(t,e){return t>=this.length&&(this.length=Number(t)+1),this.splice(t,1,e)[0]}),_(En,"$remove",function(t){if(this.length){var e=b(this,t);return e>-1?this.splice(e,1):void 0}});var Fn=Object.getOwnPropertyNames(Sn),Dn=!0;bt.prototype.walk=function(t){for(var e=Object.keys(t),i=0,n=e.length;n>i;i++)this.convert(e[i],t[e[i]])},bt.prototype.observeArray=function(t){for(var e=0,i=t.length;i>e;e++)$t(t[e])},bt.prototype.convert=function(t,e){kt(this.value,t,e)},bt.prototype.addVm=function(t){(this.vms||(this.vms=[])).push(t)},bt.prototype.removeVm=function(t){this.vms.$remove(t)};var Pn=Object.freeze({defineReactive:kt,set:t,del:e,hasOwn:i,isLiteral:n,isReserved:r,_toString:s,toNumber:o,toBoolean:a,stripQuotes:h,camelize:l,hyphenate:u,classify:f,bind:p,toArray:d,extend:v,isObject:m,isPlainObject:g,def:_,debounce:y,indexOf:b,cancellable:w,looseEqual:C,isArray:Fi,hasProto:Di,inBrowser:Pi,devtools:Ri,isIE9:Hi,isAndroid:Ii,isIos:Mi,isWechat:Wi,get transitionProp(){return Vi},get transitionEndEvent(){return Bi},get animationProp(){return zi},get animationEndEvent(){return Ui},nextTick:Qi,get _Set(){return Gi},query:L,inDoc:H,getAttr:I,getBindAttr:M,hasBindAttr:W,before:V,after:B,remove:z,prepend:U,replace:J,on:q,off:Q,setClass:Z,addClass:X,removeClass:Y,extractContent:K,trimNode:tt,isTemplate:it,createAnchor:nt,findRef:rt,mapNodeRange:st,removeNodeRange:ot,isFragment:at,getOuterHTML:ht,mergeOptions:mt,resolveAsset:gt,checkComponentAttr:lt,commonTagRE:An,reservedTagRE:On,warn:$n}),Rn=0,Ln=new $(1e3),Hn=0,In=1,Mn=2,Wn=3,Vn=0,Bn=1,zn=2,Un=3,Jn=4,qn=5,Qn=6,Gn=7,Zn=8,Xn=[];Xn[Vn]={ws:[Vn],ident:[Un,Hn],"[":[Jn],eof:[Gn]},Xn[Bn]={ws:[Bn],".":[zn],"[":[Jn],eof:[Gn]},Xn[zn]={ws:[zn],ident:[Un,Hn]},Xn[Un]={ident:[Un,Hn],0:[Un,Hn],number:[Un,Hn],ws:[Bn,In],".":[zn,In],"[":[Jn,In],eof:[Gn,In]},Xn[Jn]={"'":[qn,Hn],'"':[Qn,Hn],"[":[Jn,Mn],"]":[Bn,Wn],eof:Zn,"else":[Jn,Hn]},Xn[qn]={"'":[Jn,Hn],eof:Zn,"else":[qn,Hn]},Xn[Qn]={'"':[Jn,Hn],eof:Zn,"else":[Qn,Hn]};var Yn=Object.freeze({parsePath:Nt,getPath:jt,setPath:Et}),Kn=new $(1e3),tr="Math,Date,this,true,false,null,undefined,Infinity,NaN,isNaN,isFinite,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,parseInt,parseFloat",er=new RegExp("^("+tr.replace(/,/g,"\\b|")+"\\b)"),ir="break,case,class,catch,const,continue,debugger,default,delete,do,else,export,extends,finally,for,function,if,import,in,instanceof,let,return,super,switch,throw,try,var,while,with,yield,enum,await,implements,package,protected,static,interface,private,public",nr=new RegExp("^("+ir.replace(/,/g,"\\b|")+"\\b)"),rr=/\s/g,sr=/\n/g,or=/[\{,]\s*[\w\$_]+\s*:|('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`)|new |typeof |void /g,ar=/"(\d+)"/g,hr=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?'\]|\[".*?"\]|\[\d+\]|\[[A-Za-z_$][\w$]*\])*$/,lr=/[^\w$\.](?:[A-Za-z_$][\w$]*)/g,cr=/^(?:true|false)$/,ur=[],fr=Object.freeze({parseExpression:Ht,isSimplePath:It}),pr=[],dr=[],vr={},mr={},gr=!1,_r=0;zt.prototype.get=function(){this.beforeGet();var t,e=this.scope||this.vm;try{t=this.getter.call(e,e)}catch(i){}return this.deep&&Ut(t),this.preProcess&&(t=this.preProcess(t)),this.filters&&(t=e._applyFilters(t,null,this.filters,!1)),this.postProcess&&(t=this.postProcess(t)),this.afterGet(),t},zt.prototype.set=function(t){var e=this.scope||this.vm;this.filters&&(t=e._applyFilters(t,this.value,this.filters,!0));try{this.setter.call(e,e,t)}catch(i){}var n=e.$forContext;if(n&&n.alias===this.expression){if(n.filters)return;n._withLock(function(){e.$key?n.rawValue[e.$key]=t:n.rawValue.$set(e.$index,t)})}},zt.prototype.beforeGet=function(){_t.target=this},zt.prototype.addDep=function(t){var e=t.id;this.newDepIds.has(e)||(this.newDepIds.add(e),this.newDeps.push(t),this.depIds.has(e)||t.addSub(this))},zt.prototype.afterGet=function(){_t.target=null;for(var t=this.deps.length;t--;){var e=this.deps[t];this.newDepIds.has(e.id)||e.removeSub(this)}var i=this.depIds;this.depIds=this.newDepIds,this.newDepIds=i,this.newDepIds.clear(),i=this.deps,this.deps=this.newDeps,this.newDeps=i,this.newDeps.length=0},zt.prototype.update=function(t){this.lazy?this.dirty=!0:this.sync||!Cn.async?this.run():(this.shallow=this.queued?t?this.shallow:!1:!!t,this.queued=!0,Bt(this))},zt.prototype.run=function(){if(this.active){var t=this.get();if(t!==this.value||(m(t)||this.deep)&&!this.shallow){var e=this.value;this.value=t;this.prevError;this.cb.call(this.vm,t,e)}this.queued=this.shallow=!1}},zt.prototype.evaluate=function(){var t=_t.target;this.value=this.get(),this.dirty=!1,_t.target=t},zt.prototype.depend=function(){for(var t=this.deps.length;t--;)this.deps[t].depend()},zt.prototype.teardown=function(){if(this.active){this.vm._isBeingDestroyed||this.vm._vForRemoving||this.vm._watchers.$remove(this);for(var t=this.deps.length;t--;)this.deps[t].removeSub(this);this.active=!1,this.vm=this.cb=this.value=null}};var yr=new Gi,br={bind:function(){this.attr=3===this.el.nodeType?"data":"textContent"},update:function(t){this.el[this.attr]=s(t)}},wr=new $(1e3),Cr=new $(1e3),$r={efault:[0,"",""],legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]};$r.td=$r.th=[3,"<table><tbody><tr>","</tr></tbody></table>"],$r.option=$r.optgroup=[1,'<select multiple="multiple">',"</select>"],$r.thead=$r.tbody=$r.colgroup=$r.caption=$r.tfoot=[1,"<table>","</table>"],$r.g=$r.defs=$r.symbol=$r.use=$r.image=$r.text=$r.circle=$r.ellipse=$r.line=$r.path=$r.polygon=$r.polyline=$r.rect=[1,'<svg xmlns="path_to_url" xmlns:xlink="path_to_url" xmlns:ev="path_to_url"version="1.1">',"</svg>"];var kr=/<([\w:-]+)/,xr=/&#?\w+?;/,Ar=function(){if(Pi){var t=document.createElement("div");return t.innerHTML="<template>1</template>",!t.cloneNode(!0).firstChild.innerHTML}return!1}(),Or=function(){if(Pi){var t=document.createElement("textarea");return t.placeholder="t","t"===t.cloneNode(!0).value}return!1}(),Tr=Object.freeze({cloneNode:Gt,parseTemplate:Zt}),Nr={bind:function(){8===this.el.nodeType&&(this.nodes=[],this.anchor=nt("v-html"),J(this.el,this.anchor))},update:function(t){t=s(t),this.nodes?this.swap(t):this.el.innerHTML=t},swap:function(t){for(var e=this.nodes.length;e--;)z(this.nodes[e]);var i=Zt(t,!0,!0);this.nodes=d(i.childNodes),V(i,this.anchor)}};Xt.prototype.callHook=function(t){var e,i;for(e=0,i=this.childFrags.length;i>e;e++)this.childFrags[e].callHook(t);for(e=0,i=this.children.length;i>e;e++)t(this.children[e])},Xt.prototype.beforeRemove=function(){var t,e;for(t=0,e=this.childFrags.length;e>t;t++)this.childFrags[t].beforeRemove(!1);for(t=0,e=this.children.length;e>t;t++)this.children[t].$destroy(!1,!0);var i=this.unlink.dirs;for(t=0,e=i.length;e>t;t++)i[t]._watcher&&i[t]._watcher.teardown()},Xt.prototype.destroy=function(){this.parentFrag&&this.parentFrag.childFrags.$remove(this),this.node.__v_frag=null,this.unlink()};var jr=new $(5e3);re.prototype.create=function(t,e,i){var n=Gt(this.template);return new Xt(this.linker,this.vm,n,t,e,i)};var Er=700,Sr=800,Fr=850,Dr=1100,Pr=1500,Rr=1500,Lr=1750,Hr=2100,Ir=2200,Mr=2300,Wr=0,Vr={priority:Ir,terminal:!0,params:["track-by","stagger","enter-stagger","leave-stagger"],bind:function(){var t=this.expression.match(/(.*) (?:in|of) (.*)/);if(t){var e=t[1].match(/\((.*),(.*)\)/);e?(this.iterator=e[1].trim(),this.alias=e[2].trim()):this.alias=t[1].trim(),this.expression=t[2]}if(this.alias){this.id="__v-for__"+ ++Wr;var i=this.el.tagName;this.isOption=("OPTION"===i||"OPTGROUP"===i)&&"SELECT"===this.el.parentNode.tagName,this.start=nt("v-for-start"),this.end=nt("v-for-end"),J(this.el,this.end),V(this.start,this.end),this.cache=Object.create(null),this.factory=new re(this.vm,this.el)}},update:function(t){this.diff(t),this.updateRef(),this.updateModel()},diff:function(t){var e,n,r,s,o,a,h=t[0],l=this.fromObject=m(h)&&i(h,"$key")&&i(h,"$value"),c=this.params.trackBy,u=this.frags,f=this.frags=new Array(t.length),p=this.alias,d=this.iterator,v=this.start,g=this.end,_=H(v),y=!u;for(e=0,n=t.length;n>e;e++)h=t[e],s=l?h.$key:null,o=l?h.$value:h,a=!m(o),r=!y&&this.getCachedFrag(o,e,s),r?(r.reused=!0,r.scope.$index=e,s&&(r.scope.$key=s),d&&(r.scope[d]=null!==s?s:e),(c||l||a)&&yt(function(){r.scope[p]=o})):(r=this.create(o,p,e,s),r.fresh=!y),f[e]=r,y&&r.before(g);if(!y){var b=0,w=u.length-f.length;for(this.vm._vForRemoving=!0,e=0,n=u.length;n>e;e++)r=u[e],r.reused||(this.deleteCachedFrag(r),this.remove(r,b++,w,_));this.vm._vForRemoving=!1,b&&(this.vm._watchers=this.vm._watchers.filter(function(t){return t.active}));var C,$,k,x=0;for(e=0,n=f.length;n>e;e++)r=f[e],C=f[e-1],$=C?C.staggerCb?C.staggerAnchor:C.end||C.node:v,r.reused&&!r.staggerCb?(k=se(r,v,this.id),k===C||k&&se(k,v,this.id)===C||this.move(r,$)):this.insert(r,x++,$,_),r.reused=r.fresh=!1}},create:function(t,e,i,n){var r=this._host,s=this._scope||this.vm,o=Object.create(s);o.$refs=Object.create(s.$refs),o.$els=Object.create(s.$els),o.$parent=s,o.$forContext=this,yt(function(){kt(o,e,t)}),kt(o,"$index",i),n?kt(o,"$key",n):o.$key&&_(o,"$key",null),this.iterator&&kt(o,this.iterator,null!==n?n:i);var a=this.factory.create(r,o,this._frag);return a.forId=this.id,this.cacheFrag(t,a,i,n),a},updateRef:function(){var t=this.descriptor.ref;if(t){var e,i=(this._scope||this.vm).$refs;this.fromObject?(e={},this.frags.forEach(function(t){e[t.scope.$key]=oe(t)})):e=this.frags.map(oe),i[t]=e}},updateModel:function(){if(this.isOption){var t=this.start.parentNode,e=t&&t.__v_model;e&&e.forceUpdate()}},insert:function(t,e,i,n){t.staggerCb&&(t.staggerCb.cancel(),t.staggerCb=null);var r=this.getStagger(t,e,null,"enter");if(n&&r){var s=t.staggerAnchor;s||(s=t.staggerAnchor=nt("stagger-anchor"),s.__v_frag=t),B(s,i);var o=t.staggerCb=w(function(){t.staggerCb=null,t.before(s),z(s)});setTimeout(o,r)}else{var a=i.nextSibling;a||(B(this.end,i),a=this.end),t.before(a)}},remove:function(t,e,i,n){if(t.staggerCb)return t.staggerCb.cancel(),void(t.staggerCb=null);var r=this.getStagger(t,e,i,"leave");if(n&&r){var s=t.staggerCb=w(function(){t.staggerCb=null,t.remove()});setTimeout(s,r)}else t.remove()},move:function(t,e){e.nextSibling||this.end.parentNode.appendChild(this.end),t.before(e.nextSibling,!1)},cacheFrag:function(t,e,n,r){var s,o=this.params.trackBy,a=this.cache,h=!m(t);r||o||h?(s=he(n,r,t,o),a[s]||(a[s]=e)):(s=this.id,i(t,s)?null===t[s]&&(t[s]=e):Object.isExtensible(t)&&_(t,s,e)),e.raw=t},getCachedFrag:function(t,e,i){var n,r=this.params.trackBy,s=!m(t);if(i||r||s){var o=he(e,i,t,r);n=this.cache[o]}else n=t[this.id];return n&&(n.reused||n.fresh),n},deleteCachedFrag:function(t){var e=t.raw,n=this.params.trackBy,r=t.scope,s=r.$index,o=i(r,"$key")&&r.$key,a=!m(e);if(n||o||a){var h=he(s,o,e,n);this.cache[h]=null}else e[this.id]=null,t.raw=null},getStagger:function(t,e,i,n){n+="Stagger";var r=t.node.__v_trans,s=r&&r.hooks,o=s&&(s[n]||s.stagger);return o?o.call(t,e,i):e*parseInt(this.params[n]||this.params.stagger,10)},_preProcess:function(t){return this.rawValue=t,t},_postProcess:function(t){if(Fi(t))return t;if(g(t)){for(var e,i=Object.keys(t),n=i.length,r=new Array(n);n--;)e=i[n],r[n]={$key:e,$value:t[e]};return r}return"number"!=typeof t||isNaN(t)||(t=ae(t)),t||[]},unbind:function(){if(this.descriptor.ref&&((this._scope||this.vm).$refs[this.descriptor.ref]=null),this.frags)for(var t,e=this.frags.length;e--;)t=this.frags[e],this.deleteCachedFrag(t),t.destroy()}},Br={priority:Hr,terminal:!0,bind:function(){var t=this.el;if(t.__vue__)this.invalid=!0;else{var e=t.nextElementSibling;e&&null!==I(e,"v-else")&&(z(e),this.elseEl=e),this.anchor=nt("v-if"),J(t,this.anchor)}},update:function(t){this.invalid||(t?this.frag||this.insert():this.remove())},insert:function(){this.elseFrag&&(this.elseFrag.remove(),this.elseFrag=null),this.factory||(this.factory=new re(this.vm,this.el)),this.frag=this.factory.create(this._host,this._scope,this._frag),this.frag.before(this.anchor)},remove:function(){this.frag&&(this.frag.remove(),this.frag=null),this.elseEl&&!this.elseFrag&&(this.elseFactory||(this.elseFactory=new re(this.elseEl._context||this.vm,this.elseEl)),this.elseFrag=this.elseFactory.create(this._host,this._scope,this._frag),this.elseFrag.before(this.anchor))},unbind:function(){this.frag&&this.frag.destroy(),this.elseFrag&&this.elseFrag.destroy()}},zr={bind:function(){var t=this.el.nextElementSibling;t&&null!==I(t,"v-else")&&(this.elseEl=t)},update:function(t){this.apply(this.el,t),this.elseEl&&this.apply(this.elseEl,!t)},apply:function(t,e){function i(){t.style.display=e?"":"none"}H(t)?R(t,e?1:-1,i,this.vm):i()}},Ur={bind:function(){var t=this,e=this.el,i="range"===e.type,n=this.params.lazy,r=this.params.number,s=this.params.debounce,a=!1;if(Ii||i||(this.on("compositionstart",function(){a=!0}),this.on("compositionend",function(){a=!1,n||t.listener()})),this.focused=!1,i||n||(this.on("focus",function(){t.focused=!0}),this.on("blur",function(){t.focused=!1,t._frag&&!t._frag.inserted||t.rawListener()})),this.listener=this.rawListener=function(){if(!a&&t._bound){var n=r||i?o(e.value):e.value;t.set(n),Qi(function(){t._bound&&!t.focused&&t.update(t._watcher.value)})}},s&&(this.listener=y(this.listener,s)),this.hasjQuery="function"==typeof jQuery,this.hasjQuery){var h=jQuery.fn.on?"on":"bind";jQuery(e)[h]("change",this.rawListener),n||jQuery(e)[h]("input",this.listener)}else this.on("change",this.rawListener),n||this.on("input",this.listener);!n&&Hi&&(this.on("cut",function(){Qi(t.listener)}),this.on("keyup",function(e){46!==e.keyCode&&8!==e.keyCode||t.listener()})),(e.hasAttribute("value")||"TEXTAREA"===e.tagName&&e.value.trim())&&(this.afterBind=this.listener)},update:function(t){this.el.value=s(t)},unbind:function(){var t=this.el;if(this.hasjQuery){var e=jQuery.fn.off?"off":"unbind";jQuery(t)[e]("change",this.listener),jQuery(t)[e]("input",this.listener)}}},Jr={bind:function(){var t=this,e=this.el;this.getValue=function(){if(e.hasOwnProperty("_value"))return e._value;var i=e.value;return t.params.number&&(i=o(i)),i},this.listener=function(){t.set(t.getValue())},this.on("change",this.listener),e.hasAttribute("checked")&&(this.afterBind=this.listener)},update:function(t){this.el.checked=C(t,this.getValue())}},qr={bind:function(){var t=this,e=this.el;this.forceUpdate=function(){t._watcher&&t.update(t._watcher.get())};var i=this.multiple=e.hasAttribute("multiple");this.listener=function(){var n=le(e,i);n=t.params.number?Fi(n)?n.map(o):o(n):n,t.set(n)},this.on("change",this.listener);var n=le(e,i,!0);(i&&n.length||!i&&null!==n)&&(this.afterBind=this.listener),this.vm.$on("hook:attached",this.forceUpdate)},update:function(t){var e=this.el;e.selectedIndex=-1;for(var i,n,r=this.multiple&&Fi(t),s=e.options,o=s.length;o--;)i=s[o],n=i.hasOwnProperty("_value")?i._value:i.value,i.selected=r?ce(t,n)>-1:C(t,n)},unbind:function(){this.vm.$off("hook:attached",this.forceUpdate)}},Qr={bind:function(){function t(){var t=i.checked;return t&&i.hasOwnProperty("_trueValue")?i._trueValue:!t&&i.hasOwnProperty("_falseValue")?i._falseValue:t}var e=this,i=this.el;this.getValue=function(){return i.hasOwnProperty("_value")?i._value:e.params.number?o(i.value):i.value},this.listener=function(){var n=e._watcher.value;if(Fi(n)){var r=e.getValue();i.checked?b(n,r)<0&&n.push(r):n.$remove(r)}else e.set(t())},this.on("change",this.listener),i.hasAttribute("checked")&&(this.afterBind=this.listener)},update:function(t){var e=this.el;Fi(t)?e.checked=b(t,this.getValue())>-1:e.hasOwnProperty("_trueValue")?e.checked=C(t,e._trueValue):e.checked=!!t}},Gr={text:Ur,radio:Jr,select:qr,checkbox:Qr},Zr={priority:Sr,twoWay:!0,handlers:Gr,params:["lazy","number","debounce"],bind:function(){this.checkFilters(),this.hasRead&&!this.hasWrite;var t,e=this.el,i=e.tagName;if("INPUT"===i)t=Gr[e.type]||Gr.text;else if("SELECT"===i)t=Gr.select;else{if("TEXTAREA"!==i)return;t=Gr.text}e.__v_model=this,t.bind.call(this),this.update=t.update,this._unbind=t.unbind},checkFilters:function(){var t=this.filters;if(t)for(var e=t.length;e--;){var i=gt(this.vm.$options,"filters",t[e].name);("function"==typeof i||i.read)&&(this.hasRead=!0),i.write&&(this.hasWrite=!0)}},unbind:function(){this.el.__v_model=null,this._unbind&&this._unbind()}},Xr={esc:27,tab:9,enter:13,space:32,"delete":[8,46],up:38,left:37,right:39,down:40},Yr={priority:Er,acceptStatement:!0,keyCodes:Xr,bind:function(){if("IFRAME"===this.el.tagName&&"load"!==this.arg){var t=this;this.iframeBind=function(){q(t.el.contentWindow,t.arg,t.handler,t.modifiers.capture)},this.on("load",this.iframeBind)}},update:function(t){if(this.descriptor.raw||(t=function(){}),"function"==typeof t){this.modifiers.stop&&(t=fe(t)),this.modifiers.prevent&&(t=pe(t)),this.modifiers.self&&(t=de(t));var e=Object.keys(this.modifiers).filter(function(t){return"stop"!==t&&"prevent"!==t&&"self"!==t&&"capture"!==t});e.length&&(t=ue(t,e)),this.reset(),this.handler=t,this.iframeBind?this.iframeBind():q(this.el,this.arg,this.handler,this.modifiers.capture)}},reset:function(){var t=this.iframeBind?this.el.contentWindow:this.el;this.handler&&Q(t,this.arg,this.handler)},unbind:function(){this.reset()}},Kr=["-webkit-","-moz-","-ms-"],ts=["Webkit","Moz","ms"],es=/!important;?$/,is=Object.create(null),ns=null,rs={deep:!0,update:function(t){"string"==typeof t?this.el.style.cssText=t:Fi(t)?this.handleObject(t.reduce(v,{})):this.handleObject(t||{})},handleObject:function(t){var e,i,n=this.cache||(this.cache={});for(e in n)e in t||(this.handleSingle(e,null),delete n[e]);for(e in t)i=t[e],i!==n[e]&&(n[e]=i,this.handleSingle(e,i))},handleSingle:function(t,e){if(t=ve(t))if(null!=e&&(e+=""),e){var i=es.test(e)?"important":"";i?(e=e.replace(es,"").trim(),this.el.style.setProperty(t.kebab,e,i)):this.el.style[t.camel]=e}else this.el.style[t.camel]=""}},ss="path_to_url",os=/^xlink:/,as=/^v-|^:|^@|^(?:is|transition|transition-mode|debounce|track-by|stagger|enter-stagger|leave-stagger)$/,hs=/^(?:value|checked|selected|muted)$/,ls=/^(?:draggable|contenteditable|spellcheck)$/,cs={value:"_value","true-value":"_trueValue","false-value":"_falseValue"},us={priority:Fr,bind:function(){var t=this.arg,e=this.el.tagName;t||(this.deep=!0);var i=this.descriptor,n=i.interp;n&&(i.hasOneTime&&(this.expression=j(n,this._scope||this.vm)),(as.test(t)||"name"===t&&("PARTIAL"===e||"SLOT"===e))&&(this.el.removeAttribute(t),this.invalid=!0))},update:function(t){if(!this.invalid){var e=this.arg;this.arg?this.handleSingle(e,t):this.handleObject(t||{})}},handleObject:rs.handleObject,handleSingle:function(t,e){var i=this.el,n=this.descriptor.interp;if(this.modifiers.camel&&(t=l(t)),!n&&hs.test(t)&&t in i){var r="value"===t&&null==e?"":e;i[t]!==r&&(i[t]=r)}var s=cs[t];if(!n&&s){i[s]=e;var o=i.__v_model;o&&o.listener()}return"value"===t&&"TEXTAREA"===i.tagName?void i.removeAttribute(t):void(ls.test(t)?i.setAttribute(t,e?"true":"false"):null!=e&&e!==!1?"class"===t?(i.__v_trans&&(e+=" "+i.__v_trans.id+"-transition"), Z(i,e)):os.test(t)?i.setAttributeNS(ss,t,e===!0?"":e):i.setAttribute(t,e===!0?"":e):i.removeAttribute(t))}},fs={priority:Pr,bind:function(){if(this.arg){var t=this.id=l(this.arg),e=(this._scope||this.vm).$els;i(e,t)?e[t]=this.el:kt(e,t,this.el)}},unbind:function(){var t=(this._scope||this.vm).$els;t[this.id]===this.el&&(t[this.id]=null)}},ps={bind:function(){}},ds={bind:function(){var t=this.el;this.vm.$once("pre-hook:compiled",function(){t.removeAttribute("v-cloak")})}},vs={text:br,html:Nr,"for":Vr,"if":Br,show:zr,model:Zr,on:Yr,bind:us,el:fs,ref:ps,cloak:ds},ms={deep:!0,update:function(t){t?"string"==typeof t?this.setClass(t.trim().split(/\s+/)):this.setClass(ge(t)):this.cleanup()},setClass:function(t){this.cleanup(t);for(var e=0,i=t.length;i>e;e++){var n=t[e];n&&_e(this.el,n,X)}this.prevKeys=t},cleanup:function(t){var e=this.prevKeys;if(e)for(var i=e.length;i--;){var n=e[i];(!t||t.indexOf(n)<0)&&_e(this.el,n,Y)}}},gs={priority:Rr,params:["keep-alive","transition-mode","inline-template"],bind:function(){this.el.__vue__||(this.keepAlive=this.params.keepAlive,this.keepAlive&&(this.cache={}),this.params.inlineTemplate&&(this.inlineTemplate=K(this.el,!0)),this.pendingComponentCb=this.Component=null,this.pendingRemovals=0,this.pendingRemovalCb=null,this.anchor=nt("v-component"),J(this.el,this.anchor),this.el.removeAttribute("is"),this.el.removeAttribute(":is"),this.descriptor.ref&&this.el.removeAttribute("v-ref:"+u(this.descriptor.ref)),this.literal&&this.setComponent(this.expression))},update:function(t){this.literal||this.setComponent(t)},setComponent:function(t,e){if(this.invalidatePending(),t){var i=this;this.resolveComponent(t,function(){i.mountComponent(e)})}else this.unbuild(!0),this.remove(this.childVM,e),this.childVM=null},resolveComponent:function(t,e){var i=this;this.pendingComponentCb=w(function(n){i.ComponentName=n.options.name||("string"==typeof t?t:null),i.Component=n,e()}),this.vm._resolveComponent(t,this.pendingComponentCb)},mountComponent:function(t){this.unbuild(!0);var e=this,i=this.Component.options.activate,n=this.getCached(),r=this.build();i&&!n?(this.waitingFor=r,ye(i,r,function(){e.waitingFor===r&&(e.waitingFor=null,e.transition(r,t))})):(n&&r._updateRef(),this.transition(r,t))},invalidatePending:function(){this.pendingComponentCb&&(this.pendingComponentCb.cancel(),this.pendingComponentCb=null)},build:function(t){var e=this.getCached();if(e)return e;if(this.Component){var i={name:this.ComponentName,el:Gt(this.el),template:this.inlineTemplate,parent:this._host||this.vm,_linkerCachable:!this.inlineTemplate,_ref:this.descriptor.ref,_asComponent:!0,_isRouterView:this._isRouterView,_context:this.vm,_scope:this._scope,_frag:this._frag};t&&v(i,t);var n=new this.Component(i);return this.keepAlive&&(this.cache[this.Component.cid]=n),n}},getCached:function(){return this.keepAlive&&this.cache[this.Component.cid]},unbuild:function(t){this.waitingFor&&(this.keepAlive||this.waitingFor.$destroy(),this.waitingFor=null);var e=this.childVM;return!e||this.keepAlive?void(e&&(e._inactive=!0,e._updateRef(!0))):void e.$destroy(!1,t)},remove:function(t,e){var i=this.keepAlive;if(t){this.pendingRemovals++,this.pendingRemovalCb=e;var n=this;t.$remove(function(){n.pendingRemovals--,i||t._cleanup(),!n.pendingRemovals&&n.pendingRemovalCb&&(n.pendingRemovalCb(),n.pendingRemovalCb=null)})}else e&&e()},transition:function(t,e){var i=this,n=this.childVM;switch(n&&(n._inactive=!0),t._inactive=!1,this.childVM=t,i.params.transitionMode){case"in-out":t.$before(i.anchor,function(){i.remove(n,e)});break;case"out-in":i.remove(n,function(){t.$before(i.anchor,e)});break;default:i.remove(n),t.$before(i.anchor,e)}},unbind:function(){if(this.invalidatePending(),this.unbuild(),this.cache){for(var t in this.cache)this.cache[t].$destroy();this.cache=null}}},_s=Cn._propBindingModes,ys={},bs=/^[$_a-zA-Z]+[\w$]*$/,ws=Cn._propBindingModes,Cs={bind:function(){var t=this.vm,e=t._context,i=this.descriptor.prop,n=i.path,r=i.parentPath,s=i.mode===ws.TWO_WAY,o=this.parentWatcher=new zt(e,r,function(e){ke(t,i,e)},{twoWay:s,filters:i.filters,scope:this._scope});if($e(t,i,o.value),s){var a=this;t.$once("pre-hook:created",function(){a.childWatcher=new zt(t,n,function(t){o.set(t)},{sync:!0})})}},unbind:function(){this.parentWatcher.teardown(),this.childWatcher&&this.childWatcher.teardown()}},$s=[],ks=!1,xs="transition",As="animation",Os=Vi+"Duration",Ts=zi+"Duration",Ns=Pi&&window.requestAnimationFrame,js=Ns?function(t){Ns(function(){Ns(t)})}:function(t){setTimeout(t,50)},Es=Ee.prototype;Es.enter=function(t,e){this.cancelPending(),this.callHook("beforeEnter"),this.cb=e,X(this.el,this.enterClass),t(),this.entered=!1,this.callHookWithCb("enter"),this.entered||(this.cancel=this.hooks&&this.hooks.enterCancelled,Ne(this.enterNextTick))},Es.enterNextTick=function(){var t=this;this.justEntered=!0,js(function(){t.justEntered=!1});var e=this.enterDone,i=this.getCssTransitionType(this.enterClass);this.pendingJsCb?i===xs&&Y(this.el,this.enterClass):i===xs?(Y(this.el,this.enterClass),this.setupCssCb(Bi,e)):i===As?this.setupCssCb(Ui,e):e()},Es.enterDone=function(){this.entered=!0,this.cancel=this.pendingJsCb=null,Y(this.el,this.enterClass),this.callHook("afterEnter"),this.cb&&this.cb()},Es.leave=function(t,e){this.cancelPending(),this.callHook("beforeLeave"),this.op=t,this.cb=e,X(this.el,this.leaveClass),this.left=!1,this.callHookWithCb("leave"),this.left||(this.cancel=this.hooks&&this.hooks.leaveCancelled,this.op&&!this.pendingJsCb&&(this.justEntered?this.leaveDone():Ne(this.leaveNextTick)))},Es.leaveNextTick=function(){var t=this.getCssTransitionType(this.leaveClass);if(t){var e=t===xs?Bi:Ui;this.setupCssCb(e,this.leaveDone)}else this.leaveDone()},Es.leaveDone=function(){this.left=!0,this.cancel=this.pendingJsCb=null,this.op(),Y(this.el,this.leaveClass),this.callHook("afterLeave"),this.cb&&this.cb(),this.op=null},Es.cancelPending=function(){this.op=this.cb=null;var t=!1;this.pendingCssCb&&(t=!0,Q(this.el,this.pendingCssEvent,this.pendingCssCb),this.pendingCssEvent=this.pendingCssCb=null),this.pendingJsCb&&(t=!0,this.pendingJsCb.cancel(),this.pendingJsCb=null),t&&(Y(this.el,this.enterClass),Y(this.el,this.leaveClass)),this.cancel&&(this.cancel.call(this.vm,this.el),this.cancel=null)},Es.callHook=function(t){this.hooks&&this.hooks[t]&&this.hooks[t].call(this.vm,this.el)},Es.callHookWithCb=function(t){var e=this.hooks&&this.hooks[t];e&&(e.length>1&&(this.pendingJsCb=w(this[t+"Done"])),e.call(this.vm,this.el,this.pendingJsCb))},Es.getCssTransitionType=function(t){if(!(!Bi||document.hidden||this.hooks&&this.hooks.css===!1||Se(this.el))){var e=this.type||this.typeCache[t];if(e)return e;var i=this.el.style,n=window.getComputedStyle(this.el),r=i[Os]||n[Os];if(r&&"0s"!==r)e=xs;else{var s=i[Ts]||n[Ts];s&&"0s"!==s&&(e=As)}return e&&(this.typeCache[t]=e),e}},Es.setupCssCb=function(t,e){this.pendingCssEvent=t;var i=this,n=this.el,r=this.pendingCssCb=function(s){s.target===n&&(Q(n,t,r),i.pendingCssEvent=i.pendingCssCb=null,!i.pendingJsCb&&e&&e())};q(n,t,r)};var Ss={priority:Dr,update:function(t,e){var i=this.el,n=gt(this.vm.$options,"transitions",t);t=t||"v",i.__v_trans=new Ee(i,t,n,this.vm),e&&Y(i,e+"-transition"),X(i,t+"-transition")}},Fs={style:rs,"class":ms,component:gs,prop:Cs,transition:Ss},Ds=/^v-bind:|^:/,Ps=/^v-on:|^@/,Rs=/^v-([^:]+)(?:$|:(.*)$)/,Ls=/\.[^\.]+/g,Hs=/^(v-bind:|:)?transition$/,Is=1e3,Ms=2e3;Xe.terminal=!0;var Ws=/[^\w\-:\.]/,Vs=Object.freeze({compile:Fe,compileAndLinkProps:He,compileRoot:Ie,transclude:ri,resolveSlots:hi}),Bs=/^v-on:|^@/;pi.prototype._bind=function(){var t=this.name,e=this.descriptor;if(("cloak"!==t||this.vm._isCompiled)&&this.el&&this.el.removeAttribute){var i=e.attr||"v-"+t;this.el.removeAttribute(i)}var n=e.def;if("function"==typeof n?this.update=n:v(this,n),this._setupParams(),this.bind&&this.bind(),this._bound=!0,this.literal)this.update&&this.update(e.raw);else if((this.expression||this.modifiers)&&(this.update||this.twoWay)&&!this._checkStatement()){var r=this;this.update?this._update=function(t,e){r._locked||r.update(t,e)}:this._update=fi;var s=this._preProcess?p(this._preProcess,this):null,o=this._postProcess?p(this._postProcess,this):null,a=this._watcher=new zt(this.vm,this.expression,this._update,{filters:this.filters,twoWay:this.twoWay,deep:this.deep,preProcess:s,postProcess:o,scope:this._scope});this.afterBind?this.afterBind():this.update&&this.update(a.value)}},pi.prototype._setupParams=function(){if(this.params){var t=this.params;this.params=Object.create(null);for(var e,i,n,r=t.length;r--;)e=u(t[r]),n=l(e),i=M(this.el,e),null!=i?this._setupParamWatcher(n,i):(i=I(this.el,e),null!=i&&(this.params[n]=""===i?!0:i))}},pi.prototype._setupParamWatcher=function(t,e){var i=this,n=!1,r=(this._scope||this.vm).$watch(e,function(e,r){if(i.params[t]=e,n){var s=i.paramWatchers&&i.paramWatchers[t];s&&s.call(i,e,r)}else n=!0},{immediate:!0,user:!1});(this._paramUnwatchFns||(this._paramUnwatchFns=[])).push(r)},pi.prototype._checkStatement=function(){var t=this.expression;if(t&&this.acceptStatement&&!It(t)){var e=Ht(t).get,i=this._scope||this.vm,n=function(t){i.$event=t,e.call(i,i),i.$event=null};return this.filters&&(n=i._applyFilters(n,null,this.filters)),this.update(n),!0}},pi.prototype.set=function(t){this.twoWay&&this._withLock(function(){this._watcher.set(t)})},pi.prototype._withLock=function(t){var e=this;e._locked=!0,t.call(e),Qi(function(){e._locked=!1})},pi.prototype.on=function(t,e,i){q(this.el,t,e,i),(this._listeners||(this._listeners=[])).push([t,e])},pi.prototype._teardown=function(){if(this._bound){this._bound=!1,this.unbind&&this.unbind(),this._watcher&&this._watcher.teardown();var t,e=this._listeners;if(e)for(t=e.length;t--;)Q(this.el,e[t][0],e[t][1]);var i=this._paramUnwatchFns;if(i)for(t=i.length;t--;)i[t]();this.vm=this.el=this._watcher=this._listeners=null}};var zs=/[^|]\|[^|]/;xt(bi),ci(bi),ui(bi),di(bi),vi(bi),mi(bi),gi(bi),_i(bi),yi(bi);var Us={priority:Mr,params:["name"],bind:function(){var t=this.params.name||"default",e=this.vm._slotContents&&this.vm._slotContents[t];e&&e.hasChildNodes()?this.compile(e.cloneNode(!0),this.vm._context,this.vm):this.fallback()},compile:function(t,e,i){if(t&&e){if(this.el.hasChildNodes()&&1===t.childNodes.length&&1===t.childNodes[0].nodeType&&t.childNodes[0].hasAttribute("v-if")){var n=document.createElement("template");n.setAttribute("v-else",""),n.innerHTML=this.el.innerHTML,n._context=this.vm,t.appendChild(n)}var r=i?i._scope:this._scope;this.unlink=e.$compile(t,i,r,this._frag)}t?J(this.el,t):z(this.el)},fallback:function(){this.compile(K(this.el,!0),this.vm)},unbind:function(){this.unlink&&this.unlink()}},Js={priority:Lr,params:["name"],paramWatchers:{name:function(t){Br.remove.call(this),t&&this.insert(t)}},bind:function(){this.anchor=nt("v-partial"),J(this.el,this.anchor),this.insert(this.params.name)},insert:function(t){var e=gt(this.vm.$options,"partials",t,!0);e&&(this.factory=new re(this.vm,e),Br.insert.call(this))},unbind:function(){this.frag&&this.frag.destroy()}},qs={slot:Us,partial:Js},Qs=Vr._postProcess,Gs=/(\d{3})(?=\d)/g,Zs={orderBy:$i,filterBy:Ci,limitBy:wi,json:{read:function(t,e){return"string"==typeof t?t:JSON.stringify(t,null,Number(e)||2)},write:function(t){try{return JSON.parse(t)}catch(e){return t}}},capitalize:function(t){return t||0===t?(t=t.toString(),t.charAt(0).toUpperCase()+t.slice(1)):""},uppercase:function(t){return t||0===t?t.toString().toUpperCase():""},lowercase:function(t){return t||0===t?t.toString().toLowerCase():""},currency:function(t,e,i){if(t=parseFloat(t),!isFinite(t)||!t&&0!==t)return"";e=null!=e?e:"$",i=null!=i?i:2;var n=Math.abs(t).toFixed(i),r=i?n.slice(0,-1-i):n,s=r.length%3,o=s>0?r.slice(0,s)+(r.length>3?",":""):"",a=i?n.slice(-1-i):"",h=0>t?"-":"";return h+e+o+r.slice(s).replace(Gs,"$1,")+a},pluralize:function(t){var e=d(arguments,1);return e.length>1?e[t%10-1]||e[e.length-1]:e[0]+(1===t?"":"s")},debounce:function(t,e){return t?(e||(e=300),y(t,e)):void 0}};return xi(bi),bi.version="1.0.24",setTimeout(function(){Cn.devtools&&Ri&&Ri.emit("init",bi)},0),bi}); ```
/content/code_sandbox/public/vendor/vue/dist/vue.min.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
25,276
```javascript /*! * Vue.js v1.0.24 * (c) 2016 Evan You */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.Vue = factory()); }(this, function () { 'use strict'; function set(obj, key, val) { if (hasOwn(obj, key)) { obj[key] = val; return; } if (obj._isVue) { set(obj._data, key, val); return; } var ob = obj.__ob__; if (!ob) { obj[key] = val; return; } ob.convert(key, val); ob.dep.notify(); if (ob.vms) { var i = ob.vms.length; while (i--) { var vm = ob.vms[i]; vm._proxy(key); vm._digest(); } } return val; } /** * Delete a property and trigger change if necessary. * * @param {Object} obj * @param {String} key */ function del(obj, key) { if (!hasOwn(obj, key)) { return; } delete obj[key]; var ob = obj.__ob__; if (!ob) { if (obj._isVue) { delete obj._data[key]; obj._digest(); } return; } ob.dep.notify(); if (ob.vms) { var i = ob.vms.length; while (i--) { var vm = ob.vms[i]; vm._unproxy(key); vm._digest(); } } } var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Check whether the object has the property. * * @param {Object} obj * @param {String} key * @return {Boolean} */ function hasOwn(obj, key) { return hasOwnProperty.call(obj, key); } /** * Check if an expression is a literal value. * * @param {String} exp * @return {Boolean} */ var literalValueRE = /^\s?(true|false|-?[\d\.]+|'[^']*'|"[^"]*")\s?$/; function isLiteral(exp) { return literalValueRE.test(exp); } /** * Check if a string starts with $ or _ * * @param {String} str * @return {Boolean} */ function isReserved(str) { var c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F; } /** * Guard text output, make sure undefined outputs * empty string * * @param {*} value * @return {String} */ function _toString(value) { return value == null ? '' : value.toString(); } /** * Check and convert possible numeric strings to numbers * before setting back to data * * @param {*} value * @return {*|Number} */ function toNumber(value) { if (typeof value !== 'string') { return value; } else { var parsed = Number(value); return isNaN(parsed) ? value : parsed; } } /** * Convert string boolean literals into real booleans. * * @param {*} value * @return {*|Boolean} */ function toBoolean(value) { return value === 'true' ? true : value === 'false' ? false : value; } /** * Strip quotes from a string * * @param {String} str * @return {String | false} */ function stripQuotes(str) { var a = str.charCodeAt(0); var b = str.charCodeAt(str.length - 1); return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str; } /** * Camelize a hyphen-delmited string. * * @param {String} str * @return {String} */ var camelizeRE = /-(\w)/g; function camelize(str) { return str.replace(camelizeRE, toUpper); } function toUpper(_, c) { return c ? c.toUpperCase() : ''; } /** * Hyphenate a camelCase string. * * @param {String} str * @return {String} */ var hyphenateRE = /([a-z\d])([A-Z])/g; function hyphenate(str) { return str.replace(hyphenateRE, '$1-$2').toLowerCase(); } /** * Converts hyphen/underscore/slash delimitered names into * camelized classNames. * * e.g. my-component => MyComponent * some_else => SomeElse * some/comp => SomeComp * * @param {String} str * @return {String} */ var classifyRE = /(?:^|[-_\/])(\w)/g; function classify(str) { return str.replace(classifyRE, toUpper); } /** * Simple bind, faster than native * * @param {Function} fn * @param {Object} ctx * @return {Function} */ function bind(fn, ctx) { return function (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx); }; } /** * Convert an Array-like object to a real Array. * * @param {Array-like} list * @param {Number} [start] - start index * @return {Array} */ function toArray(list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret; } /** * Mix properties into target object. * * @param {Object} to * @param {Object} from */ function extend(to, from) { var keys = Object.keys(from); var i = keys.length; while (i--) { to[keys[i]] = from[keys[i]]; } return to; } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. * * @param {*} obj * @return {Boolean} */ function isObject(obj) { return obj !== null && typeof obj === 'object'; } /** * Strict object type check. Only returns true * for plain JavaScript objects. * * @param {*} obj * @return {Boolean} */ var toString = Object.prototype.toString; var OBJECT_STRING = '[object Object]'; function isPlainObject(obj) { return toString.call(obj) === OBJECT_STRING; } /** * Array type check. * * @param {*} obj * @return {Boolean} */ var isArray = Array.isArray; /** * Define a property. * * @param {Object} obj * @param {String} key * @param {*} val * @param {Boolean} [enumerable] */ function def(obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Debounce a function so it only gets called after the * input stops arriving after the given wait period. * * @param {Function} func * @param {Number} wait * @return {Function} - the debounced function */ function _debounce(func, wait) { var timeout, args, context, timestamp, result; var later = function later() { var last = Date.now() - timestamp; if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; } }; return function () { context = this; args = arguments; timestamp = Date.now(); if (!timeout) { timeout = setTimeout(later, wait); } return result; }; } /** * Manual indexOf because it's slightly faster than * native. * * @param {Array} arr * @param {*} obj */ function indexOf(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) return i; } return -1; } /** * Make a cancellable version of an async callback. * * @param {Function} fn * @return {Function} */ function cancellable(fn) { var cb = function cb() { if (!cb.cancelled) { return fn.apply(this, arguments); } }; cb.cancel = function () { cb.cancelled = true; }; return cb; } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? * * @param {*} a * @param {*} b * @return {Boolean} */ function looseEqual(a, b) { /* eslint-disable eqeqeq */ return a == b || (isObject(a) && isObject(b) ? JSON.stringify(a) === JSON.stringify(b) : false); /* eslint-enable eqeqeq */ } var hasProto = ('__proto__' in {}); // Browser environment sniffing var inBrowser = typeof window !== 'undefined' && Object.prototype.toString.call(window) !== '[object Object]'; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; // UA sniffing for working around browser-specific quirks var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isAndroid = UA && UA.indexOf('android') > 0; var isIos = UA && /(iphone|ipad|ipod|ios)/i.test(UA); var isWechat = UA && UA.indexOf('micromessenger') > 0; var transitionProp = undefined; var transitionEndEvent = undefined; var animationProp = undefined; var animationEndEvent = undefined; // Transition property/event sniffing if (inBrowser && !isIE9) { var isWebkitTrans = window.ontransitionend === undefined && window.onwebkittransitionend !== undefined; var isWebkitAnim = window.onanimationend === undefined && window.onwebkitanimationend !== undefined; transitionProp = isWebkitTrans ? 'WebkitTransition' : 'transition'; transitionEndEvent = isWebkitTrans ? 'webkitTransitionEnd' : 'transitionend'; animationProp = isWebkitAnim ? 'WebkitAnimation' : 'animation'; animationEndEvent = isWebkitAnim ? 'webkitAnimationEnd' : 'animationend'; } /** * Defer a task to execute it asynchronously. Ideally this * should be executed as a microtask, so we leverage * MutationObserver if it's available, and fallback to * setTimeout(0). * * @param {Function} cb * @param {Object} ctx */ var nextTick = (function () { var callbacks = []; var pending = false; var timerFunc; function nextTickHandler() { pending = false; var copies = callbacks.slice(0); callbacks = []; for (var i = 0; i < copies.length; i++) { copies[i](); } } /* istanbul ignore if */ if (typeof MutationObserver !== 'undefined' && !(isWechat && isIos)) { var counter = 1; var observer = new MutationObserver(nextTickHandler); var textNode = document.createTextNode(counter); observer.observe(textNode, { characterData: true }); timerFunc = function () { counter = (counter + 1) % 2; textNode.data = counter; }; } else { // webpack attempts to inject a shim for setImmediate // if it is used as a global, so we have to work around that to // avoid bundling unnecessary code. var context = inBrowser ? window : typeof global !== 'undefined' ? global : {}; timerFunc = context.setImmediate || setTimeout; } return function (cb, ctx) { var func = ctx ? function () { cb.call(ctx); } : cb; callbacks.push(func); if (pending) return; pending = true; timerFunc(nextTickHandler, 0); }; })(); var _Set = undefined; /* istanbul ignore if */ if (typeof Set !== 'undefined' && Set.toString().match(/native code/)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = function () { this.set = Object.create(null); }; _Set.prototype.has = function (key) { return this.set[key] !== undefined; }; _Set.prototype.add = function (key) { this.set[key] = 1; }; _Set.prototype.clear = function () { this.set = Object.create(null); }; } function Cache(limit) { this.size = 0; this.limit = limit; this.head = this.tail = undefined; this._keymap = Object.create(null); } var p = Cache.prototype; /** * Put <value> into the cache associated with <key>. * Returns the entry which was removed to make room for * the new entry. Otherwise undefined is returned. * (i.e. if there was enough room already). * * @param {String} key * @param {*} value * @return {Entry|undefined} */ p.put = function (key, value) { var removed; if (this.size === this.limit) { removed = this.shift(); } var entry = this.get(key, true); if (!entry) { entry = { key: key }; this._keymap[key] = entry; if (this.tail) { this.tail.newer = entry; entry.older = this.tail; } else { this.head = entry; } this.tail = entry; this.size++; } entry.value = value; return removed; }; /** * Purge the least recently used (oldest) entry from the * cache. Returns the removed entry or undefined if the * cache was empty. */ p.shift = function () { var entry = this.head; if (entry) { this.head = this.head.newer; this.head.older = undefined; entry.newer = entry.older = undefined; this._keymap[entry.key] = undefined; this.size--; } return entry; }; /** * Get and register recent use of <key>. Returns the value * associated with <key> or undefined if not in cache. * * @param {String} key * @param {Boolean} returnEntry * @return {Entry|*} */ p.get = function (key, returnEntry) { var entry = this._keymap[key]; if (entry === undefined) return; if (entry === this.tail) { return returnEntry ? entry : entry.value; } // HEAD--------------TAIL // <.older .newer> // <--- add direction -- // A B C <D> E if (entry.newer) { if (entry === this.head) { this.head = entry.newer; } entry.newer.older = entry.older; // C <-- E. } if (entry.older) { entry.older.newer = entry.newer; // C. --> E } entry.newer = undefined; // D --x entry.older = this.tail; // D. --> E if (this.tail) { this.tail.newer = entry; // E. <-- D } this.tail = entry; return returnEntry ? entry : entry.value; }; var cache$1 = new Cache(1000); var filterTokenRE = /[^\s'"]+|'[^']*'|"[^"]*"/g; var reservedArgRE = /^in$|^-?\d+/; /** * Parser state */ var str; var dir; var c; var prev; var i; var l; var lastFilterIndex; var inSingle; var inDouble; var curly; var square; var paren; /** * Push a filter to the current directive object */ function pushFilter() { var exp = str.slice(lastFilterIndex, i).trim(); var filter; if (exp) { filter = {}; var tokens = exp.match(filterTokenRE); filter.name = tokens[0]; if (tokens.length > 1) { filter.args = tokens.slice(1).map(processFilterArg); } } if (filter) { (dir.filters = dir.filters || []).push(filter); } lastFilterIndex = i + 1; } /** * Check if an argument is dynamic and strip quotes. * * @param {String} arg * @return {Object} */ function processFilterArg(arg) { if (reservedArgRE.test(arg)) { return { value: toNumber(arg), dynamic: false }; } else { var stripped = stripQuotes(arg); var dynamic = stripped === arg; return { value: dynamic ? arg : stripped, dynamic: dynamic }; } } /** * Parse a directive value and extract the expression * and its filters into a descriptor. * * Example: * * "a + 1 | uppercase" will yield: * { * expression: 'a + 1', * filters: [ * { name: 'uppercase', args: null } * ] * } * * @param {String} s * @return {Object} */ function parseDirective(s) { var hit = cache$1.get(s); if (hit) { return hit; } // reset parser state str = s; inSingle = inDouble = false; curly = square = paren = 0; lastFilterIndex = 0; dir = {}; for (i = 0, l = str.length; i < l; i++) { prev = c; c = str.charCodeAt(i); if (inSingle) { // check single quote if (c === 0x27 && prev !== 0x5C) inSingle = !inSingle; } else if (inDouble) { // check double quote if (c === 0x22 && prev !== 0x5C) inDouble = !inDouble; } else if (c === 0x7C && // pipe str.charCodeAt(i + 1) !== 0x7C && str.charCodeAt(i - 1) !== 0x7C) { if (dir.expression == null) { // first filter, end of expression lastFilterIndex = i + 1; dir.expression = str.slice(0, i).trim(); } else { // already has filter pushFilter(); } } else { switch (c) { case 0x22: inDouble = true;break; // " case 0x27: inSingle = true;break; // ' case 0x28: paren++;break; // ( case 0x29: paren--;break; // ) case 0x5B: square++;break; // [ case 0x5D: square--;break; // ] case 0x7B: curly++;break; // { case 0x7D: curly--;break; // } } } } if (dir.expression == null) { dir.expression = str.slice(0, i).trim(); } else if (lastFilterIndex !== 0) { pushFilter(); } cache$1.put(s, dir); return dir; } var directive = Object.freeze({ parseDirective: parseDirective }); var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g; var cache = undefined; var tagRE = undefined; var htmlRE = undefined; /** * Escape a string so it can be used in a RegExp * constructor. * * @param {String} str */ function escapeRegex(str) { return str.replace(regexEscapeRE, '\\$&'); } function compileRegex() { var open = escapeRegex(config.delimiters[0]); var close = escapeRegex(config.delimiters[1]); var unsafeOpen = escapeRegex(config.unsafeDelimiters[0]); var unsafeClose = escapeRegex(config.unsafeDelimiters[1]); tagRE = new RegExp(unsafeOpen + '((?:.|\\n)+?)' + unsafeClose + '|' + open + '((?:.|\\n)+?)' + close, 'g'); htmlRE = new RegExp('^' + unsafeOpen + '.*' + unsafeClose + '$'); // reset cache cache = new Cache(1000); } /** * Parse a template text string into an array of tokens. * * @param {String} text * @return {Array<Object> | null} * - {String} type * - {String} value * - {Boolean} [html] * - {Boolean} [oneTime] */ function parseText(text) { if (!cache) { compileRegex(); } var hit = cache.get(text); if (hit) { return hit; } if (!tagRE.test(text)) { return null; } var tokens = []; var lastIndex = tagRE.lastIndex = 0; var match, index, html, value, first, oneTime; /* eslint-disable no-cond-assign */ while (match = tagRE.exec(text)) { /* eslint-enable no-cond-assign */ index = match.index; // push text token if (index > lastIndex) { tokens.push({ value: text.slice(lastIndex, index) }); } // tag token html = htmlRE.test(match[0]); value = html ? match[1] : match[2]; first = value.charCodeAt(0); oneTime = first === 42; // * value = oneTime ? value.slice(1) : value; tokens.push({ tag: true, value: value.trim(), html: html, oneTime: oneTime }); lastIndex = index + match[0].length; } if (lastIndex < text.length) { tokens.push({ value: text.slice(lastIndex) }); } cache.put(text, tokens); return tokens; } /** * Format a list of tokens into an expression. * e.g. tokens parsed from 'a {{b}} c' can be serialized * into one single expression as '"a " + b + " c"'. * * @param {Array} tokens * @param {Vue} [vm] * @return {String} */ function tokensToExp(tokens, vm) { if (tokens.length > 1) { return tokens.map(function (token) { return formatToken(token, vm); }).join('+'); } else { return formatToken(tokens[0], vm, true); } } /** * Format a single token. * * @param {Object} token * @param {Vue} [vm] * @param {Boolean} [single] * @return {String} */ function formatToken(token, vm, single) { return token.tag ? token.oneTime && vm ? '"' + vm.$eval(token.value) + '"' : inlineFilters(token.value, single) : '"' + token.value + '"'; } /** * For an attribute with multiple interpolation tags, * e.g. attr="some-{{thing | filter}}", in order to combine * the whole thing into a single watchable expression, we * have to inline those filters. This function does exactly * that. This is a bit hacky but it avoids heavy changes * to directive parser and watcher mechanism. * * @param {String} exp * @param {Boolean} single * @return {String} */ var filterRE = /[^|]\|[^|]/; function inlineFilters(exp, single) { if (!filterRE.test(exp)) { return single ? exp : '(' + exp + ')'; } else { var dir = parseDirective(exp); if (!dir.filters) { return '(' + exp + ')'; } else { return 'this._applyFilters(' + dir.expression + // value ',null,' + // oldValue (null for read) JSON.stringify(dir.filters) + // filter descriptors ',false)'; // write? } } } var text = Object.freeze({ compileRegex: compileRegex, parseText: parseText, tokensToExp: tokensToExp }); var delimiters = ['{{', '}}']; var unsafeDelimiters = ['{{{', '}}}']; var config = Object.defineProperties({ /** * Whether to print debug messages. * Also enables stack trace for warnings. * * @type {Boolean} */ debug: false, /** * Whether to suppress warnings. * * @type {Boolean} */ silent: false, /** * Whether to use async rendering. */ async: true, /** * Whether to warn against errors caught when evaluating * expressions. */ warnExpressionErrors: true, /** * Whether to allow devtools inspection. * Disabled by default in production builds. */ devtools: 'development' !== 'production', /** * Internal flag to indicate the delimiters have been * changed. * * @type {Boolean} */ _delimitersChanged: true, /** * List of asset types that a component can own. * * @type {Array} */ _assetTypes: ['component', 'directive', 'elementDirective', 'filter', 'transition', 'partial'], /** * prop binding modes */ _propBindingModes: { ONE_WAY: 0, TWO_WAY: 1, ONE_TIME: 2 }, /** * Max circular updates allowed in a batcher flush cycle. */ _maxUpdateCount: 100 }, { delimiters: { /** * Interpolation delimiters. Changing these would trigger * the text parser to re-compile the regular expressions. * * @type {Array<String>} */ get: function get() { return delimiters; }, set: function set(val) { delimiters = val; compileRegex(); }, configurable: true, enumerable: true }, unsafeDelimiters: { get: function get() { return unsafeDelimiters; }, set: function set(val) { unsafeDelimiters = val; compileRegex(); }, configurable: true, enumerable: true } }); var warn = undefined; var formatComponentName = undefined; if ('development' !== 'production') { (function () { var hasConsole = typeof console !== 'undefined'; warn = function (msg, vm) { if (hasConsole && !config.silent) { console.error('[Vue warn]: ' + msg + (vm ? formatComponentName(vm) : '')); } }; formatComponentName = function (vm) { var name = vm._isVue ? vm.$options.name : vm.name; return name ? ' (found in component: <' + hyphenate(name) + '>)' : ''; }; })(); } /** * Append with transition. * * @param {Element} el * @param {Element} target * @param {Vue} vm * @param {Function} [cb] */ function appendWithTransition(el, target, vm, cb) { applyTransition(el, 1, function () { target.appendChild(el); }, vm, cb); } /** * InsertBefore with transition. * * @param {Element} el * @param {Element} target * @param {Vue} vm * @param {Function} [cb] */ function beforeWithTransition(el, target, vm, cb) { applyTransition(el, 1, function () { before(el, target); }, vm, cb); } /** * Remove with transition. * * @param {Element} el * @param {Vue} vm * @param {Function} [cb] */ function removeWithTransition(el, vm, cb) { applyTransition(el, -1, function () { remove(el); }, vm, cb); } /** * Apply transitions with an operation callback. * * @param {Element} el * @param {Number} direction * 1: enter * -1: leave * @param {Function} op - the actual DOM operation * @param {Vue} vm * @param {Function} [cb] */ function applyTransition(el, direction, op, vm, cb) { var transition = el.__v_trans; if (!transition || // skip if there are no js hooks and CSS transition is // not supported !transition.hooks && !transitionEndEvent || // skip transitions for initial compile !vm._isCompiled || // if the vm is being manipulated by a parent directive // during the parent's compilation phase, skip the // animation. vm.$parent && !vm.$parent._isCompiled) { op(); if (cb) cb(); return; } var action = direction > 0 ? 'enter' : 'leave'; transition[action](op, cb); } var transition = Object.freeze({ appendWithTransition: appendWithTransition, beforeWithTransition: beforeWithTransition, removeWithTransition: removeWithTransition, applyTransition: applyTransition }); /** * Query an element selector if it's not an element already. * * @param {String|Element} el * @return {Element} */ function query(el) { if (typeof el === 'string') { var selector = el; el = document.querySelector(el); if (!el) { 'development' !== 'production' && warn('Cannot find element: ' + selector); } } return el; } /** * Check if a node is in the document. * Note: document.documentElement.contains should work here * but always returns false for comment nodes in phantomjs, * making unit tests difficult. This is fixed by doing the * contains() check on the node's parentNode instead of * the node itself. * * @param {Node} node * @return {Boolean} */ function inDoc(node) { if (!node) return false; var doc = node.ownerDocument.documentElement; var parent = node.parentNode; return doc === node || doc === parent || !!(parent && parent.nodeType === 1 && doc.contains(parent)); } /** * Get and remove an attribute from a node. * * @param {Node} node * @param {String} _attr */ function getAttr(node, _attr) { var val = node.getAttribute(_attr); if (val !== null) { node.removeAttribute(_attr); } return val; } /** * Get an attribute with colon or v-bind: prefix. * * @param {Node} node * @param {String} name * @return {String|null} */ function getBindAttr(node, name) { var val = getAttr(node, ':' + name); if (val === null) { val = getAttr(node, 'v-bind:' + name); } return val; } /** * Check the presence of a bind attribute. * * @param {Node} node * @param {String} name * @return {Boolean} */ function hasBindAttr(node, name) { return node.hasAttribute(name) || node.hasAttribute(':' + name) || node.hasAttribute('v-bind:' + name); } /** * Insert el before target * * @param {Element} el * @param {Element} target */ function before(el, target) { target.parentNode.insertBefore(el, target); } /** * Insert el after target * * @param {Element} el * @param {Element} target */ function after(el, target) { if (target.nextSibling) { before(el, target.nextSibling); } else { target.parentNode.appendChild(el); } } /** * Remove el from DOM * * @param {Element} el */ function remove(el) { el.parentNode.removeChild(el); } /** * Prepend el to target * * @param {Element} el * @param {Element} target */ function prepend(el, target) { if (target.firstChild) { before(el, target.firstChild); } else { target.appendChild(el); } } /** * Replace target with el * * @param {Element} target * @param {Element} el */ function replace(target, el) { var parent = target.parentNode; if (parent) { parent.replaceChild(el, target); } } /** * Add event listener shorthand. * * @param {Element} el * @param {String} event * @param {Function} cb * @param {Boolean} [useCapture] */ function on(el, event, cb, useCapture) { el.addEventListener(event, cb, useCapture); } /** * Remove event listener shorthand. * * @param {Element} el * @param {String} event * @param {Function} cb */ function off(el, event, cb) { el.removeEventListener(event, cb); } /** * For IE9 compat: when both class and :class are present * getAttribute('class') returns wrong value... * * @param {Element} el * @return {String} */ function getClass(el) { var classname = el.className; if (typeof classname === 'object') { classname = classname.baseVal || ''; } return classname; } /** * In IE9, setAttribute('class') will result in empty class * if the element also has the :class attribute; However in * PhantomJS, setting `className` does not work on SVG elements... * So we have to do a conditional check here. * * @param {Element} el * @param {String} cls */ function setClass(el, cls) { /* istanbul ignore if */ if (isIE9 && !/svg$/.test(el.namespaceURI)) { el.className = cls; } else { el.setAttribute('class', cls); } } /** * Add class with compatibility for IE & SVG * * @param {Element} el * @param {String} cls */ function addClass(el, cls) { if (el.classList) { el.classList.add(cls); } else { var cur = ' ' + getClass(el) + ' '; if (cur.indexOf(' ' + cls + ' ') < 0) { setClass(el, (cur + cls).trim()); } } } /** * Remove class with compatibility for IE & SVG * * @param {Element} el * @param {String} cls */ function removeClass(el, cls) { if (el.classList) { el.classList.remove(cls); } else { var cur = ' ' + getClass(el) + ' '; var tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' '); } setClass(el, cur.trim()); } if (!el.className) { el.removeAttribute('class'); } } /** * Extract raw content inside an element into a temporary * container div * * @param {Element} el * @param {Boolean} asFragment * @return {Element|DocumentFragment} */ function extractContent(el, asFragment) { var child; var rawContent; /* istanbul ignore if */ if (isTemplate(el) && isFragment(el.content)) { el = el.content; } if (el.hasChildNodes()) { trimNode(el); rawContent = asFragment ? document.createDocumentFragment() : document.createElement('div'); /* eslint-disable no-cond-assign */ while (child = el.firstChild) { /* eslint-enable no-cond-assign */ rawContent.appendChild(child); } } return rawContent; } /** * Trim possible empty head/tail text and comment * nodes inside a parent. * * @param {Node} node */ function trimNode(node) { var child; /* eslint-disable no-sequences */ while ((child = node.firstChild, isTrimmable(child))) { node.removeChild(child); } while ((child = node.lastChild, isTrimmable(child))) { node.removeChild(child); } /* eslint-enable no-sequences */ } function isTrimmable(node) { return node && (node.nodeType === 3 && !node.data.trim() || node.nodeType === 8); } /** * Check if an element is a template tag. * Note if the template appears inside an SVG its tagName * will be in lowercase. * * @param {Element} el */ function isTemplate(el) { return el.tagName && el.tagName.toLowerCase() === 'template'; } /** * Create an "anchor" for performing dom insertion/removals. * This is used in a number of scenarios: * - fragment instance * - v-html * - v-if * - v-for * - component * * @param {String} content * @param {Boolean} persist - IE trashes empty textNodes on * cloneNode(true), so in certain * cases the anchor needs to be * non-empty to be persisted in * templates. * @return {Comment|Text} */ function createAnchor(content, persist) { var anchor = config.debug ? document.createComment(content) : document.createTextNode(persist ? ' ' : ''); anchor.__v_anchor = true; return anchor; } /** * Find a component ref attribute that starts with $. * * @param {Element} node * @return {String|undefined} */ var refRE = /^v-ref:/; function findRef(node) { if (node.hasAttributes()) { var attrs = node.attributes; for (var i = 0, l = attrs.length; i < l; i++) { var name = attrs[i].name; if (refRE.test(name)) { return camelize(name.replace(refRE, '')); } } } } /** * Map a function to a range of nodes . * * @param {Node} node * @param {Node} end * @param {Function} op */ function mapNodeRange(node, end, op) { var next; while (node !== end) { next = node.nextSibling; op(node); node = next; } op(end); } /** * Remove a range of nodes with transition, store * the nodes in a fragment with correct ordering, * and call callback when done. * * @param {Node} start * @param {Node} end * @param {Vue} vm * @param {DocumentFragment} frag * @param {Function} cb */ function removeNodeRange(start, end, vm, frag, cb) { var done = false; var removed = 0; var nodes = []; mapNodeRange(start, end, function (node) { if (node === end) done = true; nodes.push(node); removeWithTransition(node, vm, onRemoved); }); function onRemoved() { removed++; if (done && removed >= nodes.length) { for (var i = 0; i < nodes.length; i++) { frag.appendChild(nodes[i]); } cb && cb(); } } } /** * Check if a node is a DocumentFragment. * * @param {Node} node * @return {Boolean} */ function isFragment(node) { return node && node.nodeType === 11; } /** * Get outerHTML of elements, taking care * of SVG elements in IE as well. * * @param {Element} el * @return {String} */ function getOuterHTML(el) { if (el.outerHTML) { return el.outerHTML; } else { var container = document.createElement('div'); container.appendChild(el.cloneNode(true)); return container.innerHTML; } } var commonTagRE = /^(div|p|span|img|a|b|i|br|ul|ol|li|h1|h2|h3|h4|h5|h6|code|pre|table|th|td|tr|form|label|input|select|option|nav|article|section|header|footer)$/i; var reservedTagRE = /^(slot|partial|component)$/i; var isUnknownElement = undefined; if ('development' !== 'production') { isUnknownElement = function (el, tag) { if (tag.indexOf('-') > -1) { // path_to_url return el.constructor === window.HTMLUnknownElement || el.constructor === window.HTMLElement; } else { return (/HTMLUnknownElement/.test(el.toString()) && // Chrome returns unknown for several HTML5 elements. // path_to_url !/^(data|time|rtc|rb)$/.test(tag) ); } }; } /** * Check if an element is a component, if yes return its * component id. * * @param {Element} el * @param {Object} options * @return {Object|undefined} */ function checkComponentAttr(el, options) { var tag = el.tagName.toLowerCase(); var hasAttrs = el.hasAttributes(); if (!commonTagRE.test(tag) && !reservedTagRE.test(tag)) { if (resolveAsset(options, 'components', tag)) { return { id: tag }; } else { var is = hasAttrs && getIsBinding(el, options); if (is) { return is; } else if ('development' !== 'production') { var expectedTag = options._componentNameMap && options._componentNameMap[tag]; if (expectedTag) { warn('Unknown custom element: <' + tag + '> - ' + 'did you mean <' + expectedTag + '>? ' + 'HTML is case-insensitive, remember to use kebab-case in templates.'); } else if (isUnknownElement(el, tag)) { warn('Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.'); } } } } else if (hasAttrs) { return getIsBinding(el, options); } } /** * Get "is" binding from an element. * * @param {Element} el * @param {Object} options * @return {Object|undefined} */ function getIsBinding(el, options) { // dynamic syntax var exp = el.getAttribute('is'); if (exp != null) { if (resolveAsset(options, 'components', exp)) { el.removeAttribute('is'); return { id: exp }; } } else { exp = getBindAttr(el, 'is'); if (exp != null) { return { id: exp, dynamic: true }; } } } /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. * * All strategy functions follow the same signature: * * @param {*} parentVal * @param {*} childVal * @param {Vue} [vm] */ var strats = config.optionMergeStrategies = Object.create(null); /** * Helper that recursively merges two data objects together. */ function mergeData(to, from) { var key, toVal, fromVal; for (key in from) { toVal = to[key]; fromVal = from[key]; if (!hasOwn(to, key)) { set(to, key, fromVal); } else if (isObject(toVal) && isObject(fromVal)) { mergeData(toVal, fromVal); } } return to; } /** * Data */ strats.data = function (parentVal, childVal, vm) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal; } if (typeof childVal !== 'function') { 'development' !== 'production' && warn('The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm); return parentVal; } if (!parentVal) { return childVal; } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn() { return mergeData(childVal.call(this), parentVal.call(this)); }; } else if (parentVal || childVal) { return function mergedInstanceDataFn() { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm) : childVal; var defaultData = typeof parentVal === 'function' ? parentVal.call(vm) : undefined; if (instanceData) { return mergeData(instanceData, defaultData); } else { return defaultData; } }; } }; /** * El */ strats.el = function (parentVal, childVal, vm) { if (!vm && childVal && typeof childVal !== 'function') { 'development' !== 'production' && warn('The "el" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm); return; } var ret = childVal || parentVal; // invoke the element factory if this is instance merge return vm && typeof ret === 'function' ? ret.call(vm) : ret; }; /** * Hooks and param attributes are merged as arrays. */ strats.init = strats.created = strats.ready = strats.attached = strats.detached = strats.beforeCompile = strats.compiled = strats.beforeDestroy = strats.destroyed = strats.activate = function (parentVal, childVal) { return childVal ? parentVal ? parentVal.concat(childVal) : isArray(childVal) ? childVal : [childVal] : parentVal; }; /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets(parentVal, childVal) { var res = Object.create(parentVal || null); return childVal ? extend(res, guardArrayAssets(childVal)) : res; } config._assetTypes.forEach(function (type) { strats[type + 's'] = mergeAssets; }); /** * Events & Watchers. * * Events & watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = strats.events = function (parentVal, childVal) { if (!childVal) return parentVal; if (!parentVal) return childVal; var ret = {}; extend(ret, parentVal); for (var key in childVal) { var parent = ret[key]; var child = childVal[key]; if (parent && !isArray(parent)) { parent = [parent]; } ret[key] = parent ? parent.concat(child) : [child]; } return ret; }; /** * Other object hashes. */ strats.props = strats.methods = strats.computed = function (parentVal, childVal) { if (!childVal) return parentVal; if (!parentVal) return childVal; var ret = Object.create(null); extend(ret, parentVal); extend(ret, childVal); return ret; }; /** * Default strategy. */ var defaultStrat = function defaultStrat(parentVal, childVal) { return childVal === undefined ? parentVal : childVal; }; /** * Make sure component options get converted to actual * constructors. * * @param {Object} options */ function guardComponents(options) { if (options.components) { var components = options.components = guardArrayAssets(options.components); var ids = Object.keys(components); var def; if ('development' !== 'production') { var map = options._componentNameMap = {}; } for (var i = 0, l = ids.length; i < l; i++) { var key = ids[i]; if (commonTagRE.test(key) || reservedTagRE.test(key)) { 'development' !== 'production' && warn('Do not use built-in or reserved HTML elements as component ' + 'id: ' + key); continue; } // record a all lowercase <-> kebab-case mapping for // possible custom element case error warning if ('development' !== 'production') { map[key.replace(/-/g, '').toLowerCase()] = hyphenate(key); } def = components[key]; if (isPlainObject(def)) { components[key] = Vue.extend(def); } } } } /** * Ensure all props option syntax are normalized into the * Object-based format. * * @param {Object} options */ function guardProps(options) { var props = options.props; var i, val; if (isArray(props)) { options.props = {}; i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { options.props[val] = null; } else if (val.name) { options.props[val.name] = val; } } } else if (isPlainObject(props)) { var keys = Object.keys(props); i = keys.length; while (i--) { val = props[keys[i]]; if (typeof val === 'function') { props[keys[i]] = { type: val }; } } } } /** * Guard an Array-format assets option and converted it * into the key-value Object format. * * @param {Object|Array} assets * @return {Object} */ function guardArrayAssets(assets) { if (isArray(assets)) { var res = {}; var i = assets.length; var asset; while (i--) { asset = assets[i]; var id = typeof asset === 'function' ? asset.options && asset.options.name || asset.id : asset.name || asset.id; if (!id) { 'development' !== 'production' && warn('Array-syntax assets must provide a "name" or "id" field.'); } else { res[id] = asset; } } return res; } return assets; } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. * * @param {Object} parent * @param {Object} child * @param {Vue} [vm] - if vm is present, indicates this is * an instantiation merge. */ function mergeOptions(parent, child, vm) { guardComponents(child); guardProps(child); if ('development' !== 'production') { if (child.propsData && !vm) { warn('propsData can only be used as an instantiation option.'); } } var options = {}; var key; if (child['extends']) { parent = typeof child['extends'] === 'function' ? mergeOptions(parent, child['extends'].options, vm) : mergeOptions(parent, child['extends'], vm); } if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { parent = mergeOptions(parent, child.mixins[i], vm); } } for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField(key) { var strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options; } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. * * @param {Object} options * @param {String} type * @param {String} id * @param {Boolean} warnMissing * @return {Object|Function} */ function resolveAsset(options, type, id, warnMissing) { /* istanbul ignore if */ if (typeof id !== 'string') { return; } var assets = options[type]; var camelizedId; var res = assets[id] || // camelCase ID assets[camelizedId = camelize(id)] || // Pascal Case ID assets[camelizedId.charAt(0).toUpperCase() + camelizedId.slice(1)]; if ('development' !== 'production' && warnMissing && !res) { warn('Failed to resolve ' + type.slice(0, -1) + ': ' + id, options); } return res; } var uid$1 = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. * * @constructor */ function Dep() { this.id = uid$1++; this.subs = []; } // the current target watcher being evaluated. // this is globally unique because there could be only one // watcher being evaluated at any time. Dep.target = null; /** * Add a directive subscriber. * * @param {Directive} sub */ Dep.prototype.addSub = function (sub) { this.subs.push(sub); }; /** * Remove a directive subscriber. * * @param {Directive} sub */ Dep.prototype.removeSub = function (sub) { this.subs.$remove(sub); }; /** * Add self as a dependency to the target watcher. */ Dep.prototype.depend = function () { Dep.target.addDep(this); }; /** * Notify all subscribers of a new value. */ Dep.prototype.notify = function () { // stablize the subscriber list first var subs = toArray(this.subs); for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto) /** * Intercept mutating methods and emit events */ ;['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'].forEach(function (method) { // cache original method var original = arrayProto[method]; def(arrayMethods, method, function mutator() { // avoid leaking arguments: // path_to_url var i = arguments.length; var args = new Array(i); while (i--) { args[i] = arguments[i]; } var result = original.apply(this, args); var ob = this.__ob__; var inserted; switch (method) { case 'push': inserted = args; break; case 'unshift': inserted = args; break; case 'splice': inserted = args.slice(2); break; } if (inserted) ob.observeArray(inserted); // notify change ob.dep.notify(); return result; }); }); /** * Swap the element at the given index with a new value * and emits corresponding event. * * @param {Number} index * @param {*} val * @return {*} - replaced element */ def(arrayProto, '$set', function $set(index, val) { if (index >= this.length) { this.length = Number(index) + 1; } return this.splice(index, 1, val)[0]; }); /** * Convenience method to remove the element at given index or target element reference. * * @param {*} item */ def(arrayProto, '$remove', function $remove(item) { /* istanbul ignore if */ if (!this.length) return; var index = indexOf(this, item); if (index > -1) { return this.splice(index, 1); } }); var arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * By default, when a reactive property is set, the new value is * also converted to become reactive. However in certain cases, e.g. * v-for scope alias and props, we don't want to force conversion * because the value may be a nested value under a frozen data structure. * * So whenever we want to set a reactive property without forcing * conversion on the new value, we wrap that call inside this function. */ var shouldConvert = true; function withoutConversion(fn) { shouldConvert = false; fn(); shouldConvert = true; } /** * Observer class that are attached to each observed * object. Once attached, the observer converts target * object's property keys into getter/setters that * collect dependencies and dispatches updates. * * @param {Array|Object} value * @constructor */ function Observer(value) { this.value = value; this.dep = new Dep(); def(value, '__ob__', this); if (isArray(value)) { var augment = hasProto ? protoAugment : copyAugment; augment(value, arrayMethods, arrayKeys); this.observeArray(value); } else { this.walk(value); } } // Instance methods /** * Walk through each property and convert them into * getter/setters. This method should only be called when * value type is Object. * * @param {Object} obj */ Observer.prototype.walk = function (obj) { var keys = Object.keys(obj); for (var i = 0, l = keys.length; i < l; i++) { this.convert(keys[i], obj[keys[i]]); } }; /** * Observe a list of Array items. * * @param {Array} items */ Observer.prototype.observeArray = function (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; /** * Convert a property into getter/setter so we can emit * the events when the property is accessed/changed. * * @param {String} key * @param {*} val */ Observer.prototype.convert = function (key, val) { defineReactive(this.value, key, val); }; /** * Add an owner vm, so that when $set/$delete mutations * happen we can notify owner vms to proxy the keys and * digest the watchers. This is only called when the object * is observed as an instance's root $data. * * @param {Vue} vm */ Observer.prototype.addVm = function (vm) { (this.vms || (this.vms = [])).push(vm); }; /** * Remove an owner vm. This is called when the object is * swapped out as an instance's $data object. * * @param {Vue} vm */ Observer.prototype.removeVm = function (vm) { this.vms.$remove(vm); }; // helpers /** * Augment an target Object or Array by intercepting * the prototype chain using __proto__ * * @param {Object|Array} target * @param {Object} src */ function protoAugment(target, src) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ } /** * Augment an target Object or Array by defining * hidden properties. * * @param {Object|Array} target * @param {Object} proto */ function copyAugment(target, src, keys) { for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; def(target, key, src[key]); } } /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. * * @param {*} value * @param {Vue} [vm] * @return {Observer|undefined} * @static */ function observe(value, vm) { if (!value || typeof value !== 'object') { return; } var ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if (shouldConvert && (isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue) { ob = new Observer(value); } if (ob && vm) { ob.addVm(vm); } return ob; } /** * Define a reactive property on an Object. * * @param {Object} obj * @param {String} key * @param {*} val */ function defineReactive(obj, key, val) { var dep = new Dep(); var property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return; } // cater for pre-defined getter/setters var getter = property && property.get; var setter = property && property.set; var childOb = observe(val); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter() { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); } if (isArray(value)) { for (var e, i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); } } } return value; }, set: function reactiveSetter(newVal) { var value = getter ? getter.call(obj) : val; if (newVal === value) { return; } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = observe(newVal); dep.notify(); } }); } var util = Object.freeze({ defineReactive: defineReactive, set: set, del: del, hasOwn: hasOwn, isLiteral: isLiteral, isReserved: isReserved, _toString: _toString, toNumber: toNumber, toBoolean: toBoolean, stripQuotes: stripQuotes, camelize: camelize, hyphenate: hyphenate, classify: classify, bind: bind, toArray: toArray, extend: extend, isObject: isObject, isPlainObject: isPlainObject, def: def, debounce: _debounce, indexOf: indexOf, cancellable: cancellable, looseEqual: looseEqual, isArray: isArray, hasProto: hasProto, inBrowser: inBrowser, devtools: devtools, isIE9: isIE9, isAndroid: isAndroid, isIos: isIos, isWechat: isWechat, get transitionProp () { return transitionProp; }, get transitionEndEvent () { return transitionEndEvent; }, get animationProp () { return animationProp; }, get animationEndEvent () { return animationEndEvent; }, nextTick: nextTick, get _Set () { return _Set; }, query: query, inDoc: inDoc, getAttr: getAttr, getBindAttr: getBindAttr, hasBindAttr: hasBindAttr, before: before, after: after, remove: remove, prepend: prepend, replace: replace, on: on, off: off, setClass: setClass, addClass: addClass, removeClass: removeClass, extractContent: extractContent, trimNode: trimNode, isTemplate: isTemplate, createAnchor: createAnchor, findRef: findRef, mapNodeRange: mapNodeRange, removeNodeRange: removeNodeRange, isFragment: isFragment, getOuterHTML: getOuterHTML, mergeOptions: mergeOptions, resolveAsset: resolveAsset, checkComponentAttr: checkComponentAttr, commonTagRE: commonTagRE, reservedTagRE: reservedTagRE, get warn () { return warn; } }); var uid = 0; function initMixin (Vue) { /** * The main init sequence. This is called for every * instance, including ones that are created from extended * constructors. * * @param {Object} options - this options object should be * the result of merging class * options and the options passed * in to the constructor. */ Vue.prototype._init = function (options) { options = options || {}; this.$el = null; this.$parent = options.parent; this.$root = this.$parent ? this.$parent.$root : this; this.$children = []; this.$refs = {}; // child vm references this.$els = {}; // element references this._watchers = []; // all watchers as an array this._directives = []; // all directives // a uid this._uid = uid++; // a flag to avoid this being observed this._isVue = true; // events bookkeeping this._events = {}; // registered callbacks this._eventsCount = {}; // for $broadcast optimization // fragment instance properties this._isFragment = false; this._fragment = // @type {DocumentFragment} this._fragmentStart = // @type {Text|Comment} this._fragmentEnd = null; // @type {Text|Comment} // lifecycle state this._isCompiled = this._isDestroyed = this._isReady = this._isAttached = this._isBeingDestroyed = this._vForRemoving = false; this._unlinkFn = null; // context: // if this is a transcluded component, context // will be the common parent vm of this instance // and its host. this._context = options._context || this.$parent; // scope: // if this is inside an inline v-for, the scope // will be the intermediate scope created for this // repeat fragment. this is used for linking props // and container directives. this._scope = options._scope; // fragment: // if this instance is compiled inside a Fragment, it // needs to reigster itself as a child of that fragment // for attach/detach to work properly. this._frag = options._frag; if (this._frag) { this._frag.children.push(this); } // push self into parent / transclusion host if (this.$parent) { this.$parent.$children.push(this); } // merge options. options = this.$options = mergeOptions(this.constructor.options, options, this); // set ref this._updateRef(); // initialize data as empty object. // it will be filled up in _initData(). this._data = {}; // call init hook this._callHook('init'); // initialize data observation and scope inheritance. this._initState(); // setup event system and option events. this._initEvents(); // call created hook this._callHook('created'); // if `el` option is passed, start compilation. if (options.el) { this.$mount(options.el); } }; } var pathCache = new Cache(1000); // actions var APPEND = 0; var PUSH = 1; var INC_SUB_PATH_DEPTH = 2; var PUSH_SUB_PATH = 3; // states var BEFORE_PATH = 0; var IN_PATH = 1; var BEFORE_IDENT = 2; var IN_IDENT = 3; var IN_SUB_PATH = 4; var IN_SINGLE_QUOTE = 5; var IN_DOUBLE_QUOTE = 6; var AFTER_PATH = 7; var ERROR = 8; var pathStateMachine = []; pathStateMachine[BEFORE_PATH] = { 'ws': [BEFORE_PATH], 'ident': [IN_IDENT, APPEND], '[': [IN_SUB_PATH], 'eof': [AFTER_PATH] }; pathStateMachine[IN_PATH] = { 'ws': [IN_PATH], '.': [BEFORE_IDENT], '[': [IN_SUB_PATH], 'eof': [AFTER_PATH] }; pathStateMachine[BEFORE_IDENT] = { 'ws': [BEFORE_IDENT], 'ident': [IN_IDENT, APPEND] }; pathStateMachine[IN_IDENT] = { 'ident': [IN_IDENT, APPEND], '0': [IN_IDENT, APPEND], 'number': [IN_IDENT, APPEND], 'ws': [IN_PATH, PUSH], '.': [BEFORE_IDENT, PUSH], '[': [IN_SUB_PATH, PUSH], 'eof': [AFTER_PATH, PUSH] }; pathStateMachine[IN_SUB_PATH] = { "'": [IN_SINGLE_QUOTE, APPEND], '"': [IN_DOUBLE_QUOTE, APPEND], '[': [IN_SUB_PATH, INC_SUB_PATH_DEPTH], ']': [IN_PATH, PUSH_SUB_PATH], 'eof': ERROR, 'else': [IN_SUB_PATH, APPEND] }; pathStateMachine[IN_SINGLE_QUOTE] = { "'": [IN_SUB_PATH, APPEND], 'eof': ERROR, 'else': [IN_SINGLE_QUOTE, APPEND] }; pathStateMachine[IN_DOUBLE_QUOTE] = { '"': [IN_SUB_PATH, APPEND], 'eof': ERROR, 'else': [IN_DOUBLE_QUOTE, APPEND] }; /** * Determine the type of a character in a keypath. * * @param {Char} ch * @return {String} type */ function getPathCharType(ch) { if (ch === undefined) { return 'eof'; } var code = ch.charCodeAt(0); switch (code) { case 0x5B: // [ case 0x5D: // ] case 0x2E: // . case 0x22: // " case 0x27: // ' case 0x30: // 0 return ch; case 0x5F: // _ case 0x24: // $ return 'ident'; case 0x20: // Space case 0x09: // Tab case 0x0A: // Newline case 0x0D: // Return case 0xA0: // No-break space case 0xFEFF: // Byte Order Mark case 0x2028: // Line Separator case 0x2029: // Paragraph Separator return 'ws'; } // a-z, A-Z if (code >= 0x61 && code <= 0x7A || code >= 0x41 && code <= 0x5A) { return 'ident'; } // 1-9 if (code >= 0x31 && code <= 0x39) { return 'number'; } return 'else'; } /** * Format a subPath, return its plain form if it is * a literal string or number. Otherwise prepend the * dynamic indicator (*). * * @param {String} path * @return {String} */ function formatSubPath(path) { var trimmed = path.trim(); // invalid leading 0 if (path.charAt(0) === '0' && isNaN(path)) { return false; } return isLiteral(trimmed) ? stripQuotes(trimmed) : '*' + trimmed; } /** * Parse a string path into an array of segments * * @param {String} path * @return {Array|undefined} */ function parse(path) { var keys = []; var index = -1; var mode = BEFORE_PATH; var subPathDepth = 0; var c, newChar, key, type, transition, action, typeMap; var actions = []; actions[PUSH] = function () { if (key !== undefined) { keys.push(key); key = undefined; } }; actions[APPEND] = function () { if (key === undefined) { key = newChar; } else { key += newChar; } }; actions[INC_SUB_PATH_DEPTH] = function () { actions[APPEND](); subPathDepth++; }; actions[PUSH_SUB_PATH] = function () { if (subPathDepth > 0) { subPathDepth--; mode = IN_SUB_PATH; actions[APPEND](); } else { subPathDepth = 0; key = formatSubPath(key); if (key === false) { return false; } else { actions[PUSH](); } } }; function maybeUnescapeQuote() { var nextChar = path[index + 1]; if (mode === IN_SINGLE_QUOTE && nextChar === "'" || mode === IN_DOUBLE_QUOTE && nextChar === '"') { index++; newChar = '\\' + nextChar; actions[APPEND](); return true; } } while (mode != null) { index++; c = path[index]; if (c === '\\' && maybeUnescapeQuote()) { continue; } type = getPathCharType(c); typeMap = pathStateMachine[mode]; transition = typeMap[type] || typeMap['else'] || ERROR; if (transition === ERROR) { return; // parse error } mode = transition[0]; action = actions[transition[1]]; if (action) { newChar = transition[2]; newChar = newChar === undefined ? c : newChar; if (action() === false) { return; } } if (mode === AFTER_PATH) { keys.raw = path; return keys; } } } /** * External parse that check for a cache hit first * * @param {String} path * @return {Array|undefined} */ function parsePath(path) { var hit = pathCache.get(path); if (!hit) { hit = parse(path); if (hit) { pathCache.put(path, hit); } } return hit; } /** * Get from an object from a path string * * @param {Object} obj * @param {String} path */ function getPath(obj, path) { return parseExpression(path).get(obj); } /** * Warn against setting non-existent root path on a vm. */ var warnNonExistent; if ('development' !== 'production') { warnNonExistent = function (path, vm) { warn('You are setting a non-existent path "' + path.raw + '" ' + 'on a vm instance. Consider pre-initializing the property ' + 'with the "data" option for more reliable reactivity ' + 'and better performance.', vm); }; } /** * Set on an object from a path * * @param {Object} obj * @param {String | Array} path * @param {*} val */ function setPath(obj, path, val) { var original = obj; if (typeof path === 'string') { path = parse(path); } if (!path || !isObject(obj)) { return false; } var last, key; for (var i = 0, l = path.length; i < l; i++) { last = obj; key = path[i]; if (key.charAt(0) === '*') { key = parseExpression(key.slice(1)).get.call(original, original); } if (i < l - 1) { obj = obj[key]; if (!isObject(obj)) { obj = {}; if ('development' !== 'production' && last._isVue) { warnNonExistent(path, last); } set(last, key, obj); } } else { if (isArray(obj)) { obj.$set(key, val); } else if (key in obj) { obj[key] = val; } else { if ('development' !== 'production' && obj._isVue) { warnNonExistent(path, obj); } set(obj, key, val); } } } return true; } var path = Object.freeze({ parsePath: parsePath, getPath: getPath, setPath: setPath }); var expressionCache = new Cache(1000); var allowedKeywords = 'Math,Date,this,true,false,null,undefined,Infinity,NaN,' + 'isNaN,isFinite,decodeURI,decodeURIComponent,encodeURI,' + 'encodeURIComponent,parseInt,parseFloat'; var allowedKeywordsRE = new RegExp('^(' + allowedKeywords.replace(/,/g, '\\b|') + '\\b)'); // keywords that don't make sense inside expressions var improperKeywords = 'break,case,class,catch,const,continue,debugger,default,' + 'delete,do,else,export,extends,finally,for,function,if,' + 'import,in,instanceof,let,return,super,switch,throw,try,' + 'var,while,with,yield,enum,await,implements,package,' + 'protected,static,interface,private,public'; var improperKeywordsRE = new RegExp('^(' + improperKeywords.replace(/,/g, '\\b|') + '\\b)'); var wsRE = /\s/g; var newlineRE = /\n/g; var saveRE = /[\{,]\s*[\w\$_]+\s*:|('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`)|new |typeof |void /g; var restoreRE = /"(\d+)"/g; var pathTestRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?'\]|\[".*?"\]|\[\d+\]|\[[A-Za-z_$][\w$]*\])*$/; var identRE = /[^\w$\.](?:[A-Za-z_$][\w$]*)/g; var booleanLiteralRE = /^(?:true|false)$/; /** * Save / Rewrite / Restore * * When rewriting paths found in an expression, it is * possible for the same letter sequences to be found in * strings and Object literal property keys. Therefore we * remove and store these parts in a temporary array, and * restore them after the path rewrite. */ var saved = []; /** * Save replacer * * The save regex can match two possible cases: * 1. An opening object literal * 2. A string * If matched as a plain string, we need to escape its * newlines, since the string needs to be preserved when * generating the function body. * * @param {String} str * @param {String} isString - str if matched as a string * @return {String} - placeholder with index */ function save(str, isString) { var i = saved.length; saved[i] = isString ? str.replace(newlineRE, '\\n') : str; return '"' + i + '"'; } /** * Path rewrite replacer * * @param {String} raw * @return {String} */ function rewrite(raw) { var c = raw.charAt(0); var path = raw.slice(1); if (allowedKeywordsRE.test(path)) { return raw; } else { path = path.indexOf('"') > -1 ? path.replace(restoreRE, restore) : path; return c + 'scope.' + path; } } /** * Restore replacer * * @param {String} str * @param {String} i - matched save index * @return {String} */ function restore(str, i) { return saved[i]; } /** * Rewrite an expression, prefixing all path accessors with * `scope.` and generate getter/setter functions. * * @param {String} exp * @return {Function} */ function compileGetter(exp) { if (improperKeywordsRE.test(exp)) { 'development' !== 'production' && warn('Avoid using reserved keywords in expression: ' + exp); } // reset state saved.length = 0; // save strings and object literal keys var body = exp.replace(saveRE, save).replace(wsRE, ''); // rewrite all paths // pad 1 space here becaue the regex matches 1 extra char body = (' ' + body).replace(identRE, rewrite).replace(restoreRE, restore); return makeGetterFn(body); } /** * Build a getter function. Requires eval. * * We isolate the try/catch so it doesn't affect the * optimization of the parse function when it is not called. * * @param {String} body * @return {Function|undefined} */ function makeGetterFn(body) { try { /* eslint-disable no-new-func */ return new Function('scope', 'return ' + body + ';'); /* eslint-enable no-new-func */ } catch (e) { 'development' !== 'production' && warn('Invalid expression. ' + 'Generated function body: ' + body); } } /** * Compile a setter function for the expression. * * @param {String} exp * @return {Function|undefined} */ function compileSetter(exp) { var path = parsePath(exp); if (path) { return function (scope, val) { setPath(scope, path, val); }; } else { 'development' !== 'production' && warn('Invalid setter expression: ' + exp); } } /** * Parse an expression into re-written getter/setters. * * @param {String} exp * @param {Boolean} needSet * @return {Function} */ function parseExpression(exp, needSet) { exp = exp.trim(); // try cache var hit = expressionCache.get(exp); if (hit) { if (needSet && !hit.set) { hit.set = compileSetter(hit.exp); } return hit; } var res = { exp: exp }; res.get = isSimplePath(exp) && exp.indexOf('[') < 0 // optimized super simple getter ? makeGetterFn('scope.' + exp) // dynamic getter : compileGetter(exp); if (needSet) { res.set = compileSetter(exp); } expressionCache.put(exp, res); return res; } /** * Check if an expression is a simple path. * * @param {String} exp * @return {Boolean} */ function isSimplePath(exp) { return pathTestRE.test(exp) && // don't treat true/false as paths !booleanLiteralRE.test(exp) && // Math constants e.g. Math.PI, Math.E etc. exp.slice(0, 5) !== 'Math.'; } var expression = Object.freeze({ parseExpression: parseExpression, isSimplePath: isSimplePath }); // we have two separate queues: one for directive updates // and one for user watcher registered via $watch(). // we want to guarantee directive updates to be called // before user watchers so that when user watchers are // triggered, the DOM would have already been in updated // state. var queue = []; var userQueue = []; var has = {}; var circular = {}; var waiting = false; /** * Reset the batcher's state. */ function resetBatcherState() { queue.length = 0; userQueue.length = 0; has = {}; circular = {}; waiting = false; } /** * Flush both queues and run the watchers. */ function flushBatcherQueue() { var _again = true; _function: while (_again) { _again = false; runBatcherQueue(queue); runBatcherQueue(userQueue); // user watchers triggered more watchers, // keep flushing until it depletes if (queue.length) { _again = true; continue _function; } // dev tool hook /* istanbul ignore if */ if (devtools && config.devtools) { devtools.emit('flush'); } resetBatcherState(); } } /** * Run the watchers in a single queue. * * @param {Array} queue */ function runBatcherQueue(queue) { // do not cache length because more watchers might be pushed // as we run existing watchers for (var i = 0; i < queue.length; i++) { var watcher = queue[i]; var id = watcher.id; has[id] = null; watcher.run(); // in dev build, check and stop circular updates. if ('development' !== 'production' && has[id] != null) { circular[id] = (circular[id] || 0) + 1; if (circular[id] > config._maxUpdateCount) { warn('You may have an infinite update loop for watcher ' + 'with expression "' + watcher.expression + '"', watcher.vm); break; } } } queue.length = 0; } /** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. * * @param {Watcher} watcher * properties: * - {Number} id * - {Function} run */ function pushWatcher(watcher) { var id = watcher.id; if (has[id] == null) { // push watcher into appropriate queue var q = watcher.user ? userQueue : queue; has[id] = q.length; q.push(watcher); // queue the flush if (!waiting) { waiting = true; nextTick(flushBatcherQueue); } } } var uid$2 = 0; /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. * * @param {Vue} vm * @param {String|Function} expOrFn * @param {Function} cb * @param {Object} options * - {Array} filters * - {Boolean} twoWay * - {Boolean} deep * - {Boolean} user * - {Boolean} sync * - {Boolean} lazy * - {Function} [preProcess] * - {Function} [postProcess] * @constructor */ function Watcher(vm, expOrFn, cb, options) { // mix in options if (options) { extend(this, options); } var isFn = typeof expOrFn === 'function'; this.vm = vm; vm._watchers.push(this); this.expression = expOrFn; this.cb = cb; this.id = ++uid$2; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; this.newDeps = []; this.depIds = new _Set(); this.newDepIds = new _Set(); this.prevError = null; // for async error stacks // parse expression for getter/setter if (isFn) { this.getter = expOrFn; this.setter = undefined; } else { var res = parseExpression(expOrFn, this.twoWay); this.getter = res.get; this.setter = res.set; } this.value = this.lazy ? undefined : this.get(); // state for avoiding false triggers for deep and Array // watchers during vm._digest() this.queued = this.shallow = false; } /** * Evaluate the getter, and re-collect dependencies. */ Watcher.prototype.get = function () { this.beforeGet(); var scope = this.scope || this.vm; var value; try { value = this.getter.call(scope, scope); } catch (e) { if ('development' !== 'production' && config.warnExpressionErrors) { warn('Error when evaluating expression ' + '"' + this.expression + '": ' + e.toString(), this.vm); } } // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } if (this.preProcess) { value = this.preProcess(value); } if (this.filters) { value = scope._applyFilters(value, null, this.filters, false); } if (this.postProcess) { value = this.postProcess(value); } this.afterGet(); return value; }; /** * Set the corresponding value with the setter. * * @param {*} value */ Watcher.prototype.set = function (value) { var scope = this.scope || this.vm; if (this.filters) { value = scope._applyFilters(value, this.value, this.filters, true); } try { this.setter.call(scope, scope, value); } catch (e) { if ('development' !== 'production' && config.warnExpressionErrors) { warn('Error when evaluating setter ' + '"' + this.expression + '": ' + e.toString(), this.vm); } } // two-way sync for v-for alias var forContext = scope.$forContext; if (forContext && forContext.alias === this.expression) { if (forContext.filters) { 'development' !== 'production' && warn('It seems you are using two-way binding on ' + 'a v-for alias (' + this.expression + '), and the ' + 'v-for has filters. This will not work properly. ' + 'Either remove the filters or use an array of ' + 'objects and bind to object properties instead.', this.vm); return; } forContext._withLock(function () { if (scope.$key) { // original is an object forContext.rawValue[scope.$key] = value; } else { forContext.rawValue.$set(scope.$index, value); } }); } }; /** * Prepare for dependency collection. */ Watcher.prototype.beforeGet = function () { Dep.target = this; }; /** * Add a dependency to this directive. * * @param {Dep} dep */ Watcher.prototype.addDep = function (dep) { var id = dep.id; if (!this.newDepIds.has(id)) { this.newDepIds.add(id); this.newDeps.push(dep); if (!this.depIds.has(id)) { dep.addSub(this); } } }; /** * Clean up for dependency collection. */ Watcher.prototype.afterGet = function () { Dep.target = null; var i = this.deps.length; while (i--) { var dep = this.deps[i]; if (!this.newDepIds.has(dep.id)) { dep.removeSub(this); } } var tmp = this.depIds; this.depIds = this.newDepIds; this.newDepIds = tmp; this.newDepIds.clear(); tmp = this.deps; this.deps = this.newDeps; this.newDeps = tmp; this.newDeps.length = 0; }; /** * Subscriber interface. * Will be called when a dependency changes. * * @param {Boolean} shallow */ Watcher.prototype.update = function (shallow) { if (this.lazy) { this.dirty = true; } else if (this.sync || !config.async) { this.run(); } else { // if queued, only overwrite shallow with non-shallow, // but not the other way around. this.shallow = this.queued ? shallow ? this.shallow : false : !!shallow; this.queued = true; // record before-push error stack in debug mode /* istanbul ignore if */ if ('development' !== 'production' && config.debug) { this.prevError = new Error('[vue] async stack trace'); } pushWatcher(this); } }; /** * Batcher job interface. * Will be called by the batcher. */ Watcher.prototype.run = function () { if (this.active) { var value = this.get(); if (value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated; but only do so if this is a // non-shallow update (caused by a vm digest). (isObject(value) || this.deep) && !this.shallow) { // set new value var oldValue = this.value; this.value = value; // in debug + async mode, when a watcher callbacks // throws, we also throw the saved before-push error // so the full cross-tick stack trace is available. var prevError = this.prevError; /* istanbul ignore if */ if ('development' !== 'production' && config.debug && prevError) { this.prevError = null; try { this.cb.call(this.vm, value, oldValue); } catch (e) { nextTick(function () { throw prevError; }, 0); throw e; } } else { this.cb.call(this.vm, value, oldValue); } } this.queued = this.shallow = false; } }; /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ Watcher.prototype.evaluate = function () { // avoid overwriting another watcher that is being // collected. var current = Dep.target; this.value = this.get(); this.dirty = false; Dep.target = current; }; /** * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function () { var i = this.deps.length; while (i--) { this.deps[i].depend(); } }; /** * Remove self from all dependencies' subcriber list. */ Watcher.prototype.teardown = function () { if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed or is performing a v-for // re-render (the watcher list is then filtered by v-for). if (!this.vm._isBeingDestroyed && !this.vm._vForRemoving) { this.vm._watchers.$remove(this); } var i = this.deps.length; while (i--) { this.deps[i].removeSub(this); } this.active = false; this.vm = this.cb = this.value = null; } }; /** * Recrusively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. * * @param {*} val */ var seenObjects = new _Set(); function traverse(val, seen) { var i = undefined, keys = undefined; if (!seen) { seen = seenObjects; seen.clear(); } var isA = isArray(val); var isO = isObject(val); if (isA || isO) { if (val.__ob__) { var depId = val.__ob__.dep.id; if (seen.has(depId)) { return; } else { seen.add(depId); } } if (isA) { i = val.length; while (i--) traverse(val[i], seen); } else if (isO) { keys = Object.keys(val); i = keys.length; while (i--) traverse(val[keys[i]], seen); } } } var text$1 = { bind: function bind() { this.attr = this.el.nodeType === 3 ? 'data' : 'textContent'; }, update: function update(value) { this.el[this.attr] = _toString(value); } }; var templateCache = new Cache(1000); var idSelectorCache = new Cache(1000); var map = { efault: [0, '', ''], legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'] }; map.td = map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>']; map.option = map.optgroup = [1, '<select multiple="multiple">', '</select>']; map.thead = map.tbody = map.colgroup = map.caption = map.tfoot = [1, '<table>', '</table>']; map.g = map.defs = map.symbol = map.use = map.image = map.text = map.circle = map.ellipse = map.line = map.path = map.polygon = map.polyline = map.rect = [1, '<svg ' + 'xmlns="path_to_url" ' + 'xmlns:xlink="path_to_url" ' + 'xmlns:ev="path_to_url"' + 'version="1.1">', '</svg>']; /** * Check if a node is a supported template node with a * DocumentFragment content. * * @param {Node} node * @return {Boolean} */ function isRealTemplate(node) { return isTemplate(node) && isFragment(node.content); } var tagRE$1 = /<([\w:-]+)/; var entityRE = /&#?\w+?;/; /** * Convert a string template to a DocumentFragment. * Determines correct wrapping by tag types. Wrapping * strategy found in jQuery & component/domify. * * @param {String} templateString * @param {Boolean} raw * @return {DocumentFragment} */ function stringToFragment(templateString, raw) { // try a cache hit first var cacheKey = raw ? templateString : templateString.trim(); var hit = templateCache.get(cacheKey); if (hit) { return hit; } var frag = document.createDocumentFragment(); var tagMatch = templateString.match(tagRE$1); var entityMatch = entityRE.test(templateString); if (!tagMatch && !entityMatch) { // text only, return a single text node. frag.appendChild(document.createTextNode(templateString)); } else { var tag = tagMatch && tagMatch[1]; var wrap = map[tag] || map.efault; var depth = wrap[0]; var prefix = wrap[1]; var suffix = wrap[2]; var node = document.createElement('div'); node.innerHTML = prefix + templateString + suffix; while (depth--) { node = node.lastChild; } var child; /* eslint-disable no-cond-assign */ while (child = node.firstChild) { /* eslint-enable no-cond-assign */ frag.appendChild(child); } } if (!raw) { trimNode(frag); } templateCache.put(cacheKey, frag); return frag; } /** * Convert a template node to a DocumentFragment. * * @param {Node} node * @return {DocumentFragment} */ function nodeToFragment(node) { // if its a template tag and the browser supports it, // its content is already a document fragment. However, iOS Safari has // bug when using directly cloned template content with touch // events and can cause crashes when the nodes are removed from DOM, so we // have to treat template elements as string templates. (#2805) /* istanbul ignore if */ if (isRealTemplate(node)) { return stringToFragment(node.innerHTML); } // script template if (node.tagName === 'SCRIPT') { return stringToFragment(node.textContent); } // normal node, clone it to avoid mutating the original var clonedNode = cloneNode(node); var frag = document.createDocumentFragment(); var child; /* eslint-disable no-cond-assign */ while (child = clonedNode.firstChild) { /* eslint-enable no-cond-assign */ frag.appendChild(child); } trimNode(frag); return frag; } // Test for the presence of the Safari template cloning bug // path_to_url var hasBrokenTemplate = (function () { /* istanbul ignore else */ if (inBrowser) { var a = document.createElement('div'); a.innerHTML = '<template>1</template>'; return !a.cloneNode(true).firstChild.innerHTML; } else { return false; } })(); // Test for IE10/11 textarea placeholder clone bug var hasTextareaCloneBug = (function () { /* istanbul ignore else */ if (inBrowser) { var t = document.createElement('textarea'); t.placeholder = 't'; return t.cloneNode(true).value === 't'; } else { return false; } })(); /** * 1. Deal with Safari cloning nested <template> bug by * manually cloning all template instances. * 2. Deal with IE10/11 textarea placeholder bug by setting * the correct value after cloning. * * @param {Element|DocumentFragment} node * @return {Element|DocumentFragment} */ function cloneNode(node) { /* istanbul ignore if */ if (!node.querySelectorAll) { return node.cloneNode(); } var res = node.cloneNode(true); var i, original, cloned; /* istanbul ignore if */ if (hasBrokenTemplate) { var tempClone = res; if (isRealTemplate(node)) { node = node.content; tempClone = res.content; } original = node.querySelectorAll('template'); if (original.length) { cloned = tempClone.querySelectorAll('template'); i = cloned.length; while (i--) { cloned[i].parentNode.replaceChild(cloneNode(original[i]), cloned[i]); } } } /* istanbul ignore if */ if (hasTextareaCloneBug) { if (node.tagName === 'TEXTAREA') { res.value = node.value; } else { original = node.querySelectorAll('textarea'); if (original.length) { cloned = res.querySelectorAll('textarea'); i = cloned.length; while (i--) { cloned[i].value = original[i].value; } } } } return res; } /** * Process the template option and normalizes it into a * a DocumentFragment that can be used as a partial or a * instance template. * * @param {*} template * Possible values include: * - DocumentFragment object * - Node object of type Template * - id selector: '#some-template-id' * - template string: '<div><span>{{msg}}</span></div>' * @param {Boolean} shouldClone * @param {Boolean} raw * inline HTML interpolation. Do not check for id * selector and keep whitespace in the string. * @return {DocumentFragment|undefined} */ function parseTemplate(template, shouldClone, raw) { var node, frag; // if the template is already a document fragment, // do nothing if (isFragment(template)) { trimNode(template); return shouldClone ? cloneNode(template) : template; } if (typeof template === 'string') { // id selector if (!raw && template.charAt(0) === '#') { // id selector can be cached too frag = idSelectorCache.get(template); if (!frag) { node = document.getElementById(template.slice(1)); if (node) { frag = nodeToFragment(node); // save selector to cache idSelectorCache.put(template, frag); } } } else { // normal string template frag = stringToFragment(template, raw); } } else if (template.nodeType) { // a direct node frag = nodeToFragment(template); } return frag && shouldClone ? cloneNode(frag) : frag; } var template = Object.freeze({ cloneNode: cloneNode, parseTemplate: parseTemplate }); var html = { bind: function bind() { // a comment node means this is a binding for // {{{ inline unescaped html }}} if (this.el.nodeType === 8) { // hold nodes this.nodes = []; // replace the placeholder with proper anchor this.anchor = createAnchor('v-html'); replace(this.el, this.anchor); } }, update: function update(value) { value = _toString(value); if (this.nodes) { this.swap(value); } else { this.el.innerHTML = value; } }, swap: function swap(value) { // remove old nodes var i = this.nodes.length; while (i--) { remove(this.nodes[i]); } // convert new value to a fragment // do not attempt to retrieve from id selector var frag = parseTemplate(value, true, true); // save a reference to these nodes so we can remove later this.nodes = toArray(frag.childNodes); before(frag, this.anchor); } }; /** * Abstraction for a partially-compiled fragment. * Can optionally compile content with a child scope. * * @param {Function} linker * @param {Vue} vm * @param {DocumentFragment} frag * @param {Vue} [host] * @param {Object} [scope] * @param {Fragment} [parentFrag] */ function Fragment(linker, vm, frag, host, scope, parentFrag) { this.children = []; this.childFrags = []; this.vm = vm; this.scope = scope; this.inserted = false; this.parentFrag = parentFrag; if (parentFrag) { parentFrag.childFrags.push(this); } this.unlink = linker(vm, frag, host, scope, this); var single = this.single = frag.childNodes.length === 1 && // do not go single mode if the only node is an anchor !frag.childNodes[0].__v_anchor; if (single) { this.node = frag.childNodes[0]; this.before = singleBefore; this.remove = singleRemove; } else { this.node = createAnchor('fragment-start'); this.end = createAnchor('fragment-end'); this.frag = frag; prepend(this.node, frag); frag.appendChild(this.end); this.before = multiBefore; this.remove = multiRemove; } this.node.__v_frag = this; } /** * Call attach/detach for all components contained within * this fragment. Also do so recursively for all child * fragments. * * @param {Function} hook */ Fragment.prototype.callHook = function (hook) { var i, l; for (i = 0, l = this.childFrags.length; i < l; i++) { this.childFrags[i].callHook(hook); } for (i = 0, l = this.children.length; i < l; i++) { hook(this.children[i]); } }; /** * Insert fragment before target, single node version * * @param {Node} target * @param {Boolean} withTransition */ function singleBefore(target, withTransition) { this.inserted = true; var method = withTransition !== false ? beforeWithTransition : before; method(this.node, target, this.vm); if (inDoc(this.node)) { this.callHook(attach); } } /** * Remove fragment, single node version */ function singleRemove() { this.inserted = false; var shouldCallRemove = inDoc(this.node); var self = this; this.beforeRemove(); removeWithTransition(this.node, this.vm, function () { if (shouldCallRemove) { self.callHook(detach); } self.destroy(); }); } /** * Insert fragment before target, multi-nodes version * * @param {Node} target * @param {Boolean} withTransition */ function multiBefore(target, withTransition) { this.inserted = true; var vm = this.vm; var method = withTransition !== false ? beforeWithTransition : before; mapNodeRange(this.node, this.end, function (node) { method(node, target, vm); }); if (inDoc(this.node)) { this.callHook(attach); } } /** * Remove fragment, multi-nodes version */ function multiRemove() { this.inserted = false; var self = this; var shouldCallRemove = inDoc(this.node); this.beforeRemove(); removeNodeRange(this.node, this.end, this.vm, this.frag, function () { if (shouldCallRemove) { self.callHook(detach); } self.destroy(); }); } /** * Prepare the fragment for removal. */ Fragment.prototype.beforeRemove = function () { var i, l; for (i = 0, l = this.childFrags.length; i < l; i++) { // call the same method recursively on child // fragments, depth-first this.childFrags[i].beforeRemove(false); } for (i = 0, l = this.children.length; i < l; i++) { // Call destroy for all contained instances, // with remove:false and defer:true. // Defer is necessary because we need to // keep the children to call detach hooks // on them. this.children[i].$destroy(false, true); } var dirs = this.unlink.dirs; for (i = 0, l = dirs.length; i < l; i++) { // disable the watchers on all the directives // so that the rendered content stays the same // during removal. dirs[i]._watcher && dirs[i]._watcher.teardown(); } }; /** * Destroy the fragment. */ Fragment.prototype.destroy = function () { if (this.parentFrag) { this.parentFrag.childFrags.$remove(this); } this.node.__v_frag = null; this.unlink(); }; /** * Call attach hook for a Vue instance. * * @param {Vue} child */ function attach(child) { if (!child._isAttached && inDoc(child.$el)) { child._callHook('attached'); } } /** * Call detach hook for a Vue instance. * * @param {Vue} child */ function detach(child) { if (child._isAttached && !inDoc(child.$el)) { child._callHook('detached'); } } var linkerCache = new Cache(5000); /** * A factory that can be used to create instances of a * fragment. Caches the compiled linker if possible. * * @param {Vue} vm * @param {Element|String} el */ function FragmentFactory(vm, el) { this.vm = vm; var template; var isString = typeof el === 'string'; if (isString || isTemplate(el) && !el.hasAttribute('v-if')) { template = parseTemplate(el, true); } else { template = document.createDocumentFragment(); template.appendChild(el); } this.template = template; // linker can be cached, but only for components var linker; var cid = vm.constructor.cid; if (cid > 0) { var cacheId = cid + (isString ? el : getOuterHTML(el)); linker = linkerCache.get(cacheId); if (!linker) { linker = compile(template, vm.$options, true); linkerCache.put(cacheId, linker); } } else { linker = compile(template, vm.$options, true); } this.linker = linker; } /** * Create a fragment instance with given host and scope. * * @param {Vue} host * @param {Object} scope * @param {Fragment} parentFrag */ FragmentFactory.prototype.create = function (host, scope, parentFrag) { var frag = cloneNode(this.template); return new Fragment(this.linker, this.vm, frag, host, scope, parentFrag); }; var ON = 700; var MODEL = 800; var BIND = 850; var TRANSITION = 1100; var EL = 1500; var COMPONENT = 1500; var PARTIAL = 1750; var IF = 2100; var FOR = 2200; var SLOT = 2300; var uid$3 = 0; var vFor = { priority: FOR, terminal: true, params: ['track-by', 'stagger', 'enter-stagger', 'leave-stagger'], bind: function bind() { // support "item in/of items" syntax var inMatch = this.expression.match(/(.*) (?:in|of) (.*)/); if (inMatch) { var itMatch = inMatch[1].match(/\((.*),(.*)\)/); if (itMatch) { this.iterator = itMatch[1].trim(); this.alias = itMatch[2].trim(); } else { this.alias = inMatch[1].trim(); } this.expression = inMatch[2]; } if (!this.alias) { 'development' !== 'production' && warn('Invalid v-for expression "' + this.descriptor.raw + '": ' + 'alias is required.', this.vm); return; } // uid as a cache identifier this.id = '__v-for__' + ++uid$3; // check if this is an option list, // so that we know if we need to update the <select>'s // v-model when the option list has changed. // because v-model has a lower priority than v-for, // the v-model is not bound here yet, so we have to // retrive it in the actual updateModel() function. var tag = this.el.tagName; this.isOption = (tag === 'OPTION' || tag === 'OPTGROUP') && this.el.parentNode.tagName === 'SELECT'; // setup anchor nodes this.start = createAnchor('v-for-start'); this.end = createAnchor('v-for-end'); replace(this.el, this.end); before(this.start, this.end); // cache this.cache = Object.create(null); // fragment factory this.factory = new FragmentFactory(this.vm, this.el); }, update: function update(data) { this.diff(data); this.updateRef(); this.updateModel(); }, /** * Diff, based on new data and old data, determine the * minimum amount of DOM manipulations needed to make the * DOM reflect the new data Array. * * The algorithm diffs the new data Array by storing a * hidden reference to an owner vm instance on previously * seen data. This allows us to achieve O(n) which is * better than a levenshtein distance based algorithm, * which is O(m * n). * * @param {Array} data */ diff: function diff(data) { // check if the Array was converted from an Object var item = data[0]; var convertedFromObject = this.fromObject = isObject(item) && hasOwn(item, '$key') && hasOwn(item, '$value'); var trackByKey = this.params.trackBy; var oldFrags = this.frags; var frags = this.frags = new Array(data.length); var alias = this.alias; var iterator = this.iterator; var start = this.start; var end = this.end; var inDocument = inDoc(start); var init = !oldFrags; var i, l, frag, key, value, primitive; // First pass, go through the new Array and fill up // the new frags array. If a piece of data has a cached // instance for it, we reuse it. Otherwise build a new // instance. for (i = 0, l = data.length; i < l; i++) { item = data[i]; key = convertedFromObject ? item.$key : null; value = convertedFromObject ? item.$value : item; primitive = !isObject(value); frag = !init && this.getCachedFrag(value, i, key); if (frag) { // reusable fragment frag.reused = true; // update $index frag.scope.$index = i; // update $key if (key) { frag.scope.$key = key; } // update iterator if (iterator) { frag.scope[iterator] = key !== null ? key : i; } // update data for track-by, object repeat & // primitive values. if (trackByKey || convertedFromObject || primitive) { withoutConversion(function () { frag.scope[alias] = value; }); } } else { // new isntance frag = this.create(value, alias, i, key); frag.fresh = !init; } frags[i] = frag; if (init) { frag.before(end); } } // we're done for the initial render. if (init) { return; } // Second pass, go through the old fragments and // destroy those who are not reused (and remove them // from cache) var removalIndex = 0; var totalRemoved = oldFrags.length - frags.length; // when removing a large number of fragments, watcher removal // turns out to be a perf bottleneck, so we batch the watcher // removals into a single filter call! this.vm._vForRemoving = true; for (i = 0, l = oldFrags.length; i < l; i++) { frag = oldFrags[i]; if (!frag.reused) { this.deleteCachedFrag(frag); this.remove(frag, removalIndex++, totalRemoved, inDocument); } } this.vm._vForRemoving = false; if (removalIndex) { this.vm._watchers = this.vm._watchers.filter(function (w) { return w.active; }); } // Final pass, move/insert new fragments into the // right place. var targetPrev, prevEl, currentPrev; var insertionIndex = 0; for (i = 0, l = frags.length; i < l; i++) { frag = frags[i]; // this is the frag that we should be after targetPrev = frags[i - 1]; prevEl = targetPrev ? targetPrev.staggerCb ? targetPrev.staggerAnchor : targetPrev.end || targetPrev.node : start; if (frag.reused && !frag.staggerCb) { currentPrev = findPrevFrag(frag, start, this.id); if (currentPrev !== targetPrev && (!currentPrev || // optimization for moving a single item. // thanks to suggestions by @livoras in #1807 findPrevFrag(currentPrev, start, this.id) !== targetPrev)) { this.move(frag, prevEl); } } else { // new instance, or still in stagger. // insert with updated stagger index. this.insert(frag, insertionIndex++, prevEl, inDocument); } frag.reused = frag.fresh = false; } }, /** * Create a new fragment instance. * * @param {*} value * @param {String} alias * @param {Number} index * @param {String} [key] * @return {Fragment} */ create: function create(value, alias, index, key) { var host = this._host; // create iteration scope var parentScope = this._scope || this.vm; var scope = Object.create(parentScope); // ref holder for the scope scope.$refs = Object.create(parentScope.$refs); scope.$els = Object.create(parentScope.$els); // make sure point $parent to parent scope scope.$parent = parentScope; // for two-way binding on alias scope.$forContext = this; // define scope properties // important: define the scope alias without forced conversion // so that frozen data structures remain non-reactive. withoutConversion(function () { defineReactive(scope, alias, value); }); defineReactive(scope, '$index', index); if (key) { defineReactive(scope, '$key', key); } else if (scope.$key) { // avoid accidental fallback def(scope, '$key', null); } if (this.iterator) { defineReactive(scope, this.iterator, key !== null ? key : index); } var frag = this.factory.create(host, scope, this._frag); frag.forId = this.id; this.cacheFrag(value, frag, index, key); return frag; }, /** * Update the v-ref on owner vm. */ updateRef: function updateRef() { var ref = this.descriptor.ref; if (!ref) return; var hash = (this._scope || this.vm).$refs; var refs; if (!this.fromObject) { refs = this.frags.map(findVmFromFrag); } else { refs = {}; this.frags.forEach(function (frag) { refs[frag.scope.$key] = findVmFromFrag(frag); }); } hash[ref] = refs; }, /** * For option lists, update the containing v-model on * parent <select>. */ updateModel: function updateModel() { if (this.isOption) { var parent = this.start.parentNode; var model = parent && parent.__v_model; if (model) { model.forceUpdate(); } } }, /** * Insert a fragment. Handles staggering. * * @param {Fragment} frag * @param {Number} index * @param {Node} prevEl * @param {Boolean} inDocument */ insert: function insert(frag, index, prevEl, inDocument) { if (frag.staggerCb) { frag.staggerCb.cancel(); frag.staggerCb = null; } var staggerAmount = this.getStagger(frag, index, null, 'enter'); if (inDocument && staggerAmount) { // create an anchor and insert it synchronously, // so that we can resolve the correct order without // worrying about some elements not inserted yet var anchor = frag.staggerAnchor; if (!anchor) { anchor = frag.staggerAnchor = createAnchor('stagger-anchor'); anchor.__v_frag = frag; } after(anchor, prevEl); var op = frag.staggerCb = cancellable(function () { frag.staggerCb = null; frag.before(anchor); remove(anchor); }); setTimeout(op, staggerAmount); } else { var target = prevEl.nextSibling; /* istanbul ignore if */ if (!target) { // reset end anchor position in case the position was messed up // by an external drag-n-drop library. after(this.end, prevEl); target = this.end; } frag.before(target); } }, /** * Remove a fragment. Handles staggering. * * @param {Fragment} frag * @param {Number} index * @param {Number} total * @param {Boolean} inDocument */ remove: function remove(frag, index, total, inDocument) { if (frag.staggerCb) { frag.staggerCb.cancel(); frag.staggerCb = null; // it's not possible for the same frag to be removed // twice, so if we have a pending stagger callback, // it means this frag is queued for enter but removed // before its transition started. Since it is already // destroyed, we can just leave it in detached state. return; } var staggerAmount = this.getStagger(frag, index, total, 'leave'); if (inDocument && staggerAmount) { var op = frag.staggerCb = cancellable(function () { frag.staggerCb = null; frag.remove(); }); setTimeout(op, staggerAmount); } else { frag.remove(); } }, /** * Move a fragment to a new position. * Force no transition. * * @param {Fragment} frag * @param {Node} prevEl */ move: function move(frag, prevEl) { // fix a common issue with Sortable: // if prevEl doesn't have nextSibling, this means it's // been dragged after the end anchor. Just re-position // the end anchor to the end of the container. /* istanbul ignore if */ if (!prevEl.nextSibling) { this.end.parentNode.appendChild(this.end); } frag.before(prevEl.nextSibling, false); }, /** * Cache a fragment using track-by or the object key. * * @param {*} value * @param {Fragment} frag * @param {Number} index * @param {String} [key] */ cacheFrag: function cacheFrag(value, frag, index, key) { var trackByKey = this.params.trackBy; var cache = this.cache; var primitive = !isObject(value); var id; if (key || trackByKey || primitive) { id = getTrackByKey(index, key, value, trackByKey); if (!cache[id]) { cache[id] = frag; } else if (trackByKey !== '$index') { 'development' !== 'production' && this.warnDuplicate(value); } } else { id = this.id; if (hasOwn(value, id)) { if (value[id] === null) { value[id] = frag; } else { 'development' !== 'production' && this.warnDuplicate(value); } } else if (Object.isExtensible(value)) { def(value, id, frag); } else if ('development' !== 'production') { warn('Frozen v-for objects cannot be automatically tracked, make sure to ' + 'provide a track-by key.'); } } frag.raw = value; }, /** * Get a cached fragment from the value/index/key * * @param {*} value * @param {Number} index * @param {String} key * @return {Fragment} */ getCachedFrag: function getCachedFrag(value, index, key) { var trackByKey = this.params.trackBy; var primitive = !isObject(value); var frag; if (key || trackByKey || primitive) { var id = getTrackByKey(index, key, value, trackByKey); frag = this.cache[id]; } else { frag = value[this.id]; } if (frag && (frag.reused || frag.fresh)) { 'development' !== 'production' && this.warnDuplicate(value); } return frag; }, /** * Delete a fragment from cache. * * @param {Fragment} frag */ deleteCachedFrag: function deleteCachedFrag(frag) { var value = frag.raw; var trackByKey = this.params.trackBy; var scope = frag.scope; var index = scope.$index; // fix #948: avoid accidentally fall through to // a parent repeater which happens to have $key. var key = hasOwn(scope, '$key') && scope.$key; var primitive = !isObject(value); if (trackByKey || key || primitive) { var id = getTrackByKey(index, key, value, trackByKey); this.cache[id] = null; } else { value[this.id] = null; frag.raw = null; } }, /** * Get the stagger amount for an insertion/removal. * * @param {Fragment} frag * @param {Number} index * @param {Number} total * @param {String} type */ getStagger: function getStagger(frag, index, total, type) { type = type + 'Stagger'; var trans = frag.node.__v_trans; var hooks = trans && trans.hooks; var hook = hooks && (hooks[type] || hooks.stagger); return hook ? hook.call(frag, index, total) : index * parseInt(this.params[type] || this.params.stagger, 10); }, /** * Pre-process the value before piping it through the * filters. This is passed to and called by the watcher. */ _preProcess: function _preProcess(value) { // regardless of type, store the un-filtered raw value. this.rawValue = value; return value; }, /** * Post-process the value after it has been piped through * the filters. This is passed to and called by the watcher. * * It is necessary for this to be called during the * wathcer's dependency collection phase because we want * the v-for to update when the source Object is mutated. */ _postProcess: function _postProcess(value) { if (isArray(value)) { return value; } else if (isPlainObject(value)) { // convert plain object to array. var keys = Object.keys(value); var i = keys.length; var res = new Array(i); var key; while (i--) { key = keys[i]; res[i] = { $key: key, $value: value[key] }; } return res; } else { if (typeof value === 'number' && !isNaN(value)) { value = range(value); } return value || []; } }, unbind: function unbind() { if (this.descriptor.ref) { (this._scope || this.vm).$refs[this.descriptor.ref] = null; } if (this.frags) { var i = this.frags.length; var frag; while (i--) { frag = this.frags[i]; this.deleteCachedFrag(frag); frag.destroy(); } } } }; /** * Helper to find the previous element that is a fragment * anchor. This is necessary because a destroyed frag's * element could still be lingering in the DOM before its * leaving transition finishes, but its inserted flag * should have been set to false so we can skip them. * * If this is a block repeat, we want to make sure we only * return frag that is bound to this v-for. (see #929) * * @param {Fragment} frag * @param {Comment|Text} anchor * @param {String} id * @return {Fragment} */ function findPrevFrag(frag, anchor, id) { var el = frag.node.previousSibling; /* istanbul ignore if */ if (!el) return; frag = el.__v_frag; while ((!frag || frag.forId !== id || !frag.inserted) && el !== anchor) { el = el.previousSibling; /* istanbul ignore if */ if (!el) return; frag = el.__v_frag; } return frag; } /** * Find a vm from a fragment. * * @param {Fragment} frag * @return {Vue|undefined} */ function findVmFromFrag(frag) { var node = frag.node; // handle multi-node frag if (frag.end) { while (!node.__vue__ && node !== frag.end && node.nextSibling) { node = node.nextSibling; } } return node.__vue__; } /** * Create a range array from given number. * * @param {Number} n * @return {Array} */ function range(n) { var i = -1; var ret = new Array(Math.floor(n)); while (++i < n) { ret[i] = i; } return ret; } /** * Get the track by key for an item. * * @param {Number} index * @param {String} key * @param {*} value * @param {String} [trackByKey] */ function getTrackByKey(index, key, value, trackByKey) { return trackByKey ? trackByKey === '$index' ? index : trackByKey.charAt(0).match(/\w/) ? getPath(value, trackByKey) : value[trackByKey] : key || value; } if ('development' !== 'production') { vFor.warnDuplicate = function (value) { warn('Duplicate value found in v-for="' + this.descriptor.raw + '": ' + JSON.stringify(value) + '. Use track-by="$index" if ' + 'you are expecting duplicate values.', this.vm); }; } var vIf = { priority: IF, terminal: true, bind: function bind() { var el = this.el; if (!el.__vue__) { // check else block var next = el.nextElementSibling; if (next && getAttr(next, 'v-else') !== null) { remove(next); this.elseEl = next; } // check main block this.anchor = createAnchor('v-if'); replace(el, this.anchor); } else { 'development' !== 'production' && warn('v-if="' + this.expression + '" cannot be ' + 'used on an instance root element.', this.vm); this.invalid = true; } }, update: function update(value) { if (this.invalid) return; if (value) { if (!this.frag) { this.insert(); } } else { this.remove(); } }, insert: function insert() { if (this.elseFrag) { this.elseFrag.remove(); this.elseFrag = null; } // lazy init factory if (!this.factory) { this.factory = new FragmentFactory(this.vm, this.el); } this.frag = this.factory.create(this._host, this._scope, this._frag); this.frag.before(this.anchor); }, remove: function remove() { if (this.frag) { this.frag.remove(); this.frag = null; } if (this.elseEl && !this.elseFrag) { if (!this.elseFactory) { this.elseFactory = new FragmentFactory(this.elseEl._context || this.vm, this.elseEl); } this.elseFrag = this.elseFactory.create(this._host, this._scope, this._frag); this.elseFrag.before(this.anchor); } }, unbind: function unbind() { if (this.frag) { this.frag.destroy(); } if (this.elseFrag) { this.elseFrag.destroy(); } } }; var show = { bind: function bind() { // check else block var next = this.el.nextElementSibling; if (next && getAttr(next, 'v-else') !== null) { this.elseEl = next; } }, update: function update(value) { this.apply(this.el, value); if (this.elseEl) { this.apply(this.elseEl, !value); } }, apply: function apply(el, value) { if (inDoc(el)) { applyTransition(el, value ? 1 : -1, toggle, this.vm); } else { toggle(); } function toggle() { el.style.display = value ? '' : 'none'; } } }; var text$2 = { bind: function bind() { var self = this; var el = this.el; var isRange = el.type === 'range'; var lazy = this.params.lazy; var number = this.params.number; var debounce = this.params.debounce; // handle composition events. // path_to_url // skip this for Android because it handles composition // events quite differently. Android doesn't trigger // composition events for language input methods e.g. // Chinese, but instead triggers them for spelling // suggestions... (see Discussion/#162) var composing = false; if (!isAndroid && !isRange) { this.on('compositionstart', function () { composing = true; }); this.on('compositionend', function () { composing = false; // in IE11 the "compositionend" event fires AFTER // the "input" event, so the input handler is blocked // at the end... have to call it here. // // #1327: in lazy mode this is unecessary. if (!lazy) { self.listener(); } }); } // prevent messing with the input when user is typing, // and force update on blur. this.focused = false; if (!isRange && !lazy) { this.on('focus', function () { self.focused = true; }); this.on('blur', function () { self.focused = false; // do not sync value after fragment removal (#2017) if (!self._frag || self._frag.inserted) { self.rawListener(); } }); } // Now attach the main listener this.listener = this.rawListener = function () { if (composing || !self._bound) { return; } var val = number || isRange ? toNumber(el.value) : el.value; self.set(val); // force update on next tick to avoid lock & same value // also only update when user is not typing nextTick(function () { if (self._bound && !self.focused) { self.update(self._watcher.value); } }); }; // apply debounce if (debounce) { this.listener = _debounce(this.listener, debounce); } // Support jQuery events, since jQuery.trigger() doesn't // trigger native events in some cases and some plugins // rely on $.trigger() // // We want to make sure if a listener is attached using // jQuery, it is also removed with jQuery, that's why // we do the check for each directive instance and // store that check result on itself. This also allows // easier test coverage control by unsetting the global // jQuery variable in tests. this.hasjQuery = typeof jQuery === 'function'; if (this.hasjQuery) { var method = jQuery.fn.on ? 'on' : 'bind'; jQuery(el)[method]('change', this.rawListener); if (!lazy) { jQuery(el)[method]('input', this.listener); } } else { this.on('change', this.rawListener); if (!lazy) { this.on('input', this.listener); } } // IE9 doesn't fire input event on backspace/del/cut if (!lazy && isIE9) { this.on('cut', function () { nextTick(self.listener); }); this.on('keyup', function (e) { if (e.keyCode === 46 || e.keyCode === 8) { self.listener(); } }); } // set initial value if present if (el.hasAttribute('value') || el.tagName === 'TEXTAREA' && el.value.trim()) { this.afterBind = this.listener; } }, update: function update(value) { this.el.value = _toString(value); }, unbind: function unbind() { var el = this.el; if (this.hasjQuery) { var method = jQuery.fn.off ? 'off' : 'unbind'; jQuery(el)[method]('change', this.listener); jQuery(el)[method]('input', this.listener); } } }; var radio = { bind: function bind() { var self = this; var el = this.el; this.getValue = function () { // value overwrite via v-bind:value if (el.hasOwnProperty('_value')) { return el._value; } var val = el.value; if (self.params.number) { val = toNumber(val); } return val; }; this.listener = function () { self.set(self.getValue()); }; this.on('change', this.listener); if (el.hasAttribute('checked')) { this.afterBind = this.listener; } }, update: function update(value) { this.el.checked = looseEqual(value, this.getValue()); } }; var select = { bind: function bind() { var self = this; var el = this.el; // method to force update DOM using latest value. this.forceUpdate = function () { if (self._watcher) { self.update(self._watcher.get()); } }; // check if this is a multiple select var multiple = this.multiple = el.hasAttribute('multiple'); // attach listener this.listener = function () { var value = getValue(el, multiple); value = self.params.number ? isArray(value) ? value.map(toNumber) : toNumber(value) : value; self.set(value); }; this.on('change', this.listener); // if has initial value, set afterBind var initValue = getValue(el, multiple, true); if (multiple && initValue.length || !multiple && initValue !== null) { this.afterBind = this.listener; } // All major browsers except Firefox resets // selectedIndex with value -1 to 0 when the element // is appended to a new parent, therefore we have to // force a DOM update whenever that happens... this.vm.$on('hook:attached', this.forceUpdate); }, update: function update(value) { var el = this.el; el.selectedIndex = -1; var multi = this.multiple && isArray(value); var options = el.options; var i = options.length; var op, val; while (i--) { op = options[i]; val = op.hasOwnProperty('_value') ? op._value : op.value; /* eslint-disable eqeqeq */ op.selected = multi ? indexOf$1(value, val) > -1 : looseEqual(value, val); /* eslint-enable eqeqeq */ } }, unbind: function unbind() { /* istanbul ignore next */ this.vm.$off('hook:attached', this.forceUpdate); } }; /** * Get select value * * @param {SelectElement} el * @param {Boolean} multi * @param {Boolean} init * @return {Array|*} */ function getValue(el, multi, init) { var res = multi ? [] : null; var op, val, selected; for (var i = 0, l = el.options.length; i < l; i++) { op = el.options[i]; selected = init ? op.hasAttribute('selected') : op.selected; if (selected) { val = op.hasOwnProperty('_value') ? op._value : op.value; if (multi) { res.push(val); } else { return val; } } } return res; } /** * Native Array.indexOf uses strict equal, but in this * case we need to match string/numbers with custom equal. * * @param {Array} arr * @param {*} val */ function indexOf$1(arr, val) { var i = arr.length; while (i--) { if (looseEqual(arr[i], val)) { return i; } } return -1; } var checkbox = { bind: function bind() { var self = this; var el = this.el; this.getValue = function () { return el.hasOwnProperty('_value') ? el._value : self.params.number ? toNumber(el.value) : el.value; }; function getBooleanValue() { var val = el.checked; if (val && el.hasOwnProperty('_trueValue')) { return el._trueValue; } if (!val && el.hasOwnProperty('_falseValue')) { return el._falseValue; } return val; } this.listener = function () { var model = self._watcher.value; if (isArray(model)) { var val = self.getValue(); if (el.checked) { if (indexOf(model, val) < 0) { model.push(val); } } else { model.$remove(val); } } else { self.set(getBooleanValue()); } }; this.on('change', this.listener); if (el.hasAttribute('checked')) { this.afterBind = this.listener; } }, update: function update(value) { var el = this.el; if (isArray(value)) { el.checked = indexOf(value, this.getValue()) > -1; } else { if (el.hasOwnProperty('_trueValue')) { el.checked = looseEqual(value, el._trueValue); } else { el.checked = !!value; } } } }; var handlers = { text: text$2, radio: radio, select: select, checkbox: checkbox }; var model = { priority: MODEL, twoWay: true, handlers: handlers, params: ['lazy', 'number', 'debounce'], /** * Possible elements: * <select> * <textarea> * <input type="*"> * - text * - checkbox * - radio * - number */ bind: function bind() { // friendly warning... this.checkFilters(); if (this.hasRead && !this.hasWrite) { 'development' !== 'production' && warn('It seems you are using a read-only filter with ' + 'v-model="' + this.descriptor.raw + '". ' + 'You might want to use a two-way filter to ensure correct behavior.', this.vm); } var el = this.el; var tag = el.tagName; var handler; if (tag === 'INPUT') { handler = handlers[el.type] || handlers.text; } else if (tag === 'SELECT') { handler = handlers.select; } else if (tag === 'TEXTAREA') { handler = handlers.text; } else { 'development' !== 'production' && warn('v-model does not support element type: ' + tag, this.vm); return; } el.__v_model = this; handler.bind.call(this); this.update = handler.update; this._unbind = handler.unbind; }, /** * Check read/write filter stats. */ checkFilters: function checkFilters() { var filters = this.filters; if (!filters) return; var i = filters.length; while (i--) { var filter = resolveAsset(this.vm.$options, 'filters', filters[i].name); if (typeof filter === 'function' || filter.read) { this.hasRead = true; } if (filter.write) { this.hasWrite = true; } } }, unbind: function unbind() { this.el.__v_model = null; this._unbind && this._unbind(); } }; // keyCode aliases var keyCodes = { esc: 27, tab: 9, enter: 13, space: 32, 'delete': [8, 46], up: 38, left: 37, right: 39, down: 40 }; function keyFilter(handler, keys) { var codes = keys.map(function (key) { var charCode = key.charCodeAt(0); if (charCode > 47 && charCode < 58) { return parseInt(key, 10); } if (key.length === 1) { charCode = key.toUpperCase().charCodeAt(0); if (charCode > 64 && charCode < 91) { return charCode; } } return keyCodes[key]; }); codes = [].concat.apply([], codes); return function keyHandler(e) { if (codes.indexOf(e.keyCode) > -1) { return handler.call(this, e); } }; } function stopFilter(handler) { return function stopHandler(e) { e.stopPropagation(); return handler.call(this, e); }; } function preventFilter(handler) { return function preventHandler(e) { e.preventDefault(); return handler.call(this, e); }; } function selfFilter(handler) { return function selfHandler(e) { if (e.target === e.currentTarget) { return handler.call(this, e); } }; } var on$1 = { priority: ON, acceptStatement: true, keyCodes: keyCodes, bind: function bind() { // deal with iframes if (this.el.tagName === 'IFRAME' && this.arg !== 'load') { var self = this; this.iframeBind = function () { on(self.el.contentWindow, self.arg, self.handler, self.modifiers.capture); }; this.on('load', this.iframeBind); } }, update: function update(handler) { // stub a noop for v-on with no value, // e.g. @mousedown.prevent if (!this.descriptor.raw) { handler = function () {}; } if (typeof handler !== 'function') { 'development' !== 'production' && warn('v-on:' + this.arg + '="' + this.expression + '" expects a function value, ' + 'got ' + handler, this.vm); return; } // apply modifiers if (this.modifiers.stop) { handler = stopFilter(handler); } if (this.modifiers.prevent) { handler = preventFilter(handler); } if (this.modifiers.self) { handler = selfFilter(handler); } // key filter var keys = Object.keys(this.modifiers).filter(function (key) { return key !== 'stop' && key !== 'prevent' && key !== 'self' && key !== 'capture'; }); if (keys.length) { handler = keyFilter(handler, keys); } this.reset(); this.handler = handler; if (this.iframeBind) { this.iframeBind(); } else { on(this.el, this.arg, this.handler, this.modifiers.capture); } }, reset: function reset() { var el = this.iframeBind ? this.el.contentWindow : this.el; if (this.handler) { off(el, this.arg, this.handler); } }, unbind: function unbind() { this.reset(); } }; var prefixes = ['-webkit-', '-moz-', '-ms-']; var camelPrefixes = ['Webkit', 'Moz', 'ms']; var importantRE = /!important;?$/; var propCache = Object.create(null); var testEl = null; var style = { deep: true, update: function update(value) { if (typeof value === 'string') { this.el.style.cssText = value; } else if (isArray(value)) { this.handleObject(value.reduce(extend, {})); } else { this.handleObject(value || {}); } }, handleObject: function handleObject(value) { // cache object styles so that only changed props // are actually updated. var cache = this.cache || (this.cache = {}); var name, val; for (name in cache) { if (!(name in value)) { this.handleSingle(name, null); delete cache[name]; } } for (name in value) { val = value[name]; if (val !== cache[name]) { cache[name] = val; this.handleSingle(name, val); } } }, handleSingle: function handleSingle(prop, value) { prop = normalize(prop); if (!prop) return; // unsupported prop // cast possible numbers/booleans into strings if (value != null) value += ''; if (value) { var isImportant = importantRE.test(value) ? 'important' : ''; if (isImportant) { /* istanbul ignore if */ if ('development' !== 'production') { warn('It\'s probably a bad idea to use !important with inline rules. ' + 'This feature will be deprecated in a future version of Vue.'); } value = value.replace(importantRE, '').trim(); this.el.style.setProperty(prop.kebab, value, isImportant); } else { this.el.style[prop.camel] = value; } } else { this.el.style[prop.camel] = ''; } } }; /** * Normalize a CSS property name. * - cache result * - auto prefix * - camelCase -> dash-case * * @param {String} prop * @return {String} */ function normalize(prop) { if (propCache[prop]) { return propCache[prop]; } var res = prefix(prop); propCache[prop] = propCache[res] = res; return res; } /** * Auto detect the appropriate prefix for a CSS property. * path_to_url * * @param {String} prop * @return {String} */ function prefix(prop) { prop = hyphenate(prop); var camel = camelize(prop); var upper = camel.charAt(0).toUpperCase() + camel.slice(1); if (!testEl) { testEl = document.createElement('div'); } var i = prefixes.length; var prefixed; if (camel !== 'filter' && camel in testEl.style) { return { kebab: prop, camel: camel }; } while (i--) { prefixed = camelPrefixes[i] + upper; if (prefixed in testEl.style) { return { kebab: prefixes[i] + prop, camel: prefixed }; } } } // xlink var xlinkNS = 'path_to_url var xlinkRE = /^xlink:/; // check for attributes that prohibit interpolations var disallowedInterpAttrRE = /^v-|^:|^@|^(?:is|transition|transition-mode|debounce|track-by|stagger|enter-stagger|leave-stagger)$/; // these attributes should also set their corresponding properties // because they only affect the initial state of the element var attrWithPropsRE = /^(?:value|checked|selected|muted)$/; // these attributes expect enumrated values of "true" or "false" // but are not boolean attributes var enumeratedAttrRE = /^(?:draggable|contenteditable|spellcheck)$/; // these attributes should set a hidden property for // binding v-model to object values var modelProps = { value: '_value', 'true-value': '_trueValue', 'false-value': '_falseValue' }; var bind$1 = { priority: BIND, bind: function bind() { var attr = this.arg; var tag = this.el.tagName; // should be deep watch on object mode if (!attr) { this.deep = true; } // handle interpolation bindings var descriptor = this.descriptor; var tokens = descriptor.interp; if (tokens) { // handle interpolations with one-time tokens if (descriptor.hasOneTime) { this.expression = tokensToExp(tokens, this._scope || this.vm); } // only allow binding on native attributes if (disallowedInterpAttrRE.test(attr) || attr === 'name' && (tag === 'PARTIAL' || tag === 'SLOT')) { 'development' !== 'production' && warn(attr + '="' + descriptor.raw + '": ' + 'attribute interpolation is not allowed in Vue.js ' + 'directives and special attributes.', this.vm); this.el.removeAttribute(attr); this.invalid = true; } /* istanbul ignore if */ if ('development' !== 'production') { var raw = attr + '="' + descriptor.raw + '": '; // warn src if (attr === 'src') { warn(raw + 'interpolation in "src" attribute will cause ' + 'a 404 request. Use v-bind:src instead.', this.vm); } // warn style if (attr === 'style') { warn(raw + 'interpolation in "style" attribute will cause ' + 'the attribute to be discarded in Internet Explorer. ' + 'Use v-bind:style instead.', this.vm); } } } }, update: function update(value) { if (this.invalid) { return; } var attr = this.arg; if (this.arg) { this.handleSingle(attr, value); } else { this.handleObject(value || {}); } }, // share object handler with v-bind:class handleObject: style.handleObject, handleSingle: function handleSingle(attr, value) { var el = this.el; var interp = this.descriptor.interp; if (this.modifiers.camel) { attr = camelize(attr); } if (!interp && attrWithPropsRE.test(attr) && attr in el) { var attrValue = attr === 'value' ? value == null // IE9 will set input.value to "null" for null... ? '' : value : value; if (el[attr] !== attrValue) { el[attr] = attrValue; } } // set model props var modelProp = modelProps[attr]; if (!interp && modelProp) { el[modelProp] = value; // update v-model if present var model = el.__v_model; if (model) { model.listener(); } } // do not set value attribute for textarea if (attr === 'value' && el.tagName === 'TEXTAREA') { el.removeAttribute(attr); return; } // update attribute if (enumeratedAttrRE.test(attr)) { el.setAttribute(attr, value ? 'true' : 'false'); } else if (value != null && value !== false) { if (attr === 'class') { // handle edge case #1960: // class interpolation should not overwrite Vue transition class if (el.__v_trans) { value += ' ' + el.__v_trans.id + '-transition'; } setClass(el, value); } else if (xlinkRE.test(attr)) { el.setAttributeNS(xlinkNS, attr, value === true ? '' : value); } else { el.setAttribute(attr, value === true ? '' : value); } } else { el.removeAttribute(attr); } } }; var el = { priority: EL, bind: function bind() { /* istanbul ignore if */ if (!this.arg) { return; } var id = this.id = camelize(this.arg); var refs = (this._scope || this.vm).$els; if (hasOwn(refs, id)) { refs[id] = this.el; } else { defineReactive(refs, id, this.el); } }, unbind: function unbind() { var refs = (this._scope || this.vm).$els; if (refs[this.id] === this.el) { refs[this.id] = null; } } }; var ref = { bind: function bind() { 'development' !== 'production' && warn('v-ref:' + this.arg + ' must be used on a child ' + 'component. Found on <' + this.el.tagName.toLowerCase() + '>.', this.vm); } }; var cloak = { bind: function bind() { var el = this.el; this.vm.$once('pre-hook:compiled', function () { el.removeAttribute('v-cloak'); }); } }; // must export plain object var directives = { text: text$1, html: html, 'for': vFor, 'if': vIf, show: show, model: model, on: on$1, bind: bind$1, el: el, ref: ref, cloak: cloak }; var vClass = { deep: true, update: function update(value) { if (!value) { this.cleanup(); } else if (typeof value === 'string') { this.setClass(value.trim().split(/\s+/)); } else { this.setClass(normalize$1(value)); } }, setClass: function setClass(value) { this.cleanup(value); for (var i = 0, l = value.length; i < l; i++) { var val = value[i]; if (val) { apply(this.el, val, addClass); } } this.prevKeys = value; }, cleanup: function cleanup(value) { var prevKeys = this.prevKeys; if (!prevKeys) return; var i = prevKeys.length; while (i--) { var key = prevKeys[i]; if (!value || value.indexOf(key) < 0) { apply(this.el, key, removeClass); } } } }; /** * Normalize objects and arrays (potentially containing objects) * into array of strings. * * @param {Object|Array<String|Object>} value * @return {Array<String>} */ function normalize$1(value) { var res = []; if (isArray(value)) { for (var i = 0, l = value.length; i < l; i++) { var _key = value[i]; if (_key) { if (typeof _key === 'string') { res.push(_key); } else { for (var k in _key) { if (_key[k]) res.push(k); } } } } } else if (isObject(value)) { for (var key in value) { if (value[key]) res.push(key); } } return res; } /** * Add or remove a class/classes on an element * * @param {Element} el * @param {String} key The class name. This may or may not * contain a space character, in such a * case we'll deal with multiple class * names at once. * @param {Function} fn */ function apply(el, key, fn) { key = key.trim(); if (key.indexOf(' ') === -1) { fn(el, key); return; } // The key contains one or more space characters. // Since a class name doesn't accept such characters, we // treat it as multiple classes. var keys = key.split(/\s+/); for (var i = 0, l = keys.length; i < l; i++) { fn(el, keys[i]); } } var component = { priority: COMPONENT, params: ['keep-alive', 'transition-mode', 'inline-template'], /** * Setup. Two possible usages: * * - static: * <comp> or <div v-component="comp"> * * - dynamic: * <component :is="view"> */ bind: function bind() { if (!this.el.__vue__) { // keep-alive cache this.keepAlive = this.params.keepAlive; if (this.keepAlive) { this.cache = {}; } // check inline-template if (this.params.inlineTemplate) { // extract inline template as a DocumentFragment this.inlineTemplate = extractContent(this.el, true); } // component resolution related state this.pendingComponentCb = this.Component = null; // transition related state this.pendingRemovals = 0; this.pendingRemovalCb = null; // create a ref anchor this.anchor = createAnchor('v-component'); replace(this.el, this.anchor); // remove is attribute. // this is removed during compilation, but because compilation is // cached, when the component is used elsewhere this attribute // will remain at link time. this.el.removeAttribute('is'); this.el.removeAttribute(':is'); // remove ref, same as above if (this.descriptor.ref) { this.el.removeAttribute('v-ref:' + hyphenate(this.descriptor.ref)); } // if static, build right now. if (this.literal) { this.setComponent(this.expression); } } else { 'development' !== 'production' && warn('cannot mount component "' + this.expression + '" ' + 'on already mounted element: ' + this.el); } }, /** * Public update, called by the watcher in the dynamic * literal scenario, e.g. <component :is="view"> */ update: function update(value) { if (!this.literal) { this.setComponent(value); } }, /** * Switch dynamic components. May resolve the component * asynchronously, and perform transition based on * specified transition mode. Accepts a few additional * arguments specifically for vue-router. * * The callback is called when the full transition is * finished. * * @param {String} value * @param {Function} [cb] */ setComponent: function setComponent(value, cb) { this.invalidatePending(); if (!value) { // just remove current this.unbuild(true); this.remove(this.childVM, cb); this.childVM = null; } else { var self = this; this.resolveComponent(value, function () { self.mountComponent(cb); }); } }, /** * Resolve the component constructor to use when creating * the child vm. * * @param {String|Function} value * @param {Function} cb */ resolveComponent: function resolveComponent(value, cb) { var self = this; this.pendingComponentCb = cancellable(function (Component) { self.ComponentName = Component.options.name || (typeof value === 'string' ? value : null); self.Component = Component; cb(); }); this.vm._resolveComponent(value, this.pendingComponentCb); }, /** * Create a new instance using the current constructor and * replace the existing instance. This method doesn't care * whether the new component and the old one are actually * the same. * * @param {Function} [cb] */ mountComponent: function mountComponent(cb) { // actual mount this.unbuild(true); var self = this; var activateHooks = this.Component.options.activate; var cached = this.getCached(); var newComponent = this.build(); if (activateHooks && !cached) { this.waitingFor = newComponent; callActivateHooks(activateHooks, newComponent, function () { if (self.waitingFor !== newComponent) { return; } self.waitingFor = null; self.transition(newComponent, cb); }); } else { // update ref for kept-alive component if (cached) { newComponent._updateRef(); } this.transition(newComponent, cb); } }, /** * When the component changes or unbinds before an async * constructor is resolved, we need to invalidate its * pending callback. */ invalidatePending: function invalidatePending() { if (this.pendingComponentCb) { this.pendingComponentCb.cancel(); this.pendingComponentCb = null; } }, /** * Instantiate/insert a new child vm. * If keep alive and has cached instance, insert that * instance; otherwise build a new one and cache it. * * @param {Object} [extraOptions] * @return {Vue} - the created instance */ build: function build(extraOptions) { var cached = this.getCached(); if (cached) { return cached; } if (this.Component) { // default options var options = { name: this.ComponentName, el: cloneNode(this.el), template: this.inlineTemplate, // make sure to add the child with correct parent // if this is a transcluded component, its parent // should be the transclusion host. parent: this._host || this.vm, // if no inline-template, then the compiled // linker can be cached for better performance. _linkerCachable: !this.inlineTemplate, _ref: this.descriptor.ref, _asComponent: true, _isRouterView: this._isRouterView, // if this is a transcluded component, context // will be the common parent vm of this instance // and its host. _context: this.vm, // if this is inside an inline v-for, the scope // will be the intermediate scope created for this // repeat fragment. this is used for linking props // and container directives. _scope: this._scope, // pass in the owner fragment of this component. // this is necessary so that the fragment can keep // track of its contained components in order to // call attach/detach hooks for them. _frag: this._frag }; // extra options // in 1.0.0 this is used by vue-router only /* istanbul ignore if */ if (extraOptions) { extend(options, extraOptions); } var child = new this.Component(options); if (this.keepAlive) { this.cache[this.Component.cid] = child; } /* istanbul ignore if */ if ('development' !== 'production' && this.el.hasAttribute('transition') && child._isFragment) { warn('Transitions will not work on a fragment instance. ' + 'Template: ' + child.$options.template, child); } return child; } }, /** * Try to get a cached instance of the current component. * * @return {Vue|undefined} */ getCached: function getCached() { return this.keepAlive && this.cache[this.Component.cid]; }, /** * Teardown the current child, but defers cleanup so * that we can separate the destroy and removal steps. * * @param {Boolean} defer */ unbuild: function unbuild(defer) { if (this.waitingFor) { if (!this.keepAlive) { this.waitingFor.$destroy(); } this.waitingFor = null; } var child = this.childVM; if (!child || this.keepAlive) { if (child) { // remove ref child._inactive = true; child._updateRef(true); } return; } // the sole purpose of `deferCleanup` is so that we can // "deactivate" the vm right now and perform DOM removal // later. child.$destroy(false, defer); }, /** * Remove current destroyed child and manually do * the cleanup after removal. * * @param {Function} cb */ remove: function remove(child, cb) { var keepAlive = this.keepAlive; if (child) { // we may have a component switch when a previous // component is still being transitioned out. // we want to trigger only one lastest insertion cb // when the existing transition finishes. (#1119) this.pendingRemovals++; this.pendingRemovalCb = cb; var self = this; child.$remove(function () { self.pendingRemovals--; if (!keepAlive) child._cleanup(); if (!self.pendingRemovals && self.pendingRemovalCb) { self.pendingRemovalCb(); self.pendingRemovalCb = null; } }); } else if (cb) { cb(); } }, /** * Actually swap the components, depending on the * transition mode. Defaults to simultaneous. * * @param {Vue} target * @param {Function} [cb] */ transition: function transition(target, cb) { var self = this; var current = this.childVM; // for devtool inspection if (current) current._inactive = true; target._inactive = false; this.childVM = target; switch (self.params.transitionMode) { case 'in-out': target.$before(self.anchor, function () { self.remove(current, cb); }); break; case 'out-in': self.remove(current, function () { target.$before(self.anchor, cb); }); break; default: self.remove(current); target.$before(self.anchor, cb); } }, /** * Unbind. */ unbind: function unbind() { this.invalidatePending(); // Do not defer cleanup when unbinding this.unbuild(); // destroy all keep-alive cached instances if (this.cache) { for (var key in this.cache) { this.cache[key].$destroy(); } this.cache = null; } } }; /** * Call activate hooks in order (asynchronous) * * @param {Array} hooks * @param {Vue} vm * @param {Function} cb */ function callActivateHooks(hooks, vm, cb) { var total = hooks.length; var called = 0; hooks[0].call(vm, next); function next() { if (++called >= total) { cb(); } else { hooks[called].call(vm, next); } } } var propBindingModes = config._propBindingModes; var empty = {}; // regexes var identRE$1 = /^[$_a-zA-Z]+[\w$]*$/; var settablePathRE = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*|\[[^\[\]]+\])*$/; /** * Compile props on a root element and return * a props link function. * * @param {Element|DocumentFragment} el * @param {Array} propOptions * @param {Vue} vm * @return {Function} propsLinkFn */ function compileProps(el, propOptions, vm) { var props = []; var names = Object.keys(propOptions); var i = names.length; var options, name, attr, value, path, parsed, prop; while (i--) { name = names[i]; options = propOptions[name] || empty; if ('development' !== 'production' && name === '$data') { warn('Do not use $data as prop.', vm); continue; } // props could contain dashes, which will be // interpreted as minus calculations by the parser // so we need to camelize the path here path = camelize(name); if (!identRE$1.test(path)) { 'development' !== 'production' && warn('Invalid prop key: "' + name + '". Prop keys ' + 'must be valid identifiers.', vm); continue; } prop = { name: name, path: path, options: options, mode: propBindingModes.ONE_WAY, raw: null }; attr = hyphenate(name); // first check dynamic version if ((value = getBindAttr(el, attr)) === null) { if ((value = getBindAttr(el, attr + '.sync')) !== null) { prop.mode = propBindingModes.TWO_WAY; } else if ((value = getBindAttr(el, attr + '.once')) !== null) { prop.mode = propBindingModes.ONE_TIME; } } if (value !== null) { // has dynamic binding! prop.raw = value; parsed = parseDirective(value); value = parsed.expression; prop.filters = parsed.filters; // check binding type if (isLiteral(value) && !parsed.filters) { // for expressions containing literal numbers and // booleans, there's no need to setup a prop binding, // so we can optimize them as a one-time set. prop.optimizedLiteral = true; } else { prop.dynamic = true; // check non-settable path for two-way bindings if ('development' !== 'production' && prop.mode === propBindingModes.TWO_WAY && !settablePathRE.test(value)) { prop.mode = propBindingModes.ONE_WAY; warn('Cannot bind two-way prop with non-settable ' + 'parent path: ' + value, vm); } } prop.parentPath = value; // warn required two-way if ('development' !== 'production' && options.twoWay && prop.mode !== propBindingModes.TWO_WAY) { warn('Prop "' + name + '" expects a two-way binding type.', vm); } } else if ((value = getAttr(el, attr)) !== null) { // has literal binding! prop.raw = value; } else if ('development' !== 'production') { // check possible camelCase prop usage var lowerCaseName = path.toLowerCase(); value = /[A-Z\-]/.test(name) && (el.getAttribute(lowerCaseName) || el.getAttribute(':' + lowerCaseName) || el.getAttribute('v-bind:' + lowerCaseName) || el.getAttribute(':' + lowerCaseName + '.once') || el.getAttribute('v-bind:' + lowerCaseName + '.once') || el.getAttribute(':' + lowerCaseName + '.sync') || el.getAttribute('v-bind:' + lowerCaseName + '.sync')); if (value) { warn('Possible usage error for prop `' + lowerCaseName + '` - ' + 'did you mean `' + attr + '`? HTML is case-insensitive, remember to use ' + 'kebab-case for props in templates.', vm); } else if (options.required) { // warn missing required warn('Missing required prop: ' + name, vm); } } // push prop props.push(prop); } return makePropsLinkFn(props); } /** * Build a function that applies props to a vm. * * @param {Array} props * @return {Function} propsLinkFn */ function makePropsLinkFn(props) { return function propsLinkFn(vm, scope) { // store resolved props info vm._props = {}; var inlineProps = vm.$options.propsData; var i = props.length; var prop, path, options, value, raw; while (i--) { prop = props[i]; raw = prop.raw; path = prop.path; options = prop.options; vm._props[path] = prop; if (inlineProps && hasOwn(inlineProps, path)) { initProp(vm, prop, inlineProps[path]); }if (raw === null) { // initialize absent prop initProp(vm, prop, undefined); } else if (prop.dynamic) { // dynamic prop if (prop.mode === propBindingModes.ONE_TIME) { // one time binding value = (scope || vm._context || vm).$get(prop.parentPath); initProp(vm, prop, value); } else { if (vm._context) { // dynamic binding vm._bindDir({ name: 'prop', def: propDef, prop: prop }, null, null, scope); // el, host, scope } else { // root instance initProp(vm, prop, vm.$get(prop.parentPath)); } } } else if (prop.optimizedLiteral) { // optimized literal, cast it and just set once var stripped = stripQuotes(raw); value = stripped === raw ? toBoolean(toNumber(raw)) : stripped; initProp(vm, prop, value); } else { // string literal, but we need to cater for // Boolean props with no value, or with same // literal value (e.g. disabled="disabled") // see path_to_url value = options.type === Boolean && (raw === '' || raw === hyphenate(prop.name)) ? true : raw; initProp(vm, prop, value); } } }; } /** * Process a prop with a rawValue, applying necessary coersions, * default values & assertions and call the given callback with * processed value. * * @param {Vue} vm * @param {Object} prop * @param {*} rawValue * @param {Function} fn */ function processPropValue(vm, prop, rawValue, fn) { var isSimple = prop.dynamic && isSimplePath(prop.parentPath); var value = rawValue; if (value === undefined) { value = getPropDefaultValue(vm, prop); } value = coerceProp(prop, value); var coerced = value !== rawValue; if (!assertProp(prop, value, vm)) { value = undefined; } if (isSimple && !coerced) { withoutConversion(function () { fn(value); }); } else { fn(value); } } /** * Set a prop's initial value on a vm and its data object. * * @param {Vue} vm * @param {Object} prop * @param {*} value */ function initProp(vm, prop, value) { processPropValue(vm, prop, value, function (value) { defineReactive(vm, prop.path, value); }); } /** * Update a prop's value on a vm. * * @param {Vue} vm * @param {Object} prop * @param {*} value */ function updateProp(vm, prop, value) { processPropValue(vm, prop, value, function (value) { vm[prop.path] = value; }); } /** * Get the default value of a prop. * * @param {Vue} vm * @param {Object} prop * @return {*} */ function getPropDefaultValue(vm, prop) { // no default, return undefined var options = prop.options; if (!hasOwn(options, 'default')) { // absent boolean value defaults to false return options.type === Boolean ? false : undefined; } var def = options['default']; // warn against non-factory defaults for Object & Array if (isObject(def)) { 'development' !== 'production' && warn('Invalid default value for prop "' + prop.name + '": ' + 'Props with type Object/Array must use a factory function ' + 'to return the default value.', vm); } // call factory function for non-Function types return typeof def === 'function' && options.type !== Function ? def.call(vm) : def; } /** * Assert whether a prop is valid. * * @param {Object} prop * @param {*} value * @param {Vue} vm */ function assertProp(prop, value, vm) { if (!prop.options.required && ( // non-required prop.raw === null || // abscent value == null) // null or undefined ) { return true; } var options = prop.options; var type = options.type; var valid = !type; var expectedTypes = []; if (type) { if (!isArray(type)) { type = [type]; } for (var i = 0; i < type.length && !valid; i++) { var assertedType = assertType(value, type[i]); expectedTypes.push(assertedType.expectedType); valid = assertedType.valid; } } if (!valid) { if ('development' !== 'production') { warn('Invalid prop: type check failed for prop "' + prop.name + '".' + ' Expected ' + expectedTypes.map(formatType).join(', ') + ', got ' + formatValue(value) + '.', vm); } return false; } var validator = options.validator; if (validator) { if (!validator(value)) { 'development' !== 'production' && warn('Invalid prop: custom validator check failed for prop "' + prop.name + '".', vm); return false; } } return true; } /** * Force parsing value with coerce option. * * @param {*} value * @param {Object} options * @return {*} */ function coerceProp(prop, value) { var coerce = prop.options.coerce; if (!coerce) { return value; } // coerce is a function return coerce(value); } /** * Assert the type of a value * * @param {*} value * @param {Function} type * @return {Object} */ function assertType(value, type) { var valid; var expectedType; if (type === String) { expectedType = 'string'; valid = typeof value === expectedType; } else if (type === Number) { expectedType = 'number'; valid = typeof value === expectedType; } else if (type === Boolean) { expectedType = 'boolean'; valid = typeof value === expectedType; } else if (type === Function) { expectedType = 'function'; valid = typeof value === expectedType; } else if (type === Object) { expectedType = 'object'; valid = isPlainObject(value); } else if (type === Array) { expectedType = 'array'; valid = isArray(value); } else { valid = value instanceof type; } return { valid: valid, expectedType: expectedType }; } /** * Format type for output * * @param {String} type * @return {String} */ function formatType(type) { return type ? type.charAt(0).toUpperCase() + type.slice(1) : 'custom type'; } /** * Format value * * @param {*} value * @return {String} */ function formatValue(val) { return Object.prototype.toString.call(val).slice(8, -1); } var bindingModes = config._propBindingModes; var propDef = { bind: function bind() { var child = this.vm; var parent = child._context; // passed in from compiler directly var prop = this.descriptor.prop; var childKey = prop.path; var parentKey = prop.parentPath; var twoWay = prop.mode === bindingModes.TWO_WAY; var parentWatcher = this.parentWatcher = new Watcher(parent, parentKey, function (val) { updateProp(child, prop, val); }, { twoWay: twoWay, filters: prop.filters, // important: props need to be observed on the // v-for scope if present scope: this._scope }); // set the child initial value. initProp(child, prop, parentWatcher.value); // setup two-way binding if (twoWay) { // important: defer the child watcher creation until // the created hook (after data observation) var self = this; child.$once('pre-hook:created', function () { self.childWatcher = new Watcher(child, childKey, function (val) { parentWatcher.set(val); }, { // ensure sync upward before parent sync down. // this is necessary in cases e.g. the child // mutates a prop array, then replaces it. (#1683) sync: true }); }); } }, unbind: function unbind() { this.parentWatcher.teardown(); if (this.childWatcher) { this.childWatcher.teardown(); } } }; var queue$1 = []; var queued = false; /** * Push a job into the queue. * * @param {Function} job */ function pushJob(job) { queue$1.push(job); if (!queued) { queued = true; nextTick(flush); } } /** * Flush the queue, and do one forced reflow before * triggering transitions. */ function flush() { // Force layout var f = document.documentElement.offsetHeight; for (var i = 0; i < queue$1.length; i++) { queue$1[i](); } queue$1 = []; queued = false; // dummy return, so js linters don't complain about // unused variable f return f; } var TYPE_TRANSITION = 'transition'; var TYPE_ANIMATION = 'animation'; var transDurationProp = transitionProp + 'Duration'; var animDurationProp = animationProp + 'Duration'; /** * If a just-entered element is applied the * leave class while its enter transition hasn't started yet, * and the transitioned property has the same value for both * enter/leave, then the leave transition will be skipped and * the transitionend event never fires. This function ensures * its callback to be called after a transition has started * by waiting for double raf. * * It falls back to setTimeout on devices that support CSS * transitions but not raf (e.g. Android 4.2 browser) - since * these environments are usually slow, we are giving it a * relatively large timeout. */ var raf = inBrowser && window.requestAnimationFrame; var waitForTransitionStart = raf /* istanbul ignore next */ ? function (fn) { raf(function () { raf(fn); }); } : function (fn) { setTimeout(fn, 50); }; /** * A Transition object that encapsulates the state and logic * of the transition. * * @param {Element} el * @param {String} id * @param {Object} hooks * @param {Vue} vm */ function Transition(el, id, hooks, vm) { this.id = id; this.el = el; this.enterClass = hooks && hooks.enterClass || id + '-enter'; this.leaveClass = hooks && hooks.leaveClass || id + '-leave'; this.hooks = hooks; this.vm = vm; // async state this.pendingCssEvent = this.pendingCssCb = this.cancel = this.pendingJsCb = this.op = this.cb = null; this.justEntered = false; this.entered = this.left = false; this.typeCache = {}; // check css transition type this.type = hooks && hooks.type; /* istanbul ignore if */ if ('development' !== 'production') { if (this.type && this.type !== TYPE_TRANSITION && this.type !== TYPE_ANIMATION) { warn('invalid CSS transition type for transition="' + this.id + '": ' + this.type, vm); } } // bind var self = this;['enterNextTick', 'enterDone', 'leaveNextTick', 'leaveDone'].forEach(function (m) { self[m] = bind(self[m], self); }); } var p$1 = Transition.prototype; /** * Start an entering transition. * * 1. enter transition triggered * 2. call beforeEnter hook * 3. add enter class * 4. insert/show element * 5. call enter hook (with possible explicit js callback) * 6. reflow * 7. based on transition type: * - transition: * remove class now, wait for transitionend, * then done if there's no explicit js callback. * - animation: * wait for animationend, remove class, * then done if there's no explicit js callback. * - no css transition: * done now if there's no explicit js callback. * 8. wait for either done or js callback, then call * afterEnter hook. * * @param {Function} op - insert/show the element * @param {Function} [cb] */ p$1.enter = function (op, cb) { this.cancelPending(); this.callHook('beforeEnter'); this.cb = cb; addClass(this.el, this.enterClass); op(); this.entered = false; this.callHookWithCb('enter'); if (this.entered) { return; // user called done synchronously. } this.cancel = this.hooks && this.hooks.enterCancelled; pushJob(this.enterNextTick); }; /** * The "nextTick" phase of an entering transition, which is * to be pushed into a queue and executed after a reflow so * that removing the class can trigger a CSS transition. */ p$1.enterNextTick = function () { var _this = this; // prevent transition skipping this.justEntered = true; waitForTransitionStart(function () { _this.justEntered = false; }); var enterDone = this.enterDone; var type = this.getCssTransitionType(this.enterClass); if (!this.pendingJsCb) { if (type === TYPE_TRANSITION) { // trigger transition by removing enter class now removeClass(this.el, this.enterClass); this.setupCssCb(transitionEndEvent, enterDone); } else if (type === TYPE_ANIMATION) { this.setupCssCb(animationEndEvent, enterDone); } else { enterDone(); } } else if (type === TYPE_TRANSITION) { removeClass(this.el, this.enterClass); } }; /** * The "cleanup" phase of an entering transition. */ p$1.enterDone = function () { this.entered = true; this.cancel = this.pendingJsCb = null; removeClass(this.el, this.enterClass); this.callHook('afterEnter'); if (this.cb) this.cb(); }; /** * Start a leaving transition. * * 1. leave transition triggered. * 2. call beforeLeave hook * 3. add leave class (trigger css transition) * 4. call leave hook (with possible explicit js callback) * 5. reflow if no explicit js callback is provided * 6. based on transition type: * - transition or animation: * wait for end event, remove class, then done if * there's no explicit js callback. * - no css transition: * done if there's no explicit js callback. * 7. wait for either done or js callback, then call * afterLeave hook. * * @param {Function} op - remove/hide the element * @param {Function} [cb] */ p$1.leave = function (op, cb) { this.cancelPending(); this.callHook('beforeLeave'); this.op = op; this.cb = cb; addClass(this.el, this.leaveClass); this.left = false; this.callHookWithCb('leave'); if (this.left) { return; // user called done synchronously. } this.cancel = this.hooks && this.hooks.leaveCancelled; // only need to handle leaveDone if // 1. the transition is already done (synchronously called // by the user, which causes this.op set to null) // 2. there's no explicit js callback if (this.op && !this.pendingJsCb) { // if a CSS transition leaves immediately after enter, // the transitionend event never fires. therefore we // detect such cases and end the leave immediately. if (this.justEntered) { this.leaveDone(); } else { pushJob(this.leaveNextTick); } } }; /** * The "nextTick" phase of a leaving transition. */ p$1.leaveNextTick = function () { var type = this.getCssTransitionType(this.leaveClass); if (type) { var event = type === TYPE_TRANSITION ? transitionEndEvent : animationEndEvent; this.setupCssCb(event, this.leaveDone); } else { this.leaveDone(); } }; /** * The "cleanup" phase of a leaving transition. */ p$1.leaveDone = function () { this.left = true; this.cancel = this.pendingJsCb = null; this.op(); removeClass(this.el, this.leaveClass); this.callHook('afterLeave'); if (this.cb) this.cb(); this.op = null; }; /** * Cancel any pending callbacks from a previously running * but not finished transition. */ p$1.cancelPending = function () { this.op = this.cb = null; var hasPending = false; if (this.pendingCssCb) { hasPending = true; off(this.el, this.pendingCssEvent, this.pendingCssCb); this.pendingCssEvent = this.pendingCssCb = null; } if (this.pendingJsCb) { hasPending = true; this.pendingJsCb.cancel(); this.pendingJsCb = null; } if (hasPending) { removeClass(this.el, this.enterClass); removeClass(this.el, this.leaveClass); } if (this.cancel) { this.cancel.call(this.vm, this.el); this.cancel = null; } }; /** * Call a user-provided synchronous hook function. * * @param {String} type */ p$1.callHook = function (type) { if (this.hooks && this.hooks[type]) { this.hooks[type].call(this.vm, this.el); } }; /** * Call a user-provided, potentially-async hook function. * We check for the length of arguments to see if the hook * expects a `done` callback. If true, the transition's end * will be determined by when the user calls that callback; * otherwise, the end is determined by the CSS transition or * animation. * * @param {String} type */ p$1.callHookWithCb = function (type) { var hook = this.hooks && this.hooks[type]; if (hook) { if (hook.length > 1) { this.pendingJsCb = cancellable(this[type + 'Done']); } hook.call(this.vm, this.el, this.pendingJsCb); } }; /** * Get an element's transition type based on the * calculated styles. * * @param {String} className * @return {Number} */ p$1.getCssTransitionType = function (className) { /* istanbul ignore if */ if (!transitionEndEvent || // skip CSS transitions if page is not visible - // this solves the issue of transitionend events not // firing until the page is visible again. // pageVisibility API is supported in IE10+, same as // CSS transitions. document.hidden || // explicit js-only transition this.hooks && this.hooks.css === false || // element is hidden isHidden(this.el)) { return; } var type = this.type || this.typeCache[className]; if (type) return type; var inlineStyles = this.el.style; var computedStyles = window.getComputedStyle(this.el); var transDuration = inlineStyles[transDurationProp] || computedStyles[transDurationProp]; if (transDuration && transDuration !== '0s') { type = TYPE_TRANSITION; } else { var animDuration = inlineStyles[animDurationProp] || computedStyles[animDurationProp]; if (animDuration && animDuration !== '0s') { type = TYPE_ANIMATION; } } if (type) { this.typeCache[className] = type; } return type; }; /** * Setup a CSS transitionend/animationend callback. * * @param {String} event * @param {Function} cb */ p$1.setupCssCb = function (event, cb) { this.pendingCssEvent = event; var self = this; var el = this.el; var onEnd = this.pendingCssCb = function (e) { if (e.target === el) { off(el, event, onEnd); self.pendingCssEvent = self.pendingCssCb = null; if (!self.pendingJsCb && cb) { cb(); } } }; on(el, event, onEnd); }; /** * Check if an element is hidden - in that case we can just * skip the transition alltogether. * * @param {Element} el * @return {Boolean} */ function isHidden(el) { if (/svg$/.test(el.namespaceURI)) { // SVG elements do not have offset(Width|Height) // so we need to check the client rect var rect = el.getBoundingClientRect(); return !(rect.width || rect.height); } else { return !(el.offsetWidth || el.offsetHeight || el.getClientRects().length); } } var transition$1 = { priority: TRANSITION, update: function update(id, oldId) { var el = this.el; // resolve on owner vm var hooks = resolveAsset(this.vm.$options, 'transitions', id); id = id || 'v'; el.__v_trans = new Transition(el, id, hooks, this.vm); if (oldId) { removeClass(el, oldId + '-transition'); } addClass(el, id + '-transition'); } }; var internalDirectives = { style: style, 'class': vClass, component: component, prop: propDef, transition: transition$1 }; // special binding prefixes var bindRE = /^v-bind:|^:/; var onRE = /^v-on:|^@/; var dirAttrRE = /^v-([^:]+)(?:$|:(.*)$)/; var modifierRE = /\.[^\.]+/g; var transitionRE = /^(v-bind:|:)?transition$/; // default directive priority var DEFAULT_PRIORITY = 1000; var DEFAULT_TERMINAL_PRIORITY = 2000; /** * Compile a template and return a reusable composite link * function, which recursively contains more link functions * inside. This top level compile function would normally * be called on instance root nodes, but can also be used * for partial compilation if the partial argument is true. * * The returned composite link function, when called, will * return an unlink function that tearsdown all directives * created during the linking phase. * * @param {Element|DocumentFragment} el * @param {Object} options * @param {Boolean} partial * @return {Function} */ function compile(el, options, partial) { // link function for the node itself. var nodeLinkFn = partial || !options._asComponent ? compileNode(el, options) : null; // link function for the childNodes var childLinkFn = !(nodeLinkFn && nodeLinkFn.terminal) && !isScript(el) && el.hasChildNodes() ? compileNodeList(el.childNodes, options) : null; /** * A composite linker function to be called on a already * compiled piece of DOM, which instantiates all directive * instances. * * @param {Vue} vm * @param {Element|DocumentFragment} el * @param {Vue} [host] - host vm of transcluded content * @param {Object} [scope] - v-for scope * @param {Fragment} [frag] - link context fragment * @return {Function|undefined} */ return function compositeLinkFn(vm, el, host, scope, frag) { // cache childNodes before linking parent, fix #657 var childNodes = toArray(el.childNodes); // link var dirs = linkAndCapture(function compositeLinkCapturer() { if (nodeLinkFn) nodeLinkFn(vm, el, host, scope, frag); if (childLinkFn) childLinkFn(vm, childNodes, host, scope, frag); }, vm); return makeUnlinkFn(vm, dirs); }; } /** * Apply a linker to a vm/element pair and capture the * directives created during the process. * * @param {Function} linker * @param {Vue} vm */ function linkAndCapture(linker, vm) { /* istanbul ignore if */ if ('development' === 'production') {} var originalDirCount = vm._directives.length; linker(); var dirs = vm._directives.slice(originalDirCount); dirs.sort(directiveComparator); for (var i = 0, l = dirs.length; i < l; i++) { dirs[i]._bind(); } return dirs; } /** * Directive priority sort comparator * * @param {Object} a * @param {Object} b */ function directiveComparator(a, b) { a = a.descriptor.def.priority || DEFAULT_PRIORITY; b = b.descriptor.def.priority || DEFAULT_PRIORITY; return a > b ? -1 : a === b ? 0 : 1; } /** * Linker functions return an unlink function that * tearsdown all directives instances generated during * the process. * * We create unlink functions with only the necessary * information to avoid retaining additional closures. * * @param {Vue} vm * @param {Array} dirs * @param {Vue} [context] * @param {Array} [contextDirs] * @return {Function} */ function makeUnlinkFn(vm, dirs, context, contextDirs) { function unlink(destroying) { teardownDirs(vm, dirs, destroying); if (context && contextDirs) { teardownDirs(context, contextDirs); } } // expose linked directives unlink.dirs = dirs; return unlink; } /** * Teardown partial linked directives. * * @param {Vue} vm * @param {Array} dirs * @param {Boolean} destroying */ function teardownDirs(vm, dirs, destroying) { var i = dirs.length; while (i--) { dirs[i]._teardown(); if ('development' !== 'production' && !destroying) { vm._directives.$remove(dirs[i]); } } } /** * Compile link props on an instance. * * @param {Vue} vm * @param {Element} el * @param {Object} props * @param {Object} [scope] * @return {Function} */ function compileAndLinkProps(vm, el, props, scope) { var propsLinkFn = compileProps(el, props, vm); var propDirs = linkAndCapture(function () { propsLinkFn(vm, scope); }, vm); return makeUnlinkFn(vm, propDirs); } /** * Compile the root element of an instance. * * 1. attrs on context container (context scope) * 2. attrs on the component template root node, if * replace:true (child scope) * * If this is a fragment instance, we only need to compile 1. * * @param {Element} el * @param {Object} options * @param {Object} contextOptions * @return {Function} */ function compileRoot(el, options, contextOptions) { var containerAttrs = options._containerAttrs; var replacerAttrs = options._replacerAttrs; var contextLinkFn, replacerLinkFn; // only need to compile other attributes for // non-fragment instances if (el.nodeType !== 11) { // for components, container and replacer need to be // compiled separately and linked in different scopes. if (options._asComponent) { // 2. container attributes if (containerAttrs && contextOptions) { contextLinkFn = compileDirectives(containerAttrs, contextOptions); } if (replacerAttrs) { // 3. replacer attributes replacerLinkFn = compileDirectives(replacerAttrs, options); } } else { // non-component, just compile as a normal element. replacerLinkFn = compileDirectives(el.attributes, options); } } else if ('development' !== 'production' && containerAttrs) { // warn container directives for fragment instances var names = containerAttrs.filter(function (attr) { // allow vue-loader/vueify scoped css attributes return attr.name.indexOf('_v-') < 0 && // allow event listeners !onRE.test(attr.name) && // allow slots attr.name !== 'slot'; }).map(function (attr) { return '"' + attr.name + '"'; }); if (names.length) { var plural = names.length > 1; warn('Attribute' + (plural ? 's ' : ' ') + names.join(', ') + (plural ? ' are' : ' is') + ' ignored on component ' + '<' + options.el.tagName.toLowerCase() + '> because ' + 'the component is a fragment instance: ' + 'path_to_url#Fragment-Instance'); } } options._containerAttrs = options._replacerAttrs = null; return function rootLinkFn(vm, el, scope) { // link context scope dirs var context = vm._context; var contextDirs; if (context && contextLinkFn) { contextDirs = linkAndCapture(function () { contextLinkFn(context, el, null, scope); }, context); } // link self var selfDirs = linkAndCapture(function () { if (replacerLinkFn) replacerLinkFn(vm, el); }, vm); // return the unlink function that tearsdown context // container directives. return makeUnlinkFn(vm, selfDirs, context, contextDirs); }; } /** * Compile a node and return a nodeLinkFn based on the * node type. * * @param {Node} node * @param {Object} options * @return {Function|null} */ function compileNode(node, options) { var type = node.nodeType; if (type === 1 && !isScript(node)) { return compileElement(node, options); } else if (type === 3 && node.data.trim()) { return compileTextNode(node, options); } else { return null; } } /** * Compile an element and return a nodeLinkFn. * * @param {Element} el * @param {Object} options * @return {Function|null} */ function compileElement(el, options) { // preprocess textareas. // textarea treats its text content as the initial value. // just bind it as an attr directive for value. if (el.tagName === 'TEXTAREA') { var tokens = parseText(el.value); if (tokens) { el.setAttribute(':value', tokensToExp(tokens)); el.value = ''; } } var linkFn; var hasAttrs = el.hasAttributes(); var attrs = hasAttrs && toArray(el.attributes); // check terminal directives (for & if) if (hasAttrs) { linkFn = checkTerminalDirectives(el, attrs, options); } // check element directives if (!linkFn) { linkFn = checkElementDirectives(el, options); } // check component if (!linkFn) { linkFn = checkComponent(el, options); } // normal directives if (!linkFn && hasAttrs) { linkFn = compileDirectives(attrs, options); } return linkFn; } /** * Compile a textNode and return a nodeLinkFn. * * @param {TextNode} node * @param {Object} options * @return {Function|null} textNodeLinkFn */ function compileTextNode(node, options) { // skip marked text nodes if (node._skip) { return removeText; } var tokens = parseText(node.wholeText); if (!tokens) { return null; } // mark adjacent text nodes as skipped, // because we are using node.wholeText to compile // all adjacent text nodes together. This fixes // issues in IE where sometimes it splits up a single // text node into multiple ones. var next = node.nextSibling; while (next && next.nodeType === 3) { next._skip = true; next = next.nextSibling; } var frag = document.createDocumentFragment(); var el, token; for (var i = 0, l = tokens.length; i < l; i++) { token = tokens[i]; el = token.tag ? processTextToken(token, options) : document.createTextNode(token.value); frag.appendChild(el); } return makeTextNodeLinkFn(tokens, frag, options); } /** * Linker for an skipped text node. * * @param {Vue} vm * @param {Text} node */ function removeText(vm, node) { remove(node); } /** * Process a single text token. * * @param {Object} token * @param {Object} options * @return {Node} */ function processTextToken(token, options) { var el; if (token.oneTime) { el = document.createTextNode(token.value); } else { if (token.html) { el = document.createComment('v-html'); setTokenType('html'); } else { // IE will clean up empty textNodes during // frag.cloneNode(true), so we have to give it // something here... el = document.createTextNode(' '); setTokenType('text'); } } function setTokenType(type) { if (token.descriptor) return; var parsed = parseDirective(token.value); token.descriptor = { name: type, def: directives[type], expression: parsed.expression, filters: parsed.filters }; } return el; } /** * Build a function that processes a textNode. * * @param {Array<Object>} tokens * @param {DocumentFragment} frag */ function makeTextNodeLinkFn(tokens, frag) { return function textNodeLinkFn(vm, el, host, scope) { var fragClone = frag.cloneNode(true); var childNodes = toArray(fragClone.childNodes); var token, value, node; for (var i = 0, l = tokens.length; i < l; i++) { token = tokens[i]; value = token.value; if (token.tag) { node = childNodes[i]; if (token.oneTime) { value = (scope || vm).$eval(value); if (token.html) { replace(node, parseTemplate(value, true)); } else { node.data = value; } } else { vm._bindDir(token.descriptor, node, host, scope); } } } replace(el, fragClone); }; } /** * Compile a node list and return a childLinkFn. * * @param {NodeList} nodeList * @param {Object} options * @return {Function|undefined} */ function compileNodeList(nodeList, options) { var linkFns = []; var nodeLinkFn, childLinkFn, node; for (var i = 0, l = nodeList.length; i < l; i++) { node = nodeList[i]; nodeLinkFn = compileNode(node, options); childLinkFn = !(nodeLinkFn && nodeLinkFn.terminal) && node.tagName !== 'SCRIPT' && node.hasChildNodes() ? compileNodeList(node.childNodes, options) : null; linkFns.push(nodeLinkFn, childLinkFn); } return linkFns.length ? makeChildLinkFn(linkFns) : null; } /** * Make a child link function for a node's childNodes. * * @param {Array<Function>} linkFns * @return {Function} childLinkFn */ function makeChildLinkFn(linkFns) { return function childLinkFn(vm, nodes, host, scope, frag) { var node, nodeLinkFn, childrenLinkFn; for (var i = 0, n = 0, l = linkFns.length; i < l; n++) { node = nodes[n]; nodeLinkFn = linkFns[i++]; childrenLinkFn = linkFns[i++]; // cache childNodes before linking parent, fix #657 var childNodes = toArray(node.childNodes); if (nodeLinkFn) { nodeLinkFn(vm, node, host, scope, frag); } if (childrenLinkFn) { childrenLinkFn(vm, childNodes, host, scope, frag); } } }; } /** * Check for element directives (custom elements that should * be resovled as terminal directives). * * @param {Element} el * @param {Object} options */ function checkElementDirectives(el, options) { var tag = el.tagName.toLowerCase(); if (commonTagRE.test(tag)) { return; } var def = resolveAsset(options, 'elementDirectives', tag); if (def) { return makeTerminalNodeLinkFn(el, tag, '', options, def); } } /** * Check if an element is a component. If yes, return * a component link function. * * @param {Element} el * @param {Object} options * @return {Function|undefined} */ function checkComponent(el, options) { var component = checkComponentAttr(el, options); if (component) { var ref = findRef(el); var descriptor = { name: 'component', ref: ref, expression: component.id, def: internalDirectives.component, modifiers: { literal: !component.dynamic } }; var componentLinkFn = function componentLinkFn(vm, el, host, scope, frag) { if (ref) { defineReactive((scope || vm).$refs, ref, null); } vm._bindDir(descriptor, el, host, scope, frag); }; componentLinkFn.terminal = true; return componentLinkFn; } } /** * Check an element for terminal directives in fixed order. * If it finds one, return a terminal link function. * * @param {Element} el * @param {Array} attrs * @param {Object} options * @return {Function} terminalLinkFn */ function checkTerminalDirectives(el, attrs, options) { // skip v-pre if (getAttr(el, 'v-pre') !== null) { return skip; } // skip v-else block, but only if following v-if if (el.hasAttribute('v-else')) { var prev = el.previousElementSibling; if (prev && prev.hasAttribute('v-if')) { return skip; } } var attr, name, value, modifiers, matched, dirName, rawName, arg, def, termDef; for (var i = 0, j = attrs.length; i < j; i++) { attr = attrs[i]; name = attr.name.replace(modifierRE, ''); if (matched = name.match(dirAttrRE)) { def = resolveAsset(options, 'directives', matched[1]); if (def && def.terminal) { if (!termDef || (def.priority || DEFAULT_TERMINAL_PRIORITY) > termDef.priority) { termDef = def; rawName = attr.name; modifiers = parseModifiers(attr.name); value = attr.value; dirName = matched[1]; arg = matched[2]; } } } } if (termDef) { return makeTerminalNodeLinkFn(el, dirName, value, options, termDef, rawName, arg, modifiers); } } function skip() {} skip.terminal = true; /** * Build a node link function for a terminal directive. * A terminal link function terminates the current * compilation recursion and handles compilation of the * subtree in the directive. * * @param {Element} el * @param {String} dirName * @param {String} value * @param {Object} options * @param {Object} def * @param {String} [rawName] * @param {String} [arg] * @param {Object} [modifiers] * @return {Function} terminalLinkFn */ function makeTerminalNodeLinkFn(el, dirName, value, options, def, rawName, arg, modifiers) { var parsed = parseDirective(value); var descriptor = { name: dirName, arg: arg, expression: parsed.expression, filters: parsed.filters, raw: value, attr: rawName, modifiers: modifiers, def: def }; // check ref for v-for and router-view if (dirName === 'for' || dirName === 'router-view') { descriptor.ref = findRef(el); } var fn = function terminalNodeLinkFn(vm, el, host, scope, frag) { if (descriptor.ref) { defineReactive((scope || vm).$refs, descriptor.ref, null); } vm._bindDir(descriptor, el, host, scope, frag); }; fn.terminal = true; return fn; } /** * Compile the directives on an element and return a linker. * * @param {Array|NamedNodeMap} attrs * @param {Object} options * @return {Function} */ function compileDirectives(attrs, options) { var i = attrs.length; var dirs = []; var attr, name, value, rawName, rawValue, dirName, arg, modifiers, dirDef, tokens, matched; while (i--) { attr = attrs[i]; name = rawName = attr.name; value = rawValue = attr.value; tokens = parseText(value); // reset arg arg = null; // check modifiers modifiers = parseModifiers(name); name = name.replace(modifierRE, ''); // attribute interpolations if (tokens) { value = tokensToExp(tokens); arg = name; pushDir('bind', directives.bind, tokens); // warn against mixing mustaches with v-bind if ('development' !== 'production') { if (name === 'class' && Array.prototype.some.call(attrs, function (attr) { return attr.name === ':class' || attr.name === 'v-bind:class'; })) { warn('class="' + rawValue + '": Do not mix mustache interpolation ' + 'and v-bind for "class" on the same element. Use one or the other.', options); } } } else // special attribute: transition if (transitionRE.test(name)) { modifiers.literal = !bindRE.test(name); pushDir('transition', internalDirectives.transition); } else // event handlers if (onRE.test(name)) { arg = name.replace(onRE, ''); pushDir('on', directives.on); } else // attribute bindings if (bindRE.test(name)) { dirName = name.replace(bindRE, ''); if (dirName === 'style' || dirName === 'class') { pushDir(dirName, internalDirectives[dirName]); } else { arg = dirName; pushDir('bind', directives.bind); } } else // normal directives if (matched = name.match(dirAttrRE)) { dirName = matched[1]; arg = matched[2]; // skip v-else (when used with v-show) if (dirName === 'else') { continue; } dirDef = resolveAsset(options, 'directives', dirName, true); if (dirDef) { pushDir(dirName, dirDef); } } } /** * Push a directive. * * @param {String} dirName * @param {Object|Function} def * @param {Array} [interpTokens] */ function pushDir(dirName, def, interpTokens) { var hasOneTimeToken = interpTokens && hasOneTime(interpTokens); var parsed = !hasOneTimeToken && parseDirective(value); dirs.push({ name: dirName, attr: rawName, raw: rawValue, def: def, arg: arg, modifiers: modifiers, // conversion from interpolation strings with one-time token // to expression is differed until directive bind time so that we // have access to the actual vm context for one-time bindings. expression: parsed && parsed.expression, filters: parsed && parsed.filters, interp: interpTokens, hasOneTime: hasOneTimeToken }); } if (dirs.length) { return makeNodeLinkFn(dirs); } } /** * Parse modifiers from directive attribute name. * * @param {String} name * @return {Object} */ function parseModifiers(name) { var res = Object.create(null); var match = name.match(modifierRE); if (match) { var i = match.length; while (i--) { res[match[i].slice(1)] = true; } } return res; } /** * Build a link function for all directives on a single node. * * @param {Array} directives * @return {Function} directivesLinkFn */ function makeNodeLinkFn(directives) { return function nodeLinkFn(vm, el, host, scope, frag) { // reverse apply because it's sorted low to high var i = directives.length; while (i--) { vm._bindDir(directives[i], el, host, scope, frag); } }; } /** * Check if an interpolation string contains one-time tokens. * * @param {Array} tokens * @return {Boolean} */ function hasOneTime(tokens) { var i = tokens.length; while (i--) { if (tokens[i].oneTime) return true; } } function isScript(el) { return el.tagName === 'SCRIPT' && (!el.hasAttribute('type') || el.getAttribute('type') === 'text/javascript'); } var specialCharRE = /[^\w\-:\.]/; /** * Process an element or a DocumentFragment based on a * instance option object. This allows us to transclude * a template node/fragment before the instance is created, * so the processed fragment can then be cloned and reused * in v-for. * * @param {Element} el * @param {Object} options * @return {Element|DocumentFragment} */ function transclude(el, options) { // extract container attributes to pass them down // to compiler, because they need to be compiled in // parent scope. we are mutating the options object here // assuming the same object will be used for compile // right after this. if (options) { options._containerAttrs = extractAttrs(el); } // for template tags, what we want is its content as // a documentFragment (for fragment instances) if (isTemplate(el)) { el = parseTemplate(el); } if (options) { if (options._asComponent && !options.template) { options.template = '<slot></slot>'; } if (options.template) { options._content = extractContent(el); el = transcludeTemplate(el, options); } } if (isFragment(el)) { // anchors for fragment instance // passing in `persist: true` to avoid them being // discarded by IE during template cloning prepend(createAnchor('v-start', true), el); el.appendChild(createAnchor('v-end', true)); } return el; } /** * Process the template option. * If the replace option is true this will swap the $el. * * @param {Element} el * @param {Object} options * @return {Element|DocumentFragment} */ function transcludeTemplate(el, options) { var template = options.template; var frag = parseTemplate(template, true); if (frag) { var replacer = frag.firstChild; var tag = replacer.tagName && replacer.tagName.toLowerCase(); if (options.replace) { /* istanbul ignore if */ if (el === document.body) { 'development' !== 'production' && warn('You are mounting an instance with a template to ' + '<body>. This will replace <body> entirely. You ' + 'should probably use `replace: false` here.'); } // there are many cases where the instance must // become a fragment instance: basically anything that // can create more than 1 root nodes. if ( // multi-children template frag.childNodes.length > 1 || // non-element template replacer.nodeType !== 1 || // single nested component tag === 'component' || resolveAsset(options, 'components', tag) || hasBindAttr(replacer, 'is') || // element directive resolveAsset(options, 'elementDirectives', tag) || // for block replacer.hasAttribute('v-for') || // if block replacer.hasAttribute('v-if')) { return frag; } else { options._replacerAttrs = extractAttrs(replacer); mergeAttrs(el, replacer); return replacer; } } else { el.appendChild(frag); return el; } } else { 'development' !== 'production' && warn('Invalid template option: ' + template); } } /** * Helper to extract a component container's attributes * into a plain object array. * * @param {Element} el * @return {Array} */ function extractAttrs(el) { if (el.nodeType === 1 && el.hasAttributes()) { return toArray(el.attributes); } } /** * Merge the attributes of two elements, and make sure * the class names are merged properly. * * @param {Element} from * @param {Element} to */ function mergeAttrs(from, to) { var attrs = from.attributes; var i = attrs.length; var name, value; while (i--) { name = attrs[i].name; value = attrs[i].value; if (!to.hasAttribute(name) && !specialCharRE.test(name)) { to.setAttribute(name, value); } else if (name === 'class' && !parseText(value) && (value = value.trim())) { value.split(/\s+/).forEach(function (cls) { addClass(to, cls); }); } } } /** * Scan and determine slot content distribution. * We do this during transclusion instead at compile time so that * the distribution is decoupled from the compilation order of * the slots. * * @param {Element|DocumentFragment} template * @param {Element} content * @param {Vue} vm */ function resolveSlots(vm, content) { if (!content) { return; } var contents = vm._slotContents = Object.create(null); var el, name; for (var i = 0, l = content.children.length; i < l; i++) { el = content.children[i]; /* eslint-disable no-cond-assign */ if (name = el.getAttribute('slot')) { (contents[name] || (contents[name] = [])).push(el); } /* eslint-enable no-cond-assign */ if ('development' !== 'production' && getBindAttr(el, 'slot')) { warn('The "slot" attribute must be static.', vm.$parent); } } for (name in contents) { contents[name] = extractFragment(contents[name], content); } if (content.hasChildNodes()) { var nodes = content.childNodes; if (nodes.length === 1 && nodes[0].nodeType === 3 && !nodes[0].data.trim()) { return; } contents['default'] = extractFragment(content.childNodes, content); } } /** * Extract qualified content nodes from a node list. * * @param {NodeList} nodes * @return {DocumentFragment} */ function extractFragment(nodes, parent) { var frag = document.createDocumentFragment(); nodes = toArray(nodes); for (var i = 0, l = nodes.length; i < l; i++) { var node = nodes[i]; if (isTemplate(node) && !node.hasAttribute('v-if') && !node.hasAttribute('v-for')) { parent.removeChild(node); node = parseTemplate(node, true); } frag.appendChild(node); } return frag; } var compiler = Object.freeze({ compile: compile, compileAndLinkProps: compileAndLinkProps, compileRoot: compileRoot, transclude: transclude, resolveSlots: resolveSlots }); function stateMixin (Vue) { /** * Accessor for `$data` property, since setting $data * requires observing the new object and updating * proxied properties. */ Object.defineProperty(Vue.prototype, '$data', { get: function get() { return this._data; }, set: function set(newData) { if (newData !== this._data) { this._setData(newData); } } }); /** * Setup the scope of an instance, which contains: * - observed data * - computed properties * - user methods * - meta properties */ Vue.prototype._initState = function () { this._initProps(); this._initMeta(); this._initMethods(); this._initData(); this._initComputed(); }; /** * Initialize props. */ Vue.prototype._initProps = function () { var options = this.$options; var el = options.el; var props = options.props; if (props && !el) { 'development' !== 'production' && warn('Props will not be compiled if no `el` option is ' + 'provided at instantiation.', this); } // make sure to convert string selectors into element now el = options.el = query(el); this._propsUnlinkFn = el && el.nodeType === 1 && props // props must be linked in proper scope if inside v-for ? compileAndLinkProps(this, el, props, this._scope) : null; }; /** * Initialize the data. */ Vue.prototype._initData = function () { var dataFn = this.$options.data; var data = this._data = dataFn ? dataFn() : {}; if (!isPlainObject(data)) { data = {}; 'development' !== 'production' && warn('data functions should return an object.', this); } var props = this._props; // proxy data on instance var keys = Object.keys(data); var i, key; i = keys.length; while (i--) { key = keys[i]; // there are two scenarios where we can proxy a data key: // 1. it's not already defined as a prop // 2. it's provided via a instantiation option AND there are no // template prop present if (!props || !hasOwn(props, key)) { this._proxy(key); } else if ('development' !== 'production') { warn('Data field "' + key + '" is already defined ' + 'as a prop. To provide default value for a prop, use the "default" ' + 'prop option; if you want to pass prop values to an instantiation ' + 'call, use the "propsData" option.', this); } } // observe data observe(data, this); }; /** * Swap the instance's $data. Called in $data's setter. * * @param {Object} newData */ Vue.prototype._setData = function (newData) { newData = newData || {}; var oldData = this._data; this._data = newData; var keys, key, i; // unproxy keys not present in new data keys = Object.keys(oldData); i = keys.length; while (i--) { key = keys[i]; if (!(key in newData)) { this._unproxy(key); } } // proxy keys not already proxied, // and trigger change for changed values keys = Object.keys(newData); i = keys.length; while (i--) { key = keys[i]; if (!hasOwn(this, key)) { // new property this._proxy(key); } } oldData.__ob__.removeVm(this); observe(newData, this); this._digest(); }; /** * Proxy a property, so that * vm.prop === vm._data.prop * * @param {String} key */ Vue.prototype._proxy = function (key) { if (!isReserved(key)) { // need to store ref to self here // because these getter/setters might // be called by child scopes via // prototype inheritance. var self = this; Object.defineProperty(self, key, { configurable: true, enumerable: true, get: function proxyGetter() { return self._data[key]; }, set: function proxySetter(val) { self._data[key] = val; } }); } }; /** * Unproxy a property. * * @param {String} key */ Vue.prototype._unproxy = function (key) { if (!isReserved(key)) { delete this[key]; } }; /** * Force update on every watcher in scope. */ Vue.prototype._digest = function () { for (var i = 0, l = this._watchers.length; i < l; i++) { this._watchers[i].update(true); // shallow updates } }; /** * Setup computed properties. They are essentially * special getter/setters */ function noop() {} Vue.prototype._initComputed = function () { var computed = this.$options.computed; if (computed) { for (var key in computed) { var userDef = computed[key]; var def = { enumerable: true, configurable: true }; if (typeof userDef === 'function') { def.get = makeComputedGetter(userDef, this); def.set = noop; } else { def.get = userDef.get ? userDef.cache !== false ? makeComputedGetter(userDef.get, this) : bind(userDef.get, this) : noop; def.set = userDef.set ? bind(userDef.set, this) : noop; } Object.defineProperty(this, key, def); } } }; function makeComputedGetter(getter, owner) { var watcher = new Watcher(owner, getter, null, { lazy: true }); return function computedGetter() { if (watcher.dirty) { watcher.evaluate(); } if (Dep.target) { watcher.depend(); } return watcher.value; }; } /** * Setup instance methods. Methods must be bound to the * instance since they might be passed down as a prop to * child components. */ Vue.prototype._initMethods = function () { var methods = this.$options.methods; if (methods) { for (var key in methods) { this[key] = bind(methods[key], this); } } }; /** * Initialize meta information like $index, $key & $value. */ Vue.prototype._initMeta = function () { var metas = this.$options._meta; if (metas) { for (var key in metas) { defineReactive(this, key, metas[key]); } } }; } var eventRE = /^v-on:|^@/; function eventsMixin (Vue) { /** * Setup the instance's option events & watchers. * If the value is a string, we pull it from the * instance's methods by name. */ Vue.prototype._initEvents = function () { var options = this.$options; if (options._asComponent) { registerComponentEvents(this, options.el); } registerCallbacks(this, '$on', options.events); registerCallbacks(this, '$watch', options.watch); }; /** * Register v-on events on a child component * * @param {Vue} vm * @param {Element} el */ function registerComponentEvents(vm, el) { var attrs = el.attributes; var name, value, handler; for (var i = 0, l = attrs.length; i < l; i++) { name = attrs[i].name; if (eventRE.test(name)) { name = name.replace(eventRE, ''); // force the expression into a statement so that // it always dynamically resolves the method to call (#2670) // kinda ugly hack, but does the job. value = attrs[i].value; if (isSimplePath(value)) { value += '.apply(this, $arguments)'; } handler = (vm._scope || vm._context).$eval(value, true); handler._fromParent = true; vm.$on(name.replace(eventRE), handler); } } } /** * Register callbacks for option events and watchers. * * @param {Vue} vm * @param {String} action * @param {Object} hash */ function registerCallbacks(vm, action, hash) { if (!hash) return; var handlers, key, i, j; for (key in hash) { handlers = hash[key]; if (isArray(handlers)) { for (i = 0, j = handlers.length; i < j; i++) { register(vm, action, key, handlers[i]); } } else { register(vm, action, key, handlers); } } } /** * Helper to register an event/watch callback. * * @param {Vue} vm * @param {String} action * @param {String} key * @param {Function|String|Object} handler * @param {Object} [options] */ function register(vm, action, key, handler, options) { var type = typeof handler; if (type === 'function') { vm[action](key, handler, options); } else if (type === 'string') { var methods = vm.$options.methods; var method = methods && methods[handler]; if (method) { vm[action](key, method, options); } else { 'development' !== 'production' && warn('Unknown method: "' + handler + '" when ' + 'registering callback for ' + action + ': "' + key + '".', vm); } } else if (handler && type === 'object') { register(vm, action, key, handler.handler, handler); } } /** * Setup recursive attached/detached calls */ Vue.prototype._initDOMHooks = function () { this.$on('hook:attached', onAttached); this.$on('hook:detached', onDetached); }; /** * Callback to recursively call attached hook on children */ function onAttached() { if (!this._isAttached) { this._isAttached = true; this.$children.forEach(callAttach); } } /** * Iterator to call attached hook * * @param {Vue} child */ function callAttach(child) { if (!child._isAttached && inDoc(child.$el)) { child._callHook('attached'); } } /** * Callback to recursively call detached hook on children */ function onDetached() { if (this._isAttached) { this._isAttached = false; this.$children.forEach(callDetach); } } /** * Iterator to call detached hook * * @param {Vue} child */ function callDetach(child) { if (child._isAttached && !inDoc(child.$el)) { child._callHook('detached'); } } /** * Trigger all handlers for a hook * * @param {String} hook */ Vue.prototype._callHook = function (hook) { this.$emit('pre-hook:' + hook); var handlers = this.$options[hook]; if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { handlers[i].call(this); } } this.$emit('hook:' + hook); }; } function noop() {} /** * A directive links a DOM element with a piece of data, * which is the result of evaluating an expression. * It registers a watcher with the expression and calls * the DOM update function when a change is triggered. * * @param {Object} descriptor * - {String} name * - {Object} def * - {String} expression * - {Array<Object>} [filters] * - {Object} [modifiers] * - {Boolean} literal * - {String} attr * - {String} arg * - {String} raw * - {String} [ref] * - {Array<Object>} [interp] * - {Boolean} [hasOneTime] * @param {Vue} vm * @param {Node} el * @param {Vue} [host] - transclusion host component * @param {Object} [scope] - v-for scope * @param {Fragment} [frag] - owner fragment * @constructor */ function Directive(descriptor, vm, el, host, scope, frag) { this.vm = vm; this.el = el; // copy descriptor properties this.descriptor = descriptor; this.name = descriptor.name; this.expression = descriptor.expression; this.arg = descriptor.arg; this.modifiers = descriptor.modifiers; this.filters = descriptor.filters; this.literal = this.modifiers && this.modifiers.literal; // private this._locked = false; this._bound = false; this._listeners = null; // link context this._host = host; this._scope = scope; this._frag = frag; // store directives on node in dev mode if ('development' !== 'production' && this.el) { this.el._vue_directives = this.el._vue_directives || []; this.el._vue_directives.push(this); } } /** * Initialize the directive, mixin definition properties, * setup the watcher, call definition bind() and update() * if present. */ Directive.prototype._bind = function () { var name = this.name; var descriptor = this.descriptor; // remove attribute if ((name !== 'cloak' || this.vm._isCompiled) && this.el && this.el.removeAttribute) { var attr = descriptor.attr || 'v-' + name; this.el.removeAttribute(attr); } // copy def properties var def = descriptor.def; if (typeof def === 'function') { this.update = def; } else { extend(this, def); } // setup directive params this._setupParams(); // initial bind if (this.bind) { this.bind(); } this._bound = true; if (this.literal) { this.update && this.update(descriptor.raw); } else if ((this.expression || this.modifiers) && (this.update || this.twoWay) && !this._checkStatement()) { // wrapped updater for context var dir = this; if (this.update) { this._update = function (val, oldVal) { if (!dir._locked) { dir.update(val, oldVal); } }; } else { this._update = noop; } var preProcess = this._preProcess ? bind(this._preProcess, this) : null; var postProcess = this._postProcess ? bind(this._postProcess, this) : null; var watcher = this._watcher = new Watcher(this.vm, this.expression, this._update, // callback { filters: this.filters, twoWay: this.twoWay, deep: this.deep, preProcess: preProcess, postProcess: postProcess, scope: this._scope }); // v-model with inital inline value need to sync back to // model instead of update to DOM on init. They would // set the afterBind hook to indicate that. if (this.afterBind) { this.afterBind(); } else if (this.update) { this.update(watcher.value); } } }; /** * Setup all param attributes, e.g. track-by, * transition-mode, etc... */ Directive.prototype._setupParams = function () { if (!this.params) { return; } var params = this.params; // swap the params array with a fresh object. this.params = Object.create(null); var i = params.length; var key, val, mappedKey; while (i--) { key = hyphenate(params[i]); mappedKey = camelize(key); val = getBindAttr(this.el, key); if (val != null) { // dynamic this._setupParamWatcher(mappedKey, val); } else { // static val = getAttr(this.el, key); if (val != null) { this.params[mappedKey] = val === '' ? true : val; } } } }; /** * Setup a watcher for a dynamic param. * * @param {String} key * @param {String} expression */ Directive.prototype._setupParamWatcher = function (key, expression) { var self = this; var called = false; var unwatch = (this._scope || this.vm).$watch(expression, function (val, oldVal) { self.params[key] = val; // since we are in immediate mode, // only call the param change callbacks if this is not the first update. if (called) { var cb = self.paramWatchers && self.paramWatchers[key]; if (cb) { cb.call(self, val, oldVal); } } else { called = true; } }, { immediate: true, user: false });(this._paramUnwatchFns || (this._paramUnwatchFns = [])).push(unwatch); }; /** * Check if the directive is a function caller * and if the expression is a callable one. If both true, * we wrap up the expression and use it as the event * handler. * * e.g. on-click="a++" * * @return {Boolean} */ Directive.prototype._checkStatement = function () { var expression = this.expression; if (expression && this.acceptStatement && !isSimplePath(expression)) { var fn = parseExpression(expression).get; var scope = this._scope || this.vm; var handler = function handler(e) { scope.$event = e; fn.call(scope, scope); scope.$event = null; }; if (this.filters) { handler = scope._applyFilters(handler, null, this.filters); } this.update(handler); return true; } }; /** * Set the corresponding value with the setter. * This should only be used in two-way directives * e.g. v-model. * * @param {*} value * @public */ Directive.prototype.set = function (value) { /* istanbul ignore else */ if (this.twoWay) { this._withLock(function () { this._watcher.set(value); }); } else if ('development' !== 'production') { warn('Directive.set() can only be used inside twoWay' + 'directives.'); } }; /** * Execute a function while preventing that function from * triggering updates on this directive instance. * * @param {Function} fn */ Directive.prototype._withLock = function (fn) { var self = this; self._locked = true; fn.call(self); nextTick(function () { self._locked = false; }); }; /** * Convenience method that attaches a DOM event listener * to the directive element and autometically tears it down * during unbind. * * @param {String} event * @param {Function} handler * @param {Boolean} [useCapture] */ Directive.prototype.on = function (event, handler, useCapture) { on(this.el, event, handler, useCapture);(this._listeners || (this._listeners = [])).push([event, handler]); }; /** * Teardown the watcher and call unbind. */ Directive.prototype._teardown = function () { if (this._bound) { this._bound = false; if (this.unbind) { this.unbind(); } if (this._watcher) { this._watcher.teardown(); } var listeners = this._listeners; var i; if (listeners) { i = listeners.length; while (i--) { off(this.el, listeners[i][0], listeners[i][1]); } } var unwatchFns = this._paramUnwatchFns; if (unwatchFns) { i = unwatchFns.length; while (i--) { unwatchFns[i](); } } if ('development' !== 'production' && this.el) { this.el._vue_directives.$remove(this); } this.vm = this.el = this._watcher = this._listeners = null; } }; function lifecycleMixin (Vue) { /** * Update v-ref for component. * * @param {Boolean} remove */ Vue.prototype._updateRef = function (remove) { var ref = this.$options._ref; if (ref) { var refs = (this._scope || this._context).$refs; if (remove) { if (refs[ref] === this) { refs[ref] = null; } } else { refs[ref] = this; } } }; /** * Transclude, compile and link element. * * If a pre-compiled linker is available, that means the * passed in element will be pre-transcluded and compiled * as well - all we need to do is to call the linker. * * Otherwise we need to call transclude/compile/link here. * * @param {Element} el */ Vue.prototype._compile = function (el) { var options = this.$options; // transclude and init element // transclude can potentially replace original // so we need to keep reference; this step also injects // the template and caches the original attributes // on the container node and replacer node. var original = el; el = transclude(el, options); this._initElement(el); // handle v-pre on root node (#2026) if (el.nodeType === 1 && getAttr(el, 'v-pre') !== null) { return; } // root is always compiled per-instance, because // container attrs and props can be different every time. var contextOptions = this._context && this._context.$options; var rootLinker = compileRoot(el, options, contextOptions); // resolve slot distribution resolveSlots(this, options._content); // compile and link the rest var contentLinkFn; var ctor = this.constructor; // component compilation can be cached // as long as it's not using inline-template if (options._linkerCachable) { contentLinkFn = ctor.linker; if (!contentLinkFn) { contentLinkFn = ctor.linker = compile(el, options); } } // link phase // make sure to link root with prop scope! var rootUnlinkFn = rootLinker(this, el, this._scope); var contentUnlinkFn = contentLinkFn ? contentLinkFn(this, el) : compile(el, options)(this, el); // register composite unlink function // to be called during instance destruction this._unlinkFn = function () { rootUnlinkFn(); // passing destroying: true to avoid searching and // splicing the directives contentUnlinkFn(true); }; // finally replace original if (options.replace) { replace(original, el); } this._isCompiled = true; this._callHook('compiled'); }; /** * Initialize instance element. Called in the public * $mount() method. * * @param {Element} el */ Vue.prototype._initElement = function (el) { if (isFragment(el)) { this._isFragment = true; this.$el = this._fragmentStart = el.firstChild; this._fragmentEnd = el.lastChild; // set persisted text anchors to empty if (this._fragmentStart.nodeType === 3) { this._fragmentStart.data = this._fragmentEnd.data = ''; } this._fragment = el; } else { this.$el = el; } this.$el.__vue__ = this; this._callHook('beforeCompile'); }; /** * Create and bind a directive to an element. * * @param {Object} descriptor - parsed directive descriptor * @param {Node} node - target node * @param {Vue} [host] - transclusion host component * @param {Object} [scope] - v-for scope * @param {Fragment} [frag] - owner fragment */ Vue.prototype._bindDir = function (descriptor, node, host, scope, frag) { this._directives.push(new Directive(descriptor, this, node, host, scope, frag)); }; /** * Teardown an instance, unobserves the data, unbind all the * directives, turn off all the event listeners, etc. * * @param {Boolean} remove - whether to remove the DOM node. * @param {Boolean} deferCleanup - if true, defer cleanup to * be called later */ Vue.prototype._destroy = function (remove, deferCleanup) { if (this._isBeingDestroyed) { if (!deferCleanup) { this._cleanup(); } return; } var destroyReady; var pendingRemoval; var self = this; // Cleanup should be called either synchronously or asynchronoysly as // callback of this.$remove(), or if remove and deferCleanup are false. // In any case it should be called after all other removing, unbinding and // turning of is done var cleanupIfPossible = function cleanupIfPossible() { if (destroyReady && !pendingRemoval && !deferCleanup) { self._cleanup(); } }; // remove DOM element if (remove && this.$el) { pendingRemoval = true; this.$remove(function () { pendingRemoval = false; cleanupIfPossible(); }); } this._callHook('beforeDestroy'); this._isBeingDestroyed = true; var i; // remove self from parent. only necessary // if parent is not being destroyed as well. var parent = this.$parent; if (parent && !parent._isBeingDestroyed) { parent.$children.$remove(this); // unregister ref (remove: true) this._updateRef(true); } // destroy all children. i = this.$children.length; while (i--) { this.$children[i].$destroy(); } // teardown props if (this._propsUnlinkFn) { this._propsUnlinkFn(); } // teardown all directives. this also tearsdown all // directive-owned watchers. if (this._unlinkFn) { this._unlinkFn(); } i = this._watchers.length; while (i--) { this._watchers[i].teardown(); } // remove reference to self on $el if (this.$el) { this.$el.__vue__ = null; } destroyReady = true; cleanupIfPossible(); }; /** * Clean up to ensure garbage collection. * This is called after the leave transition if there * is any. */ Vue.prototype._cleanup = function () { if (this._isDestroyed) { return; } // remove self from owner fragment // do it in cleanup so that we can call $destroy with // defer right when a fragment is about to be removed. if (this._frag) { this._frag.children.$remove(this); } // remove reference from data ob // frozen object may not have observer. if (this._data && this._data.__ob__) { this._data.__ob__.removeVm(this); } // Clean up references to private properties and other // instances. preserve reference to _data so that proxy // accessors still work. The only potential side effect // here is that mutating the instance after it's destroyed // may affect the state of other components that are still // observing the same object, but that seems to be a // reasonable responsibility for the user rather than // always throwing an error on them. this.$el = this.$parent = this.$root = this.$children = this._watchers = this._context = this._scope = this._directives = null; // call the last hook... this._isDestroyed = true; this._callHook('destroyed'); // turn off all instance listeners. this.$off(); }; } function miscMixin (Vue) { /** * Apply a list of filter (descriptors) to a value. * Using plain for loops here because this will be called in * the getter of any watcher with filters so it is very * performance sensitive. * * @param {*} value * @param {*} [oldValue] * @param {Array} filters * @param {Boolean} write * @return {*} */ Vue.prototype._applyFilters = function (value, oldValue, filters, write) { var filter, fn, args, arg, offset, i, l, j, k; for (i = 0, l = filters.length; i < l; i++) { filter = filters[write ? l - i - 1 : i]; fn = resolveAsset(this.$options, 'filters', filter.name, true); if (!fn) continue; fn = write ? fn.write : fn.read || fn; if (typeof fn !== 'function') continue; args = write ? [value, oldValue] : [value]; offset = write ? 2 : 1; if (filter.args) { for (j = 0, k = filter.args.length; j < k; j++) { arg = filter.args[j]; args[j + offset] = arg.dynamic ? this.$get(arg.value) : arg.value; } } value = fn.apply(this, args); } return value; }; /** * Resolve a component, depending on whether the component * is defined normally or using an async factory function. * Resolves synchronously if already resolved, otherwise * resolves asynchronously and caches the resolved * constructor on the factory. * * @param {String|Function} value * @param {Function} cb */ Vue.prototype._resolveComponent = function (value, cb) { var factory; if (typeof value === 'function') { factory = value; } else { factory = resolveAsset(this.$options, 'components', value, true); } /* istanbul ignore if */ if (!factory) { return; } // async component factory if (!factory.options) { if (factory.resolved) { // cached cb(factory.resolved); } else if (factory.requested) { // pool callbacks factory.pendingCallbacks.push(cb); } else { factory.requested = true; var cbs = factory.pendingCallbacks = [cb]; factory.call(this, function resolve(res) { if (isPlainObject(res)) { res = Vue.extend(res); } // cache resolved factory.resolved = res; // invoke callbacks for (var i = 0, l = cbs.length; i < l; i++) { cbs[i](res); } }, function reject(reason) { 'development' !== 'production' && warn('Failed to resolve async component' + (typeof value === 'string' ? ': ' + value : '') + '. ' + (reason ? '\nReason: ' + reason : '')); }); } } else { // normal component cb(factory); } }; } var filterRE$1 = /[^|]\|[^|]/; function dataAPI (Vue) { /** * Get the value from an expression on this vm. * * @param {String} exp * @param {Boolean} [asStatement] * @return {*} */ Vue.prototype.$get = function (exp, asStatement) { var res = parseExpression(exp); if (res) { if (asStatement) { var self = this; return function statementHandler() { self.$arguments = toArray(arguments); var result = res.get.call(self, self); self.$arguments = null; return result; }; } else { try { return res.get.call(this, this); } catch (e) {} } } }; /** * Set the value from an expression on this vm. * The expression must be a valid left-hand * expression in an assignment. * * @param {String} exp * @param {*} val */ Vue.prototype.$set = function (exp, val) { var res = parseExpression(exp, true); if (res && res.set) { res.set.call(this, this, val); } }; /** * Delete a property on the VM * * @param {String} key */ Vue.prototype.$delete = function (key) { del(this._data, key); }; /** * Watch an expression, trigger callback when its * value changes. * * @param {String|Function} expOrFn * @param {Function} cb * @param {Object} [options] * - {Boolean} deep * - {Boolean} immediate * @return {Function} - unwatchFn */ Vue.prototype.$watch = function (expOrFn, cb, options) { var vm = this; var parsed; if (typeof expOrFn === 'string') { parsed = parseDirective(expOrFn); expOrFn = parsed.expression; } var watcher = new Watcher(vm, expOrFn, cb, { deep: options && options.deep, sync: options && options.sync, filters: parsed && parsed.filters, user: !options || options.user !== false }); if (options && options.immediate) { cb.call(vm, watcher.value); } return function unwatchFn() { watcher.teardown(); }; }; /** * Evaluate a text directive, including filters. * * @param {String} text * @param {Boolean} [asStatement] * @return {String} */ Vue.prototype.$eval = function (text, asStatement) { // check for filters. if (filterRE$1.test(text)) { var dir = parseDirective(text); // the filter regex check might give false positive // for pipes inside strings, so it's possible that // we don't get any filters here var val = this.$get(dir.expression, asStatement); return dir.filters ? this._applyFilters(val, null, dir.filters) : val; } else { // no filter return this.$get(text, asStatement); } }; /** * Interpolate a piece of template text. * * @param {String} text * @return {String} */ Vue.prototype.$interpolate = function (text) { var tokens = parseText(text); var vm = this; if (tokens) { if (tokens.length === 1) { return vm.$eval(tokens[0].value) + ''; } else { return tokens.map(function (token) { return token.tag ? vm.$eval(token.value) : token.value; }).join(''); } } else { return text; } }; /** * Log instance data as a plain JS object * so that it is easier to inspect in console. * This method assumes console is available. * * @param {String} [path] */ Vue.prototype.$log = function (path) { var data = path ? getPath(this._data, path) : this._data; if (data) { data = clean(data); } // include computed fields if (!path) { var key; for (key in this.$options.computed) { data[key] = clean(this[key]); } if (this._props) { for (key in this._props) { data[key] = clean(this[key]); } } } console.log(data); }; /** * "clean" a getter/setter converted object into a plain * object copy. * * @param {Object} - obj * @return {Object} */ function clean(obj) { return JSON.parse(JSON.stringify(obj)); } } function domAPI (Vue) { /** * Convenience on-instance nextTick. The callback is * auto-bound to the instance, and this avoids component * modules having to rely on the global Vue. * * @param {Function} fn */ Vue.prototype.$nextTick = function (fn) { nextTick(fn, this); }; /** * Append instance to target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$appendTo = function (target, cb, withTransition) { return insert(this, target, cb, withTransition, append, appendWithTransition); }; /** * Prepend instance to target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$prependTo = function (target, cb, withTransition) { target = query(target); if (target.hasChildNodes()) { this.$before(target.firstChild, cb, withTransition); } else { this.$appendTo(target, cb, withTransition); } return this; }; /** * Insert instance before target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$before = function (target, cb, withTransition) { return insert(this, target, cb, withTransition, beforeWithCb, beforeWithTransition); }; /** * Insert instance after target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$after = function (target, cb, withTransition) { target = query(target); if (target.nextSibling) { this.$before(target.nextSibling, cb, withTransition); } else { this.$appendTo(target.parentNode, cb, withTransition); } return this; }; /** * Remove instance from DOM * * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$remove = function (cb, withTransition) { if (!this.$el.parentNode) { return cb && cb(); } var inDocument = this._isAttached && inDoc(this.$el); // if we are not in document, no need to check // for transitions if (!inDocument) withTransition = false; var self = this; var realCb = function realCb() { if (inDocument) self._callHook('detached'); if (cb) cb(); }; if (this._isFragment) { removeNodeRange(this._fragmentStart, this._fragmentEnd, this, this._fragment, realCb); } else { var op = withTransition === false ? removeWithCb : removeWithTransition; op(this.$el, this, realCb); } return this; }; /** * Shared DOM insertion function. * * @param {Vue} vm * @param {Element} target * @param {Function} [cb] * @param {Boolean} [withTransition] * @param {Function} op1 - op for non-transition insert * @param {Function} op2 - op for transition insert * @return vm */ function insert(vm, target, cb, withTransition, op1, op2) { target = query(target); var targetIsDetached = !inDoc(target); var op = withTransition === false || targetIsDetached ? op1 : op2; var shouldCallHook = !targetIsDetached && !vm._isAttached && !inDoc(vm.$el); if (vm._isFragment) { mapNodeRange(vm._fragmentStart, vm._fragmentEnd, function (node) { op(node, target, vm); }); cb && cb(); } else { op(vm.$el, target, vm, cb); } if (shouldCallHook) { vm._callHook('attached'); } return vm; } /** * Check for selectors * * @param {String|Element} el */ function query(el) { return typeof el === 'string' ? document.querySelector(el) : el; } /** * Append operation that takes a callback. * * @param {Node} el * @param {Node} target * @param {Vue} vm - unused * @param {Function} [cb] */ function append(el, target, vm, cb) { target.appendChild(el); if (cb) cb(); } /** * InsertBefore operation that takes a callback. * * @param {Node} el * @param {Node} target * @param {Vue} vm - unused * @param {Function} [cb] */ function beforeWithCb(el, target, vm, cb) { before(el, target); if (cb) cb(); } /** * Remove operation that takes a callback. * * @param {Node} el * @param {Vue} vm - unused * @param {Function} [cb] */ function removeWithCb(el, vm, cb) { remove(el); if (cb) cb(); } } function eventsAPI (Vue) { /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn */ Vue.prototype.$on = function (event, fn) { (this._events[event] || (this._events[event] = [])).push(fn); modifyListenerCount(this, event, 1); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn */ Vue.prototype.$once = function (event, fn) { var self = this; function on() { self.$off(event, on); fn.apply(this, arguments); } on.fn = fn; this.$on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn */ Vue.prototype.$off = function (event, fn) { var cbs; // all if (!arguments.length) { if (this.$parent) { for (event in this._events) { cbs = this._events[event]; if (cbs) { modifyListenerCount(this, event, -cbs.length); } } } this._events = {}; return this; } // specific event cbs = this._events[event]; if (!cbs) { return this; } if (arguments.length === 1) { modifyListenerCount(this, event, -cbs.length); this._events[event] = null; return this; } // specific handler var cb; var i = cbs.length; while (i--) { cb = cbs[i]; if (cb === fn || cb.fn === fn) { modifyListenerCount(this, event, -1); cbs.splice(i, 1); break; } } return this; }; /** * Trigger an event on self. * * @param {String|Object} event * @return {Boolean} shouldPropagate */ Vue.prototype.$emit = function (event) { var isSource = typeof event === 'string'; event = isSource ? event : event.name; var cbs = this._events[event]; var shouldPropagate = isSource || !cbs; if (cbs) { cbs = cbs.length > 1 ? toArray(cbs) : cbs; // this is a somewhat hacky solution to the question raised // in #2102: for an inline component listener like <comp @test="doThis">, // the propagation handling is somewhat broken. Therefore we // need to treat these inline callbacks differently. var hasParentCbs = isSource && cbs.some(function (cb) { return cb._fromParent; }); if (hasParentCbs) { shouldPropagate = false; } var args = toArray(arguments, 1); for (var i = 0, l = cbs.length; i < l; i++) { var cb = cbs[i]; var res = cb.apply(this, args); if (res === true && (!hasParentCbs || cb._fromParent)) { shouldPropagate = true; } } } return shouldPropagate; }; /** * Recursively broadcast an event to all children instances. * * @param {String|Object} event * @param {...*} additional arguments */ Vue.prototype.$broadcast = function (event) { var isSource = typeof event === 'string'; event = isSource ? event : event.name; // if no child has registered for this event, // then there's no need to broadcast. if (!this._eventsCount[event]) return; var children = this.$children; var args = toArray(arguments); if (isSource) { // use object event to indicate non-source emit // on children args[0] = { name: event, source: this }; } for (var i = 0, l = children.length; i < l; i++) { var child = children[i]; var shouldPropagate = child.$emit.apply(child, args); if (shouldPropagate) { child.$broadcast.apply(child, args); } } return this; }; /** * Recursively propagate an event up the parent chain. * * @param {String} event * @param {...*} additional arguments */ Vue.prototype.$dispatch = function (event) { var shouldPropagate = this.$emit.apply(this, arguments); if (!shouldPropagate) return; var parent = this.$parent; var args = toArray(arguments); // use object event to indicate non-source emit // on parents args[0] = { name: event, source: this }; while (parent) { shouldPropagate = parent.$emit.apply(parent, args); parent = shouldPropagate ? parent.$parent : null; } return this; }; /** * Modify the listener counts on all parents. * This bookkeeping allows $broadcast to return early when * no child has listened to a certain event. * * @param {Vue} vm * @param {String} event * @param {Number} count */ var hookRE = /^hook:/; function modifyListenerCount(vm, event, count) { var parent = vm.$parent; // hooks do not get broadcasted so no need // to do bookkeeping for them if (!parent || !count || hookRE.test(event)) return; while (parent) { parent._eventsCount[event] = (parent._eventsCount[event] || 0) + count; parent = parent.$parent; } } } function lifecycleAPI (Vue) { /** * Set instance target element and kick off the compilation * process. The passed in `el` can be a selector string, an * existing Element, or a DocumentFragment (for block * instances). * * @param {Element|DocumentFragment|string} el * @public */ Vue.prototype.$mount = function (el) { if (this._isCompiled) { 'development' !== 'production' && warn('$mount() should be called only once.', this); return; } el = query(el); if (!el) { el = document.createElement('div'); } this._compile(el); this._initDOMHooks(); if (inDoc(this.$el)) { this._callHook('attached'); ready.call(this); } else { this.$once('hook:attached', ready); } return this; }; /** * Mark an instance as ready. */ function ready() { this._isAttached = true; this._isReady = true; this._callHook('ready'); } /** * Teardown the instance, simply delegate to the internal * _destroy. * * @param {Boolean} remove * @param {Boolean} deferCleanup */ Vue.prototype.$destroy = function (remove, deferCleanup) { this._destroy(remove, deferCleanup); }; /** * Partially compile a piece of DOM and return a * decompile function. * * @param {Element|DocumentFragment} el * @param {Vue} [host] * @param {Object} [scope] * @param {Fragment} [frag] * @return {Function} */ Vue.prototype.$compile = function (el, host, scope, frag) { return compile(el, this.$options, true)(this, el, host, scope, frag); }; } /** * The exposed Vue constructor. * * API conventions: * - public API methods/properties are prefixed with `$` * - internal methods/properties are prefixed with `_` * - non-prefixed properties are assumed to be proxied user * data. * * @constructor * @param {Object} [options] * @public */ function Vue(options) { this._init(options); } // install internals initMixin(Vue); stateMixin(Vue); eventsMixin(Vue); lifecycleMixin(Vue); miscMixin(Vue); // install instance APIs dataAPI(Vue); domAPI(Vue); eventsAPI(Vue); lifecycleAPI(Vue); var slot = { priority: SLOT, params: ['name'], bind: function bind() { // this was resolved during component transclusion var name = this.params.name || 'default'; var content = this.vm._slotContents && this.vm._slotContents[name]; if (!content || !content.hasChildNodes()) { this.fallback(); } else { this.compile(content.cloneNode(true), this.vm._context, this.vm); } }, compile: function compile(content, context, host) { if (content && context) { if (this.el.hasChildNodes() && content.childNodes.length === 1 && content.childNodes[0].nodeType === 1 && content.childNodes[0].hasAttribute('v-if')) { // if the inserted slot has v-if // inject fallback content as the v-else var elseBlock = document.createElement('template'); elseBlock.setAttribute('v-else', ''); elseBlock.innerHTML = this.el.innerHTML; // the else block should be compiled in child scope elseBlock._context = this.vm; content.appendChild(elseBlock); } var scope = host ? host._scope : this._scope; this.unlink = context.$compile(content, host, scope, this._frag); } if (content) { replace(this.el, content); } else { remove(this.el); } }, fallback: function fallback() { this.compile(extractContent(this.el, true), this.vm); }, unbind: function unbind() { if (this.unlink) { this.unlink(); } } }; var partial = { priority: PARTIAL, params: ['name'], // watch changes to name for dynamic partials paramWatchers: { name: function name(value) { vIf.remove.call(this); if (value) { this.insert(value); } } }, bind: function bind() { this.anchor = createAnchor('v-partial'); replace(this.el, this.anchor); this.insert(this.params.name); }, insert: function insert(id) { var partial = resolveAsset(this.vm.$options, 'partials', id, true); if (partial) { this.factory = new FragmentFactory(this.vm, partial); vIf.insert.call(this); } }, unbind: function unbind() { if (this.frag) { this.frag.destroy(); } } }; var elementDirectives = { slot: slot, partial: partial }; var convertArray = vFor._postProcess; /** * Limit filter for arrays * * @param {Number} n * @param {Number} offset (Decimal expected) */ function limitBy(arr, n, offset) { offset = offset ? parseInt(offset, 10) : 0; n = toNumber(n); return typeof n === 'number' ? arr.slice(offset, offset + n) : arr; } /** * Filter filter for arrays * * @param {String} search * @param {String} [delimiter] * @param {String} ...dataKeys */ function filterBy(arr, search, delimiter) { arr = convertArray(arr); if (search == null) { return arr; } if (typeof search === 'function') { return arr.filter(search); } // cast to lowercase string search = ('' + search).toLowerCase(); // allow optional `in` delimiter // because why not var n = delimiter === 'in' ? 3 : 2; // extract and flatten keys var keys = Array.prototype.concat.apply([], toArray(arguments, n)); var res = []; var item, key, val, j; for (var i = 0, l = arr.length; i < l; i++) { item = arr[i]; val = item && item.$value || item; j = keys.length; if (j) { while (j--) { key = keys[j]; if (key === '$key' && contains(item.$key, search) || contains(getPath(val, key), search)) { res.push(item); break; } } } else if (contains(item, search)) { res.push(item); } } return res; } /** * Filter filter for arrays * * @param {String|Array<String>|Function} ...sortKeys * @param {Number} [order] */ function orderBy(arr) { var comparator = null; var sortKeys = undefined; arr = convertArray(arr); // determine order (last argument) var args = toArray(arguments, 1); var order = args[args.length - 1]; if (typeof order === 'number') { order = order < 0 ? -1 : 1; args = args.length > 1 ? args.slice(0, -1) : args; } else { order = 1; } // determine sortKeys & comparator var firstArg = args[0]; if (!firstArg) { return arr; } else if (typeof firstArg === 'function') { // custom comparator comparator = function (a, b) { return firstArg(a, b) * order; }; } else { // string keys. flatten first sortKeys = Array.prototype.concat.apply([], args); comparator = function (a, b, i) { i = i || 0; return i >= sortKeys.length - 1 ? baseCompare(a, b, i) : baseCompare(a, b, i) || comparator(a, b, i + 1); }; } function baseCompare(a, b, sortKeyIndex) { var sortKey = sortKeys[sortKeyIndex]; if (sortKey) { if (sortKey !== '$key') { if (isObject(a) && '$value' in a) a = a.$value; if (isObject(b) && '$value' in b) b = b.$value; } a = isObject(a) ? getPath(a, sortKey) : a; b = isObject(b) ? getPath(b, sortKey) : b; } return a === b ? 0 : a > b ? order : -order; } // sort on a copy to avoid mutating original array return arr.slice().sort(comparator); } /** * String contain helper * * @param {*} val * @param {String} search */ function contains(val, search) { var i; if (isPlainObject(val)) { var keys = Object.keys(val); i = keys.length; while (i--) { if (contains(val[keys[i]], search)) { return true; } } } else if (isArray(val)) { i = val.length; while (i--) { if (contains(val[i], search)) { return true; } } } else if (val != null) { return val.toString().toLowerCase().indexOf(search) > -1; } } var digitsRE = /(\d{3})(?=\d)/g; // asset collections must be a plain object. var filters = { orderBy: orderBy, filterBy: filterBy, limitBy: limitBy, /** * Stringify value. * * @param {Number} indent */ json: { read: function read(value, indent) { return typeof value === 'string' ? value : JSON.stringify(value, null, Number(indent) || 2); }, write: function write(value) { try { return JSON.parse(value); } catch (e) { return value; } } }, /** * 'abc' => 'Abc' */ capitalize: function capitalize(value) { if (!value && value !== 0) return ''; value = value.toString(); return value.charAt(0).toUpperCase() + value.slice(1); }, /** * 'abc' => 'ABC' */ uppercase: function uppercase(value) { return value || value === 0 ? value.toString().toUpperCase() : ''; }, /** * 'AbC' => 'abc' */ lowercase: function lowercase(value) { return value || value === 0 ? value.toString().toLowerCase() : ''; }, /** * 12345 => $12,345.00 * * @param {String} sign * @param {Number} decimals Decimal places */ currency: function currency(value, _currency, decimals) { value = parseFloat(value); if (!isFinite(value) || !value && value !== 0) return ''; _currency = _currency != null ? _currency : '$'; decimals = decimals != null ? decimals : 2; var stringified = Math.abs(value).toFixed(decimals); var _int = decimals ? stringified.slice(0, -1 - decimals) : stringified; var i = _int.length % 3; var head = i > 0 ? _int.slice(0, i) + (_int.length > 3 ? ',' : '') : ''; var _float = decimals ? stringified.slice(-1 - decimals) : ''; var sign = value < 0 ? '-' : ''; return sign + _currency + head + _int.slice(i).replace(digitsRE, '$1,') + _float; }, /** * 'item' => 'items' * * @params * an array of strings corresponding to * the single, double, triple ... forms of the word to * be pluralized. When the number to be pluralized * exceeds the length of the args, it will use the last * entry in the array. * * e.g. ['single', 'double', 'triple', 'multiple'] */ pluralize: function pluralize(value) { var args = toArray(arguments, 1); return args.length > 1 ? args[value % 10 - 1] || args[args.length - 1] : args[0] + (value === 1 ? '' : 's'); }, /** * Debounce a handler function. * * @param {Function} handler * @param {Number} delay = 300 * @return {Function} */ debounce: function debounce(handler, delay) { if (!handler) return; if (!delay) { delay = 300; } return _debounce(handler, delay); } }; function installGlobalAPI (Vue) { /** * Vue and every constructor that extends Vue has an * associated options object, which can be accessed during * compilation steps as `this.constructor.options`. * * These can be seen as the default options of every * Vue instance. */ Vue.options = { directives: directives, elementDirectives: elementDirectives, filters: filters, transitions: {}, components: {}, partials: {}, replace: true }; /** * Expose useful internals */ Vue.util = util; Vue.config = config; Vue.set = set; Vue['delete'] = del; Vue.nextTick = nextTick; /** * The following are exposed for advanced usage / plugins */ Vue.compiler = compiler; Vue.FragmentFactory = FragmentFactory; Vue.internalDirectives = internalDirectives; Vue.parsers = { path: path, text: text, template: template, directive: directive, expression: expression }; /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ Vue.cid = 0; var cid = 1; /** * Class inheritance * * @param {Object} extendOptions */ Vue.extend = function (extendOptions) { extendOptions = extendOptions || {}; var Super = this; var isFirstExtend = Super.cid === 0; if (isFirstExtend && extendOptions._Ctor) { return extendOptions._Ctor; } var name = extendOptions.name || Super.options.name; if ('development' !== 'production') { if (!/^[a-zA-Z][\w-]*$/.test(name)) { warn('Invalid component name: "' + name + '". Component names ' + 'can only contain alphanumeric characaters and the hyphen.'); name = null; } } var Sub = createClass(name || 'VueComponent'); Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub; Sub.cid = cid++; Sub.options = mergeOptions(Super.options, extendOptions); Sub['super'] = Super; // allow further extension Sub.extend = Super.extend; // create asset registers, so extended classes // can have their private assets too. config._assetTypes.forEach(function (type) { Sub[type] = Super[type]; }); // enable recursive self-lookup if (name) { Sub.options.components[name] = Sub; } // cache constructor if (isFirstExtend) { extendOptions._Ctor = Sub; } return Sub; }; /** * A function that returns a sub-class constructor with the * given name. This gives us much nicer output when * logging instances in the console. * * @param {String} name * @return {Function} */ function createClass(name) { /* eslint-disable no-new-func */ return new Function('return function ' + classify(name) + ' (options) { this._init(options) }')(); /* eslint-enable no-new-func */ } /** * Plugin system * * @param {Object} plugin */ Vue.use = function (plugin) { /* istanbul ignore if */ if (plugin.installed) { return; } // additional parameters var args = toArray(arguments, 1); args.unshift(this); if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args); } else { plugin.apply(null, args); } plugin.installed = true; return this; }; /** * Apply a global mixin by merging it into the default * options. */ Vue.mixin = function (mixin) { Vue.options = mergeOptions(Vue.options, mixin); }; /** * Create asset registration methods with the following * signature: * * @param {String} id * @param {*} definition */ config._assetTypes.forEach(function (type) { Vue[type] = function (id, definition) { if (!definition) { return this.options[type + 's'][id]; } else { /* istanbul ignore if */ if ('development' !== 'production') { if (type === 'component' && (commonTagRE.test(id) || reservedTagRE.test(id))) { warn('Do not use built-in or reserved HTML elements as component ' + 'id: ' + id); } } if (type === 'component' && isPlainObject(definition)) { definition.name = id; definition = Vue.extend(definition); } this.options[type + 's'][id] = definition; return definition; } }; }); // expose internal transition API extend(Vue.transition, transition); } installGlobalAPI(Vue); Vue.version = '1.0.24'; // devtools global hook /* istanbul ignore next */ setTimeout(function () { if (config.devtools) { if (devtools) { devtools.emit('init', Vue); } else if ('development' !== 'production' && inBrowser && /Chrome\/\d+/.test(window.navigator.userAgent)) { console.log('Download the Vue Devtools for a better development experience:\n' + 'path_to_url } } }, 0); return Vue; })); ```
/content/code_sandbox/public/vendor/vue/dist/vue.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
68,333
```javascript /*global module:false*/ module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: '<json:package.json>', meta: { banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' + }, concat: { dist: { src: ['<banner:meta.banner>', '<file_strip_banner:../src/<%= pkg.name %>.js>'], dest: '../<%= pkg.name %>.js' } }, min: { dist: { src: ['<banner:meta.banner>', '<config:concat.dist.dest>'], dest: '../<%= pkg.name %>.min.js' } }, qunit: { files: ['../test/**/*.html'] }, lint: { files: ['grunt.js', '../src/**/*.js', '../test/**/*.js'] }, watch: { files: '<config:lint.files>', tasks: 'lint qunit' }, jshint: { options: { curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, boss: true, eqnull: true, browser: true, laxcomma: true }, globals: { jQuery: true } }, uglify: {} }); // Default task. grunt.registerTask('default', 'lint qunit concat min'); }; ```
/content/code_sandbox/public/vendor/jquery-backstretch/grunt.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
372
```javascript /*! Backstretch - v2.0.4 - 2013-06-19 * path_to_url (function(a,d,p){a.fn.backstretch=function(c,b){(c===p||0===c.length)&&a.error("No images were supplied for Backstretch");0===a(d).scrollTop()&&d.scrollTo(0,0);return this.each(function(){var d=a(this),g=d.data("backstretch");if(g){if("string"==typeof c&&"function"==typeof g[c]){g[c](b);return}b=a.extend(g.options,b);g.destroy(!0)}g=new q(this,c,b);d.data("backstretch",g)})};a.backstretch=function(c,b){return a("body").backstretch(c,b).data("backstretch")};a.expr[":"].backstretch=function(c){return a(c).data("backstretch")!==p};a.fn.backstretch.defaults={centeredX:!0,centeredY:!0,duration:5E3,fade:0};var r={left:0,top:0,overflow:"hidden",margin:0,padding:0,height:"100%",width:"100%",zIndex:-999999},s={position:"absolute",display:"none",margin:0,padding:0,border:"none",width:"auto",height:"auto",maxHeight:"none",maxWidth:"none",zIndex:-999999},q=function(c,b,e){this.options=a.extend({},a.fn.backstretch.defaults,e||{});this.images=a.isArray(b)?b:[b];a.each(this.images,function(){a("<img />")[0].src=this});this.isBody=c===document.body;this.$container=a(c);this.$root=this.isBody?l?a(d):a(document):this.$container;c=this.$container.children(".backstretch").first();this.$wrap=c.length?c:a('<div class="backstretch"></div>').css(r).appendTo(this.$container);this.isBody||(c=this.$container.css("position"),b=this.$container.css("zIndex"),this.$container.css({position:"static"===c?"relative":c,zIndex:"auto"===b?0:b,background:"none"}),this.$wrap.css({zIndex:-999998}));this.$wrap.css({position:this.isBody&&l?"fixed":"absolute"});this.index=0;this.show(this.index);a(d).on("resize.backstretch",a.proxy(this.resize,this)).on("orientationchange.backstretch",a.proxy(function(){this.isBody&&0===d.pageYOffset&&(d.scrollTo(0,1),this.resize())},this))};q.prototype={resize:function(){try{var a={left:0,top:0},b=this.isBody?this.$root.width():this.$root.innerWidth(),e=b,g=this.isBody?d.innerHeight?d.innerHeight:this.$root.height():this.$root.innerHeight(),j=e/this.$img.data("ratio"),f;j>=g?(f=(j-g)/2,this.options.centeredY&&(a.top="-"+f+"px")):(j=g,e=j*this.$img.data("ratio"),f=(e-b)/2,this.options.centeredX&&(a.left="-"+f+"px"));this.$wrap.css({width:b,height:g}).find("img:not(.deleteable)").css({width:e,height:j}).css(a)}catch(h){}return this},show:function(c){if(!(Math.abs(c)>this.images.length-1)){var b=this,e=b.$wrap.find("img").addClass("deleteable"),d={relatedTarget:b.$container[0]};b.$container.trigger(a.Event("backstretch.before",d),[b,c]);this.index=c;clearInterval(b.interval);b.$img=a("<img />").css(s).bind("load",function(f){var h=this.width||a(f.target).width();f=this.height||a(f.target).height();a(this).data("ratio",h/f);a(this).fadeIn(b.options.speed||b.options.fade,function(){e.remove();b.paused||b.cycle();a(["after","show"]).each(function(){b.$container.trigger(a.Event("backstretch."+this,d),[b,c])})});b.resize()}).appendTo(b.$wrap);b.$img.attr("src",b.images[c]);return b}},next:function(){return this.show(this.index<this.images.length-1?this.index+1:0)},prev:function(){return this.show(0===this.index?this.images.length-1:this.index-1)},pause:function(){this.paused=!0;return this},resume:function(){this.paused=!1;this.next();return this},cycle:function(){1<this.images.length&&(clearInterval(this.interval),this.interval=setInterval(a.proxy(function(){this.paused||this.next()},this),this.options.duration));return this},destroy:function(c){a(d).off("resize.backstretch orientationchange.backstretch");clearInterval(this.interval);c||this.$wrap.remove();this.$container.removeData("backstretch")}};var l,f=navigator.userAgent,m=navigator.platform,e=f.match(/AppleWebKit\/([0-9]+)/),e=!!e&&e[1],h=f.match(/Fennec\/([0-9]+)/),h=!!h&&h[1],n=f.match(/Opera Mobi\/([0-9]+)/),t=!!n&&n[1],k=f.match(/MSIE ([0-9]+)/),k=!!k&&k[1];l=!((-1<m.indexOf("iPhone")||-1<m.indexOf("iPad")||-1<m.indexOf("iPod"))&&e&&534>e||d.operamini&&"[object OperaMini]"==={}.toString.call(d.operamini)||n&&7458>t||-1<f.indexOf("Android")&&e&&533>e||h&&6>h||"palmGetResource"in d&&e&&534>e||-1<f.indexOf("MeeGo")&&-1<f.indexOf("NokiaBrowser/8.5.0")||k&&6>=k)})(jQuery,window); ```
/content/code_sandbox/public/vendor/jquery-backstretch/jquery.backstretch.min.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
1,271
```javascript /*! Backstretch - v2.0.4 - 2013-06-19 * path_to_url ;(function ($, window, undefined) { 'use strict'; /* PLUGIN DEFINITION * ========================= */ $.fn.backstretch = function (images, options) { // We need at least one image or method name if (images === undefined || images.length === 0) { $.error("No images were supplied for Backstretch"); } /* * Scroll the page one pixel to get the right window height on iOS * Pretty harmless for everyone else */ if ($(window).scrollTop() === 0 ) { window.scrollTo(0, 0); } return this.each(function () { var $this = $(this) , obj = $this.data('backstretch'); // Do we already have an instance attached to this element? if (obj) { // Is this a method they're trying to execute? if (typeof images == 'string' && typeof obj[images] == 'function') { // Call the method obj[images](options); // No need to do anything further return; } // Merge the old options with the new options = $.extend(obj.options, options); // Remove the old instance obj.destroy(true); } obj = new Backstretch(this, images, options); $this.data('backstretch', obj); }); }; // If no element is supplied, we'll attach to body $.backstretch = function (images, options) { // Return the instance return $('body') .backstretch(images, options) .data('backstretch'); }; // Custom selector $.expr[':'].backstretch = function(elem) { return $(elem).data('backstretch') !== undefined; }; /* DEFAULTS * ========================= */ $.fn.backstretch.defaults = { centeredX: true // Should we center the image on the X axis? , centeredY: true // Should we center the image on the Y axis? , duration: 5000 // Amount of time in between slides (if slideshow) , fade: 0 // Speed of fade transition between slides }; /* STYLES * * Baked-in styles that we'll apply to our elements. * In an effort to keep the plugin simple, these are not exposed as options. * That said, anyone can override these in their own stylesheet. * ========================= */ var styles = { wrap: { left: 0 , top: 0 , overflow: 'hidden' , margin: 0 , padding: 0 , height: '100%' , width: '100%' , zIndex: -999999 } , img: { position: 'absolute' , display: 'none' , margin: 0 , padding: 0 , border: 'none' , width: 'auto' , height: 'auto' , maxHeight: 'none' , maxWidth: 'none' , zIndex: -999999 } }; /* CLASS DEFINITION * ========================= */ var Backstretch = function (container, images, options) { this.options = $.extend({}, $.fn.backstretch.defaults, options || {}); /* In its simplest form, we allow Backstretch to be called on an image path. * e.g. $.backstretch('/path/to/image.jpg') * So, we need to turn this back into an array. */ this.images = $.isArray(images) ? images : [images]; // Preload images $.each(this.images, function () { $('<img />')[0].src = this; }); // Convenience reference to know if the container is body. this.isBody = container === document.body; /* We're keeping track of a few different elements * * Container: the element that Backstretch was called on. * Wrap: a DIV that we place the image into, so we can hide the overflow. * Root: Convenience reference to help calculate the correct height. */ this.$container = $(container); this.$root = this.isBody ? supportsFixedPosition ? $(window) : $(document) : this.$container; // Don't create a new wrap if one already exists (from a previous instance of Backstretch) var $existing = this.$container.children(".backstretch").first(); this.$wrap = $existing.length ? $existing : $('<div class="backstretch"></div>').css(styles.wrap).appendTo(this.$container); // Non-body elements need some style adjustments if (!this.isBody) { // If the container is statically positioned, we need to make it relative, // and if no zIndex is defined, we should set it to zero. var position = this.$container.css('position') , zIndex = this.$container.css('zIndex'); this.$container.css({ position: position === 'static' ? 'relative' : position , zIndex: zIndex === 'auto' ? 0 : zIndex , background: 'none' }); // Needs a higher z-index this.$wrap.css({zIndex: -999998}); } // Fixed or absolute positioning? this.$wrap.css({ position: this.isBody && supportsFixedPosition ? 'fixed' : 'absolute' }); // Set the first image this.index = 0; this.show(this.index); // Listen for resize $(window).on('resize.backstretch', $.proxy(this.resize, this)) .on('orientationchange.backstretch', $.proxy(function () { // Need to do this in order to get the right window height if (this.isBody && window.pageYOffset === 0) { window.scrollTo(0, 1); this.resize(); } }, this)); }; /* PUBLIC METHODS * ========================= */ Backstretch.prototype = { resize: function () { try { var bgCSS = {left: 0, top: 0} , rootWidth = this.isBody ? this.$root.width() : this.$root.innerWidth() , bgWidth = rootWidth , rootHeight = this.isBody ? ( window.innerHeight ? window.innerHeight : this.$root.height() ) : this.$root.innerHeight() , bgHeight = bgWidth / this.$img.data('ratio') , bgOffset; // Make adjustments based on image ratio if (bgHeight >= rootHeight) { bgOffset = (bgHeight - rootHeight) / 2; if(this.options.centeredY) { bgCSS.top = '-' + bgOffset + 'px'; } } else { bgHeight = rootHeight; bgWidth = bgHeight * this.$img.data('ratio'); bgOffset = (bgWidth - rootWidth) / 2; if(this.options.centeredX) { bgCSS.left = '-' + bgOffset + 'px'; } } this.$wrap.css({width: rootWidth, height: rootHeight}) .find('img:not(.deleteable)').css({width: bgWidth, height: bgHeight}).css(bgCSS); } catch(err) { // IE7 seems to trigger resize before the image is loaded. // This try/catch block is a hack to let it fail gracefully. } return this; } // Show the slide at a certain position , show: function (newIndex) { // Validate index if (Math.abs(newIndex) > this.images.length - 1) { return; } // Vars var self = this , oldImage = self.$wrap.find('img').addClass('deleteable') , evtOptions = { relatedTarget: self.$container[0] }; // Trigger the "before" event self.$container.trigger($.Event('backstretch.before', evtOptions), [self, newIndex]); // Set the new index this.index = newIndex; // Pause the slideshow clearInterval(self.interval); // New image self.$img = $('<img />') .css(styles.img) .bind('load', function (e) { var imgWidth = this.width || $(e.target).width() , imgHeight = this.height || $(e.target).height(); // Save the ratio $(this).data('ratio', imgWidth / imgHeight); // Show the image, then delete the old one // "speed" option has been deprecated, but we want backwards compatibilty $(this).fadeIn(self.options.speed || self.options.fade, function () { oldImage.remove(); // Resume the slideshow if (!self.paused) { self.cycle(); } // Trigger the "after" and "show" events // "show" is being deprecated $(['after', 'show']).each(function () { self.$container.trigger($.Event('backstretch.' + this, evtOptions), [self, newIndex]); }); }); // Resize self.resize(); }) .appendTo(self.$wrap); // Hack for IE img onload event self.$img.attr('src', self.images[newIndex]); return self; } , next: function () { // Next slide return this.show(this.index < this.images.length - 1 ? this.index + 1 : 0); } , prev: function () { // Previous slide return this.show(this.index === 0 ? this.images.length - 1 : this.index - 1); } , pause: function () { // Pause the slideshow this.paused = true; return this; } , resume: function () { // Resume the slideshow this.paused = false; this.next(); return this; } , cycle: function () { // Start/resume the slideshow if(this.images.length > 1) { // Clear the interval, just in case clearInterval(this.interval); this.interval = setInterval($.proxy(function () { // Check for paused slideshow if (!this.paused) { this.next(); } }, this), this.options.duration); } return this; } , destroy: function (preserveBackground) { // Stop the resize events $(window).off('resize.backstretch orientationchange.backstretch'); // Clear the interval clearInterval(this.interval); // Remove Backstretch if(!preserveBackground) { this.$wrap.remove(); } this.$container.removeData('backstretch'); } }; /* SUPPORTS FIXED POSITION? * * Based on code from jQuery Mobile 1.1.0 * path_to_url * * In a nutshell, we need to figure out if fixed positioning is supported. * Unfortunately, this is very difficult to do on iOS, and usually involves * injecting content, scrolling the page, etc.. It's ugly. * jQuery Mobile uses this workaround. It's not ideal, but works. * * Modified to detect IE6 * ========================= */ var supportsFixedPosition = (function () { var ua = navigator.userAgent , platform = navigator.platform // Rendering engine is Webkit, and capture major version , wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ) , wkversion = !!wkmatch && wkmatch[ 1 ] , ffmatch = ua.match( /Fennec\/([0-9]+)/ ) , ffversion = !!ffmatch && ffmatch[ 1 ] , operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ ) , omversion = !!operammobilematch && operammobilematch[ 1 ] , iematch = ua.match( /MSIE ([0-9]+)/ ) , ieversion = !!iematch && iematch[ 1 ]; return !( // iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5) ((platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534) || // Opera Mini (window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]") || (operammobilematch && omversion < 7458) || //Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2) (ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533) || // Firefox Mobile before 6.0 - (ffversion && ffversion < 6) || // WebOS less than 3 ("palmGetResource" in window && wkversion && wkversion < 534) || // MeeGo (ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1) || // IE6 (ieversion && ieversion <= 6) ); }()); }(jQuery, window)); ```
/content/code_sandbox/public/vendor/jquery-backstretch/jquery.backstretch.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
2,910
```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Backstretch Test Suite</title> <!-- Load local jQuery. This can be overridden with a ?jquery=___ param. --> <script src="../libs/jquery-loader.js"></script> <!-- Load local QUnit (grunt requires v1.0.0 or newer). --> <link rel="stylesheet" href="../libs/qunit/qunit.css" media="screen"> <script src="../libs/qunit/qunit.js"></script> <!-- Load local lib and tests. --> <script src="../src/jquery.backstretch.js"></script> <script src="backstretch_test.js"></script> <!-- Removing access to jQuery and $. But it'll still be available as _$, if you REALLY want to mess around with jQuery in the console. REMEMBER WE ARE TESTING YOUR PLUGIN HERE --> <script>window._$ = jQuery.noConflict(true);</script> </head> <body> <h1 id="qunit-header">Backstretch Test Suite</h1> <h2 id="qunit-banner"></h2> <div id="qunit-testrunner-toolbar"></div> <h2 id="qunit-userAgent"></h2> <ol id="qunit-tests"></ol> <div id="qunit-fixture"> <span>lame test markup</span> <span>normal test markup</span> <span>awesome test markup</span> </div> </body> </html> ```
/content/code_sandbox/public/vendor/jquery-backstretch/test/backstretch.html
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
330
```javascript /*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/ /*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/ /*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/ (function($) { /* ======== A Handy Little QUnit Reference ======== path_to_url Test methods: expect(numAssertions) stop(increment) start(decrement) Test assertions: ok(value, [message]) equal(actual, expected, [message]) notEqual(actual, expected, [message]) deepEqual(actual, expected, [message]) notDeepEqual(actual, expected, [message]) strictEqual(actual, expected, [message]) notStrictEqual(actual, expected, [message]) raises(block, [expected], [message]) */ var global = { elems: $('#qunit-fixture').children() , img1: 'image1.jpg' , img2: 'image2.jpg' , destroy: function () { try { $(':backstretch').data('backstretch').destroy(); } catch(err) { /* Do nothing */ } } }; /* Backstretch tests * ========================= */ module('Backstretch', { teardown: global.destroy }); test('instantiation', function () { strictEqual(global.elems.backstretch(global.img1), global.elems, 'chaninable when executed on elements'); strictEqual($.backstretch(global.img1).constructor, Object, 'returns Backstretch object'); }); test('images', function () { raises(function() { $.backstretch(); }, 'raise an error when no image is supplied'); raises(function() { $.backstretch([]); }, 'raise an error when an empty image array is supplied'); }); test('options', function () { // Make sure previous instances are destroyed global.destroy(); var duration = 999999 , instance = $.backstretch(global.img1, {duration: duration}); // Test to make sure the options are being set strictEqual(instance.options.duration, duration, 'passed options are being set'); }); }(jQuery)); ```
/content/code_sandbox/public/vendor/jquery-backstretch/test/backstretch_test.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
469
```javascript (function() { // Get any jquery=___ param from the query string. var jqversion = location.search.match(/[?&]jquery=(.*?)(?=&|$)/); var path; if (jqversion) { // A version was specified, load that version from code.jquery.com. path = 'path_to_url + jqversion[1] + '.js'; } else { // No version was specified, load the local version. path = '../libs/jquery/jquery.js'; } // This is the only time I'll ever use document.write, I promise! document.write('<script src="' + path + '"></script>'); }()); ```
/content/code_sandbox/public/vendor/jquery-backstretch/libs/jquery-loader.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
141
```javascript /*! * jQuery JavaScript Library v1.8.3 * path_to_url * * Includes Sizzle.js * path_to_url * * Released under the MIT license * path_to_url * * Date: Tue Nov 13 2012 08:20:33 GMT-0500 (Eastern Standard Time) */ (function( window, undefined ) { var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, navigator = window.navigator, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Save a reference to some core methods core_push = Array.prototype.push, core_slice = Array.prototype.slice, core_indexOf = Array.prototype.indexOf, core_toString = Object.prototype.toString, core_hasOwn = Object.prototype.hasOwnProperty, core_trim = String.prototype.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source, // Used for detecting and trimming whitespace core_rnotwhite = /\S/, core_rspace = /\s+/, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return ( letter + "" ).toUpperCase(); }, // The ready event handler and self cleanup method DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; doc = ( context && context.nodeType ? context.ownerDocument || context : document ); // scripts is true for back-compat selector = jQuery.parseHTML( match[1], doc, true ); if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { this.attr.call( selector, context, true ); } return jQuery.merge( this, selector ); // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The current version of jQuery being used jquery: "1.8.3", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems, name, selector ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ), "slice", core_slice.call(arguments).join(",") ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready, 1 ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { return obj == null ? String( obj ) : class2type[ core_toString.call(obj) ] || "object"; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // scripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, scripts ) { var parsed; if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { scripts = context; context = 0; } context = context || document; // Single tag if ( (parsed = rsingleTag.exec( data )) ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] ); return jQuery.merge( [], (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes ); }, parseJSON: function( data ) { if ( !data || typeof data !== "string") { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from path_to_url if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // path_to_url globalEval: function( data ) { if ( data && core_rnotwhite.test( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var name, i = 0, length = obj.length, isObj = length === undefined || jQuery.isFunction( obj ); if ( args ) { if ( isObj ) { for ( name in obj ) { if ( callback.apply( obj[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( obj[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in obj ) { if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var type, ret = results || []; if ( arr != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 type = jQuery.type( arr ); if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) { core_push.call( ret, arr ); } else { jQuery.merge( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: path_to_url#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready, 1 ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // path_to_url top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.split( core_rspace ), function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Control if a given callback is in the list has: function( fn ) { return jQuery.inArray( fn, list ) > -1; }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ]( jQuery.isFunction( fn ) ? function() { var returned = fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); } } : newDefer[ action ] ); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] = list.fire deferred[ tuple[0] ] = list.fire; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, select, opt, input, fragment, eventName, i, isSupported, clickFn, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if ( !all || !a || !all.length ) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // IE strips leading whitespace when .innerHTML is used leadingWhitespace: ( div.firstChild.nodeType === 3 ), // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: ( a.getAttribute("href") === "/a" ), // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: ( document.compatMode === "CSS1Compat" ), // Will be defined later submitBubbles: true, changeBubbles: true, focusinBubbles: false, deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", clickFn = function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent("onclick"); div.detachEvent( "onclick", clickFn ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; input.setAttribute( "checked", "checked" ); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); // Technique from Juriy Zaytsev // path_to_url // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: path_to_url if ( div.attachEvent ) { for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } // Run tests that need a body at doc ready jQuery(function() { var container, div, tds, marginDiv, divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). // (only IE 8 fails this test) div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = document.createElement("div"); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; div.appendChild( marginDiv ); support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); container.style.zoom = 1; } // Null elements to avoid leaks in IE body.removeChild( container ); container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE fragment.removeChild( div ); all = a = select = opt = input = fragment = div = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, deletedIds: [], // Remove at next major release (1.9/2.0) uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var parts, part, attr, name, l, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.substring(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery.removeData( elem, type + "queue", true ); jQuery.removeData( elem, key, true ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // path_to_url delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, fixSpecified, rclass = /[\t\r\n]/g, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea|)$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var removes, className, elem, c, cl, i, l; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { removes = ( value || "" ).split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { className = (" " + elem.className + " ").replace( rclass, " " ); // loop over each item in the removal list for ( c = 0, cl = removes.length; c < cl; c++ ) { // Remove until there is nothing to remove, while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) { className = className.replace( " " + removes[ c ] + " " , " " ); } } elem.className = value ? jQuery.trim( className ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.split( core_rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9 attrFn: {}, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.split( core_rspace ); for ( ; i < attrNames.length; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = value; } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // path_to_url var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true, coords: true }; // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.value = value + "" ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret === null ? undefined : ret; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/, rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var t, tns, type, origType, namespaces, origCount, j, events, special, eventType, handleObj, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector? special.delegateType : special.bindType ) || type; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( eventType.length === 0 && origCount !== eventType.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery.removeData( elem, "events", true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, type = event.type || event, namespaces = []; // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "!" ) >= 0 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data != null ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; for ( old = elem; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old === (elem.ownerDocument || document) ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related, handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = core_slice.call( arguments ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = []; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(event.button && event.type === "click") ) { for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { selMatch = {}; matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8) event.metaKey = !!event.metaKey; return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === "undefined" ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; function returnFalse() { return false; } function returnTrue() { return true; } // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // path_to_url jQuery.Event.prototype = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj, selector = handleObj.selector; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "_submit_attached" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "_submit_attached", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "_change_attached", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // && selector != null // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Released under the MIT license * path_to_url */ (function( window, undefined ) { var cachedruns, assertGetIdNotName, Expr, getText, isXML, contains, compile, sortOrder, hasDuplicate, outermostContext, baseHasDuplicate = true, strundefined = "undefined", expando = ( "sizcache" + Math.random() ).replace( ".", "" ), Token = String, document = window.document, docElem = document.documentElement, dirruns = 0, done = 0, pop = [].pop, push = [].push, slice = [].slice, // Use a stripped-down indexOf if a native one is unavailable indexOf = [].indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Augment a function for special use by Sizzle markFunction = function( fn, value ) { fn[ expando ] = value == null || value; return fn; }, createCache = function() { var cache = {}, keys = []; return markFunction(function( key, value ) { // Only keep the most recent entries if ( keys.push( key ) > Expr.cacheLength ) { delete cache[ keys.shift() ]; } // Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157) return (cache[ key + " " ] = value); }, cache ); }, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // Regex // Whitespace characters path_to_url#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // path_to_url#characters characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier (path_to_url#attribute-selectors) // Proper syntax: path_to_url#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators path_to_url#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments not in parens/brackets, // then attribute selectors and non-pseudos (denoted by :), // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)", // For matchExpr.POS and matchExpr.needsContext pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, rnot = /^:not/, rsibling = /[\x20\t\r\n\f]*[+~]/, rendsWithNot = /:not\($/, rheader = /h\d/i, rinputs = /input|select|textarea|button/i, rbackslash = /\\(?!\\)/g, matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "POS": new RegExp( pos, "i" ), "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) }, // Support // Used for testing something on an element assert = function( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } }, // Check if getElementsByTagName("*") returns only elements assertTagNameNoComments = assert(function( div ) { div.appendChild( document.createComment("") ); return !div.getElementsByTagName("*").length; }), // Check if getAttribute returns normalized href attributes assertHrefNotNormalized = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }), // Check if attributes should be retrieved by attribute nodes assertAttributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }), // Check if getElementsByClassName can be trusted assertUsableClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }), // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID assertUsableName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = document.getElementsByName && // buggy browsers will return fewer than the correct 2 document.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 document.getElementsByName( expando + 0 ).length; assertGetIdNotName = !document.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // If slice is not available, provide a backup try { slice.call( docElem.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; for ( ; (elem = this[i]); i++ ) { results.push( elem ); } return results; }; } function Sizzle( selector, context, results, seed ) { results = results || []; context = context || document; var match, elem, xml, m, nodeType = context.nodeType; if ( !selector || typeof selector !== "string" ) { return results; } if ( nodeType !== 1 && nodeType !== 9 ) { return []; } xml = isXML( context ); if ( !xml && !seed ) { if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed, xml ); } Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { return Sizzle( expr, null, null, [ elem ] ).length > 0; }; // Returns a function to use in pseudos for input types function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } // Returns a function to use in pseudos for positionals function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( nodeType ) { if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes } else { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } return ret; }; isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Element contains another contains = Sizzle.contains = docElem.contains ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); } : docElem.compareDocumentPosition ? function( a, b ) { return b && !!( a.compareDocumentPosition( b ) & 16 ); } : function( a, b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } return false; }; Sizzle.attr = function( elem, name ) { var val, xml = isXML( elem ); if ( !xml ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( xml || assertAttributes ) { return elem.getAttribute( name ); } val = elem.getAttributeNode( name ); return val ? typeof elem[ name ] === "boolean" ? elem[ name ] ? name : null : val.specified ? val.value : null : null; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, // IE6/7 return a modified href attrHandle: assertHrefNotNormalized ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }, find: { "ID": assertGetIdNotName ? function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } } : function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }, "TAG": assertTagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { var elem, tmp = [], i = 0; for ( ; (elem = results[i]); i++ ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }, "NAME": assertUsableName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }, "CLASS": assertUsableClassName && function( className, context, xml ) { if ( typeof context.getElementsByClassName !== strundefined && !xml ) { return context.getElementsByClassName( className ); } } }, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( rbackslash, "" ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 3 xn-component of xn+y argument ([+-]?\d*n|) 4 sign of xn-component 5 x of xn-component 6 sign of y-component 7 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1] === "nth" ) { // nth-child requires argument if ( !match[2] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) ); match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" ); // other types prohibit arguments } else if ( match[2] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var unquoted, excess; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } if ( match[3] ) { match[2] = match[3]; } else if ( (unquoted = match[4]) ) { // Only check arguments that contain a pseudo if ( rpseudo.test(unquoted) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index unquoted = unquoted.slice( 0, excess ); match[0] = match[0].slice( 0, excess ); } match[2] = unquoted; } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "ID": assertGetIdNotName ? function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { return elem.getAttribute("id") === id; }; } : function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === id; }; }, "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( rbackslash, "" ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ expando ][ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem, context ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.substr( result.length - check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, argument, first, last ) { if ( type === "nth" ) { return function( elem ) { var node, diff, parent = elem.parentNode; if ( first === 1 && last === 0 ) { return true; } if ( parent ) { diff = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { diff++; if ( elem === node ) { break; } } } } // Incorporate the offset (or cast to NaN), then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); }; } return function( elem ) { var node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // path_to_url#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // path_to_url#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, "empty": function( elem ) { // path_to_url#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") var nodeType; elem = elem.firstChild; while ( elem ) { if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) { return false; } elem = elem.nextSibling; } return true; }, "header": function( elem ) { return rheader.test( elem.nodeName ); }, "text": function( elem ) { var type, attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && (type = elem.type) === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type ); }, // Input types "radio": createInputPseudo("radio"), "checkbox": createInputPseudo("checkbox"), "file": createInputPseudo("file"), "password": createInputPseudo("password"), "image": createInputPseudo("image"), "submit": createButtonPseudo("submit"), "reset": createButtonPseudo("reset"), "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "focus": function( elem ) { var doc = elem.ownerDocument; return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, "active": function( elem ) { return elem === elem.ownerDocument.activeElement; }, // Positional types "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { for ( var i = 0; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { for ( var i = 1; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; function siblingCheck( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; } sortOrder = docElem.compareDocumentPosition ? function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4 ) ? -1 : 1; } : function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). [0, 0].sort( sortOrder ); baseHasDuplicate = !hasDuplicate; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], i = 1, j = 0; hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ expando ][ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); // Cast descendant combinators to space matched.type = match[0].replace( rtrim, " " ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); matched.type = type; matched.matches = match; } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && combinator.dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( !xml ) { var cache, dirkey = dirruns + " " + doneName + " ", cachedkey = dirkey + cachedruns; while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( (cache = elem[ expando ]) === cachedkey ) { return elem.sizset; } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { if ( elem.sizset ) { return elem; } } else { elem[ expando ] = cachedkey; if ( matcher( elem, context, xml ) ) { elem.sizset = true; return elem; } elem.sizset = false; } } } } else { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( matcher( elem, context, xml ) ) { return elem; } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && tokens.join("") ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if ( outermost ) { outermostContext = context !== document && context; cachedruns = superMatcher.el; } // Add elements passing elementMatchers directly to results for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { for ( j = 0; (matcher = elementMatchers[j]); j++ ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++superMatcher.el; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { for ( j = 0; (matcher = setMatchers[j]); j++ ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; superMatcher.el = 0; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ expando ][ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed, xml ) { var i, tokens, token, type, find, match = tokenize( selector ), j = match.length; if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !xml && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().length ); } // Fetch a seed set for right-to-left matching for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( rbackslash, "" ), rsibling.test( tokens[0].type ) && context.parentNode || context, xml )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && tokens.join(""); if ( !selector ) { push.apply( results, slice.call( seed, 0 ) ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, xml, results, rsibling.test( selector ) ); return results; } if ( document.querySelectorAll ) { (function() { var disconnectedMatch, oldSelect = select, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ], // matchesSelector(:active) reports false when true (IE9/Opera 11.5) // A support test would require too much code (would include document ready) // just skip matchesSelector for :active rbuggyMatches = [ ":active" ], matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector; // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // path_to_url div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // path_to_url#checked // IE8 throws error here (do not put tests after this one) if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE9 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<p test=''></p>"; if ( div.querySelectorAll("[test^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here (do not put tests after this one) div.innerHTML = "<input type='hidden'/>"; if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push(":enabled", ":disabled"); } }); // rbuggyQSA always contains :focus, so no need for a length check rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") ); select = function( selector, context, results, seed, xml ) { // Only use querySelectorAll when not filtering, // when this is not xml, // and when no QSA bugs apply if ( !seed && !xml && !rbuggyQSA.test( selector ) ) { var groups, i, old = true, nid = expando, newContext = context, newSelector = context.nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + groups[i].join(""); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( newSelector ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } return oldSelect( selector, context, results, seed, xml ); }; if ( matches ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead try { matches.call( div, "[test!='']:sizzle" ); rbuggyMatches.push( "!=", pseudos ); } catch ( e ) {} }); // rbuggyMatches always contains :active and :focus, so no need for a length check rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); Sizzle.matchesSelector = function( elem, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyMatches always contains :active, so no need for an existence check if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, null, null, [ elem ] ).length > 0; }; } })(); } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Back-compat function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, l, length, n, r, ret, self = this; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } ret = this.pushStack( "", "find", selector ); for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret, name, core_slice.call( arguments ).join(",") ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem, i ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem, i ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rcheckableType = /^(?:checkbox|radio)$/, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "X<div>", "</div>" ]; } jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( set, this ), "before", this.selector ); } }, after: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( this, set ), "after", this.selector ); } }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName( "*" ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { if ( !isDisconnected( this[0] ) ) { // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = [].concat.apply( [], args ); var results, first, fragment, iNoClone, i = 0, value = args[0], scripts = [], l = this.length; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call( this, i, table ? self.html() : undefined ); self.domManip( args, table, callback ); }); } if ( this[0] ) { results = jQuery.buildFragment( args, this, scripts ); fragment = results.fragment; first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). // Fragments from the fragment cache must always be cloned and never used in place. for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) { callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], i === iNoClone ? fragment : jQuery.clone( fragment, true, true ) ); } } // Fix #11809: Avoid leaking memory fragment = first = null; if ( scripts.length ) { jQuery.each( scripts, function( i, elem ) { if ( elem.src ) { if ( jQuery.ajax ) { jQuery.ajax({ url: elem.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.error("no ajax"); } } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } }); } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); if ( nodeName === "object" ) { // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, context, scripts ) { var fragment, cacheable, cachehit, first = args[ 0 ]; // Set context from what may come in as undefined or a jQuery collection or a node // Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 & // also doubles as fix for #8950 where plain objects caused createDocumentFragment exception context = context || document; context = !context.nodeType && context[0] || context; context = context.ownerDocument || context; // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { // Mark cacheable and look for a hit cacheable = true; fragment = jQuery.fragments[ first ]; cachehit = fragment !== undefined; } if ( !fragment ) { fragment = context.createDocumentFragment(); jQuery.clean( args, context, fragment, scripts ); // Update the cache, but only store false // unless this is a second parsing of the same content if ( cacheable ) { jQuery.fragments[ first ] = cachehit && fragment; } } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), l = insert.length, parent = this.length === 1 && this[0].parentNode; if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( ; i < l; i++ ) { elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, clone; if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, safe = context === document && safeFragment, ret = []; // Ensure that context is a document if ( !context || typeof context.createDocumentFragment === "undefined" ) { context = document; } // Use the already-created safe fragment if context permits for ( i = 0; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Ensure a safe container in which to render the html safe = safe || createSafeFragment( context ); div = context.createElement("div"); safe.appendChild( div ); // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Go to html and back, then peel off extra wrappers tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; depth = wrap[0]; div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> hasBody = rtbody.test(elem); tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; // Take out of fragment container (we need a fresh div each time) div.parentNode.removeChild( div ); } } if ( elem.nodeType ) { ret.push( elem ); } else { jQuery.merge( ret, elem ); } } // Fix #11356: Clear elements from safeFragment if ( div ) { elem = div = safe = null; } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { for ( i = 0; (elem = ret[i]) != null; i++ ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } } // Append elements to a provided document fragment if ( fragment ) { // Special handling of each script element handleScript = function( elem ) { // Check if we consider it executable if ( !elem.type || rscriptType.test( elem.type ) ) { // Detach the script and store it in the scripts array (if provided) or the fragment // Return truthy to indicate that it has been handled return scripts ? scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : fragment.appendChild( elem ); } }; for ( i = 0; (elem = ret[i]) != null; i++ ) { // Check if we're done after handling an executable script if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { // Append to fragment and handle embedded scripts fragment.appendChild( elem ); if ( typeof elem.getElementsByTagName !== "undefined" ) { // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); // Splice the scripts into ret after their former ancestor and advance our index beyond them ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); i += jsTags.length; } } } } return ret; }, cleanData: function( elems, /* internal */ acceptData ) { var data, id, elem, type, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } jQuery.deletedIds.push( id ); } } } } } }); // Limit scope pollution from any deprecated API (function() { var matched, browser; // Use of jQuery.browser is frowned upon. // More details: path_to_url // jQuery.uaMatch maintained for back-compat jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; matched = jQuery.uaMatch( navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; } // Chrome is Webkit, but Webkit is also Safari. if ( browser.chrome ) { browser.webkit = true; } else if ( browser.webkit ) { browser.safari = true; } jQuery.browser = browser; jQuery.sub = function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }; })(); var curCSS, iframe, iframeDoc, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: path_to_url rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], eventsToggle = jQuery.fn.toggle; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var elem, display, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && elem.style.display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { display = curCSS( elem, "display" ); if ( !values[ index ] && display !== "none" ) { jQuery._data( elem, "olddisplay", display ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state, fn2 ) { var bool = typeof state === "boolean"; if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) { return eventsToggle.apply( this, arguments ); } return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Exclude the following css properties to add px cssNumber: { "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, numeric, extra ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( numeric || extra !== undefined ) { num = parseFloat( val ); return numeric || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { curCSS = function( elem, name ) { var ret, width, minWidth, maxWidth, computed = window.getComputedStyle( elem, null ), style = elem.style; if ( computed ) { // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: path_to_url#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { curCSS = function( elem, name ) { var left, rsLeft, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // path_to_url#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { // we use jQuery.css instead of curCSS here // because of the reliableMarginRight CSS hook! val += jQuery.css( elem, extra + cssExpand[ i ], true ); } // From this point on we use curCSS for maximum performance (relevant in animations) if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } else { // at this point, extra isn't content, so add padding val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, valueIsBorderBox = true, isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - path_to_url // MathML - path_to_url if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { if ( elemdisplay[ nodeName ] ) { return elemdisplay[ nodeName ]; } var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ), display = elem.css("display"); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // Use the already-created iframe if possible iframe = document.body.appendChild( iframe || jQuery.extend( document.createElement("iframe"), { frameBorder: 0, width: 0, height: 0 }) ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write("<!doctype html><html><body>"); iframeDoc.close(); } elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) ); display = curCSS( elem, "display" ); document.body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } else { return getWidthOrHeight( elem, name, extra ); } } }, set: function( elem, value, extra ) { return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box" ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there there is no filter style applied in a css rule, we are done if ( currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, function() { if ( computed ) { return curCSS( elem, "marginRight" ); } }); } }; } // Webkit bug: path_to_url // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { var ret = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ], expanded = {}; for ( i = 0; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rselectTextarea = /^(?:select|textarea)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rts = /([?&])_=[^&]*/, rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = ["*/"] + ["*"]; // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, list, placeBefore, dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ), i = 0, length = dataTypes.length; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var selection, list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ); for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } // Don't do a request if no elements are being requested if ( !this.length ) { return this; } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // Request the remote document jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params, complete: function( jqXHR, status ) { if ( callback ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); } } }).done(function( responseText ) { // Save response for use in complete callback response = arguments; // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append( responseText.replace( rscript, "" ) ) // Locate the specified elements .find( selector ) : // If not, just inject the full result responseText ); }); return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded; charset=UTF-8", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { context: true, url: true } }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // ifModified key ifModifiedKey, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || strAbort; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ ifModifiedKey ] = modified; } modified = jqXHR.getResponseHeader("Etag"); if ( modified ) { jQuery.etag[ ifModifiedKey ] = modified; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( !statusText || status ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.always( tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace ); // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout( function(){ jqXHR.abort( "timeout" ); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch (e) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } return jqXHR; }, // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { var conv, conv2, current, tmp, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ], converters = {}, i = 0; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split(" "); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } var oldCallbacks = [], rquestion = /\?/, rjsonp = /(=)\?(?=&|$)|\?\?/, nonce = jQuery.now(); // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, data = s.data, url = s.url, hasCallback = s.jsonp !== false, replaceInUrl = hasCallback && rjsonp.test( url ), replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( data ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; overwritten = window[ callbackName ]; // Insert callback into url or form data if ( replaceInUrl ) { s.url = url.replace( rjsonp, "$1" + callbackName ); } else if ( replaceInData ) { s.data = data.replace( rjsonp, "$1" + callbackName ); } else if ( hasCallback ) { s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var xhrCallbacks, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( _ ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responseHeaders, responses, xml; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // path_to_url try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( e ) { } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback, 0 ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback(0,1); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var end, unit, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }, 0 ); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } function Animation( elem, properties, options ) { var result, index = 0, tweenerIndex = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end, easing ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } createTweens( animation, props ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { anim: animation, queue: animation.opts.queue, elem: elem }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.done(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery.removeData( elem, "fxshow", true ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing any value as a 4th parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, false, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Remove in 2.0 - this supports IE8's panic based approach // to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" || // special check for .toggle( handler, handler, ... ) ( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations resolve immediately if ( empty ) { anim.stop( true ); } }; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) && !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.interval = 13; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } var rroot = /^(?:body|html)$/i; jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } if ( (body = doc.body) === elem ) { return jQuery.offset.bodyOffset( elem ); } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== "undefined" ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); clientTop = docElem.clientTop || body.clientTop || 0; clientLeft = docElem.clientLeft || body.clientLeft || 0; scrollTop = win.pageYOffset || docElem.scrollTop; scrollLeft = win.pageXOffset || docElem.scrollLeft; return { top: box.top + scrollTop - clientTop, left: box.left + scrollLeft - clientLeft }; }; jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[0] ) { return; } var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.body; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // path_to_url return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, value, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window ); ```
/content/code_sandbox/public/vendor/jquery-backstretch/libs/jquery/jquery.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
72,564
```css /** * QUnit v1.4.0 - A JavaScript Unit Testing Framework * * path_to_url * * Dual licensed under the MIT (MIT-LICENSE.txt) * or GPL (GPL-LICENSE.txt) licenses. */ /** Font Family and Sizes */ #qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult { font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif; } #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; } #qunit-tests { font-size: smaller; } /** Resets */ #qunit-tests, #qunit-tests ol, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult { margin: 0; padding: 0; } /** Header */ #qunit-header { padding: 0.5em 0 0.5em 1em; color: #8699a4; background-color: #0d3349; font-size: 1.5em; line-height: 1em; font-weight: normal; border-radius: 15px 15px 0 0; -moz-border-radius: 15px 15px 0 0; -webkit-border-top-right-radius: 15px; -webkit-border-top-left-radius: 15px; } #qunit-header a { text-decoration: none; color: #c2ccd1; } #qunit-header a:hover, #qunit-header a:focus { color: #fff; } #qunit-header label { display: inline-block; } #qunit-banner { height: 5px; } #qunit-testrunner-toolbar { padding: 0.5em 0 0.5em 2em; color: #5E740B; background-color: #eee; } #qunit-userAgent { padding: 0.5em 0 0.5em 2.5em; background-color: #2b81af; color: #fff; text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px; } /** Tests: Pass/Fail */ #qunit-tests { list-style-position: inside; } #qunit-tests li { padding: 0.4em 0.5em 0.4em 2.5em; border-bottom: 1px solid #fff; list-style-position: inside; } #qunit-tests.hidepass li.pass, #qunit-tests.hidepass li.running { display: none; } #qunit-tests li strong { cursor: pointer; } #qunit-tests li a { padding: 0.5em; color: #c2ccd1; text-decoration: none; } #qunit-tests li a:hover, #qunit-tests li a:focus { color: #000; } #qunit-tests ol { margin-top: 0.5em; padding: 0.5em; background-color: #fff; border-radius: 15px; -moz-border-radius: 15px; -webkit-border-radius: 15px; box-shadow: inset 0px 2px 13px #999; -moz-box-shadow: inset 0px 2px 13px #999; -webkit-box-shadow: inset 0px 2px 13px #999; } #qunit-tests table { border-collapse: collapse; margin-top: .2em; } #qunit-tests th { text-align: right; vertical-align: top; padding: 0 .5em 0 0; } #qunit-tests td { vertical-align: top; } #qunit-tests pre { margin: 0; white-space: pre-wrap; word-wrap: break-word; } #qunit-tests del { background-color: #e0f2be; color: #374e0c; text-decoration: none; } #qunit-tests ins { background-color: #ffcaca; color: #500; text-decoration: none; } /*** Test Counts */ #qunit-tests b.counts { color: black; } #qunit-tests b.passed { color: #5E740B; } #qunit-tests b.failed { color: #710909; } #qunit-tests li li { margin: 0.5em; padding: 0.4em 0.5em 0.4em 0.5em; background-color: #fff; border-bottom: none; list-style-position: inside; } /*** Passing Styles */ #qunit-tests li li.pass { color: #5E740B; background-color: #fff; border-left: 26px solid #C6E746; } #qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; } #qunit-tests .pass .test-name { color: #366097; } #qunit-tests .pass .test-actual, #qunit-tests .pass .test-expected { color: #999999; } #qunit-banner.qunit-pass { background-color: #C6E746; } /*** Failing Styles */ #qunit-tests li li.fail { color: #710909; background-color: #fff; border-left: 26px solid #EE5757; white-space: pre; } #qunit-tests > li:last-child { border-radius: 0 0 15px 15px; -moz-border-radius: 0 0 15px 15px; -webkit-border-bottom-right-radius: 15px; -webkit-border-bottom-left-radius: 15px; } #qunit-tests .fail { color: #000000; background-color: #EE5757; } #qunit-tests .fail .test-name, #qunit-tests .fail .module-name { color: #000000; } #qunit-tests .fail .test-actual { color: #EE5757; } #qunit-tests .fail .test-expected { color: green; } #qunit-banner.qunit-fail { background-color: #EE5757; } /** Result */ #qunit-testresult { padding: 0.5em 0.5em 0.5em 2.5em; color: #2b81af; background-color: #D2E0E6; border-bottom: 1px solid white; } /** Fixture */ #qunit-fixture { position: absolute; top: -10000px; left: -10000px; width: 1000px; height: 1000px; } ```
/content/code_sandbox/public/vendor/jquery-backstretch/libs/qunit/qunit.css
css
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
1,466
```javascript /** * QUnit v1.4.0 - A JavaScript Unit Testing Framework * * path_to_url * * Dual licensed under the MIT (MIT-LICENSE.txt) * or GPL (GPL-LICENSE.txt) licenses. */ (function(window) { var defined = { setTimeout: typeof window.setTimeout !== "undefined", sessionStorage: (function() { var x = "qunit-test-string"; try { sessionStorage.setItem(x, x); sessionStorage.removeItem(x); return true; } catch(e) { return false; } }()) }; var testId = 0, toString = Object.prototype.toString, hasOwn = Object.prototype.hasOwnProperty; var Test = function(name, testName, expected, async, callback) { this.name = name; this.testName = testName; this.expected = expected; this.async = async; this.callback = callback; this.assertions = []; }; Test.prototype = { init: function() { var tests = id("qunit-tests"); if (tests) { var b = document.createElement("strong"); b.innerHTML = "Running " + this.name; var li = document.createElement("li"); li.appendChild( b ); li.className = "running"; li.id = this.id = "test-output" + testId++; tests.appendChild( li ); } }, setup: function() { if (this.module != config.previousModule) { if ( config.previousModule ) { runLoggingCallbacks('moduleDone', QUnit, { name: config.previousModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all } ); } config.previousModule = this.module; config.moduleStats = { all: 0, bad: 0 }; runLoggingCallbacks( 'moduleStart', QUnit, { name: this.module } ); } else if (config.autorun) { runLoggingCallbacks( 'moduleStart', QUnit, { name: this.module } ); } config.current = this; this.testEnvironment = extend({ setup: function() {}, teardown: function() {} }, this.moduleTestEnvironment); runLoggingCallbacks( 'testStart', QUnit, { name: this.testName, module: this.module }); // allow utility functions to access the current test environment // TODO why?? QUnit.current_testEnvironment = this.testEnvironment; if ( !config.pollution ) { saveGlobal(); } if ( config.notrycatch ) { this.testEnvironment.setup.call(this.testEnvironment); return; } try { this.testEnvironment.setup.call(this.testEnvironment); } catch(e) { QUnit.pushFailure( "Setup failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) ); } }, run: function() { config.current = this; if ( this.async ) { QUnit.stop(); } if ( config.notrycatch ) { this.callback.call(this.testEnvironment); return; } try { this.callback.call(this.testEnvironment); } catch(e) { QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + ": " + e.message, extractStacktrace( e, 1 ) ); // else next test will carry the responsibility saveGlobal(); // Restart the tests if they're blocking if ( config.blocking ) { QUnit.start(); } } }, teardown: function() { config.current = this; if ( config.notrycatch ) { this.testEnvironment.teardown.call(this.testEnvironment); return; } else { try { this.testEnvironment.teardown.call(this.testEnvironment); } catch(e) { QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) ); } } checkPollution(); }, finish: function() { config.current = this; if ( this.expected != null && this.expected != this.assertions.length ) { QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" ); } else if ( this.expected == null && !this.assertions.length ) { QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions." ); } var good = 0, bad = 0, li, i, tests = id("qunit-tests"); config.stats.all += this.assertions.length; config.moduleStats.all += this.assertions.length; if ( tests ) { var ol = document.createElement("ol"); for ( i = 0; i < this.assertions.length; i++ ) { var assertion = this.assertions[i]; li = document.createElement("li"); li.className = assertion.result ? "pass" : "fail"; li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed"); ol.appendChild( li ); if ( assertion.result ) { good++; } else { bad++; config.stats.bad++; config.moduleStats.bad++; } } // store result when possible if ( QUnit.config.reorder && defined.sessionStorage ) { if (bad) { sessionStorage.setItem("qunit-test-" + this.module + "-" + this.testName, bad); } else { sessionStorage.removeItem("qunit-test-" + this.module + "-" + this.testName); } } if (bad === 0) { ol.style.display = "none"; } var b = document.createElement("strong"); b.innerHTML = this.name + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>"; var a = document.createElement("a"); a.innerHTML = "Rerun"; a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); addEvent(b, "click", function() { var next = b.nextSibling.nextSibling, display = next.style.display; next.style.display = display === "none" ? "block" : "none"; }); addEvent(b, "dblclick", function(e) { var target = e && e.target ? e.target : window.event.srcElement; if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) { target = target.parentNode; } if ( window.location && target.nodeName.toLowerCase() === "strong" ) { window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); } }); li = id(this.id); li.className = bad ? "fail" : "pass"; li.removeChild( li.firstChild ); li.appendChild( b ); li.appendChild( a ); li.appendChild( ol ); } else { for ( i = 0; i < this.assertions.length; i++ ) { if ( !this.assertions[i].result ) { bad++; config.stats.bad++; config.moduleStats.bad++; } } } QUnit.reset(); runLoggingCallbacks( 'testDone', QUnit, { name: this.testName, module: this.module, failed: bad, passed: this.assertions.length - bad, total: this.assertions.length } ); }, queue: function() { var test = this; synchronize(function() { test.init(); }); function run() { // each of these can by async synchronize(function() { test.setup(); }); synchronize(function() { test.run(); }); synchronize(function() { test.teardown(); }); synchronize(function() { test.finish(); }); } // defer when previous test run passed, if storage is available var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-test-" + this.module + "-" + this.testName); if (bad) { run(); } else { synchronize(run, true); } } }; var QUnit = { // call on start of module test to prepend name to all tests module: function(name, testEnvironment) { config.currentModule = name; config.currentModuleTestEnviroment = testEnvironment; }, asyncTest: function(testName, expected, callback) { if ( arguments.length === 2 ) { callback = expected; expected = null; } QUnit.test(testName, expected, callback, true); }, test: function(testName, expected, callback, async) { var name = '<span class="test-name">' + escapeInnerText(testName) + '</span>'; if ( arguments.length === 2 ) { callback = expected; expected = null; } if ( config.currentModule ) { name = '<span class="module-name">' + config.currentModule + "</span>: " + name; } if ( !validTest(config.currentModule + ": " + testName) ) { return; } var test = new Test(name, testName, expected, async, callback); test.module = config.currentModule; test.moduleTestEnvironment = config.currentModuleTestEnviroment; test.queue(); }, // Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. expect: function(asserts) { config.current.expected = asserts; }, // Asserts true. // @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); ok: function(result, msg) { if (!config.current) { throw new Error("ok() assertion outside test context, was " + sourceFromStacktrace(2)); } result = !!result; var details = { result: result, message: msg }; msg = escapeInnerText(msg || (result ? "okay" : "failed")); if ( !result ) { var source = sourceFromStacktrace(2); if (source) { details.source = source; msg += '<table><tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr></table>'; } } runLoggingCallbacks( 'log', QUnit, details ); config.current.assertions.push({ result: result, message: msg }); }, // Checks that the first two arguments are equal, with an optional message. Prints out both actual and expected values. // @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." ); equal: function(actual, expected, message) { QUnit.push(expected == actual, actual, expected, message); }, notEqual: function(actual, expected, message) { QUnit.push(expected != actual, actual, expected, message); }, deepEqual: function(actual, expected, message) { QUnit.push(QUnit.equiv(actual, expected), actual, expected, message); }, notDeepEqual: function(actual, expected, message) { QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message); }, strictEqual: function(actual, expected, message) { QUnit.push(expected === actual, actual, expected, message); }, notStrictEqual: function(actual, expected, message) { QUnit.push(expected !== actual, actual, expected, message); }, raises: function(block, expected, message) { var actual, ok = false; if (typeof expected === 'string') { message = expected; expected = null; } try { block(); } catch (e) { actual = e; } if (actual) { // we don't want to validate thrown error if (!expected) { ok = true; // expected is a regexp } else if (QUnit.objectType(expected) === "regexp") { ok = expected.test(actual); // expected is a constructor } else if (actual instanceof expected) { ok = true; // expected is a validation function which returns true is validation passed } else if (expected.call({}, actual) === true) { ok = true; } } QUnit.ok(ok, message); }, start: function(count) { config.semaphore -= count || 1; if (config.semaphore > 0) { // don't start until equal number of stop-calls return; } if (config.semaphore < 0) { // ignore if start is called more often then stop config.semaphore = 0; } // A slight delay, to avoid any current callbacks if ( defined.setTimeout ) { window.setTimeout(function() { if (config.semaphore > 0) { return; } if ( config.timeout ) { clearTimeout(config.timeout); } config.blocking = false; process(true); }, 13); } else { config.blocking = false; process(true); } }, stop: function(count) { config.semaphore += count || 1; config.blocking = true; if ( config.testTimeout && defined.setTimeout ) { clearTimeout(config.timeout); config.timeout = window.setTimeout(function() { QUnit.ok( false, "Test timed out" ); config.semaphore = 1; QUnit.start(); }, config.testTimeout); } } }; //We want access to the constructor's prototype (function() { function F(){} F.prototype = QUnit; QUnit = new F(); //Make F QUnit's constructor so that we can add to the prototype later QUnit.constructor = F; }()); // deprecated; still export them to window to provide clear error messages // next step: remove entirely QUnit.equals = function() { QUnit.push(false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead"); }; QUnit.same = function() { QUnit.push(false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead"); }; // Maintain internal state var config = { // The queue of tests to run queue: [], // block until document ready blocking: true, // when enabled, show only failing tests // gets persisted through sessionStorage and can be changed in UI via checkbox hidepassed: false, // by default, run previously failed tests first // very useful in combination with "Hide passed tests" checked reorder: true, // by default, modify document.title when suite is done altertitle: true, urlConfig: ['noglobals', 'notrycatch'], //logging callback queues begin: [], done: [], log: [], testStart: [], testDone: [], moduleStart: [], moduleDone: [] }; // Load paramaters (function() { var location = window.location || { search: "", protocol: "file:" }, params = location.search.slice( 1 ).split( "&" ), length = params.length, urlParams = {}, current; if ( params[ 0 ] ) { for ( var i = 0; i < length; i++ ) { current = params[ i ].split( "=" ); current[ 0 ] = decodeURIComponent( current[ 0 ] ); // allow just a key to turn on a flag, e.g., test.html?noglobals current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true; urlParams[ current[ 0 ] ] = current[ 1 ]; } } QUnit.urlParams = urlParams; config.filter = urlParams.filter; // Figure out if we're running the tests from a server or not QUnit.isLocal = location.protocol === 'file:'; }()); // Expose the API as global variables, unless an 'exports' // object exists, in that case we assume we're in CommonJS - export everything at the end if ( typeof exports === "undefined" || typeof require === "undefined" ) { extend(window, QUnit); window.QUnit = QUnit; } // define these after exposing globals to keep them in these QUnit namespace only extend(QUnit, { config: config, // Initialize the configuration options init: function() { extend(config, { stats: { all: 0, bad: 0 }, moduleStats: { all: 0, bad: 0 }, started: +new Date(), updateRate: 1000, blocking: false, autostart: true, autorun: false, filter: "", queue: [], semaphore: 0 }); var qunit = id( "qunit" ); if ( qunit ) { qunit.innerHTML = '<h1 id="qunit-header">' + escapeInnerText( document.title ) + '</h1>' + '<h2 id="qunit-banner"></h2>' + '<div id="qunit-testrunner-toolbar"></div>' + '<h2 id="qunit-userAgent"></h2>' + '<ol id="qunit-tests"></ol>'; } var tests = id( "qunit-tests" ), banner = id( "qunit-banner" ), result = id( "qunit-testresult" ); if ( tests ) { tests.innerHTML = ""; } if ( banner ) { banner.className = ""; } if ( result ) { result.parentNode.removeChild( result ); } if ( tests ) { result = document.createElement( "p" ); result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore( result, tests ); result.innerHTML = 'Running...<br/>&nbsp;'; } }, // Resets the test setup. Useful for tests that modify the DOM. // If jQuery is available, uses jQuery's html(), otherwise just innerHTML. reset: function() { if ( window.jQuery ) { jQuery( "#qunit-fixture" ).html( config.fixture ); } else { var main = id( 'qunit-fixture' ); if ( main ) { main.innerHTML = config.fixture; } } }, // Trigger an event on an element. // @example triggerEvent( document.body, "click" ); triggerEvent: function( elem, type, event ) { if ( document.createEvent ) { event = document.createEvent("MouseEvents"); event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elem.dispatchEvent( event ); } else if ( elem.fireEvent ) { elem.fireEvent("on"+type); } }, // Safe object type checking is: function( type, obj ) { return QUnit.objectType( obj ) == type; }, objectType: function( obj ) { if (typeof obj === "undefined") { return "undefined"; // consider: typeof null === object } if (obj === null) { return "null"; } var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || ''; switch (type) { case 'Number': if (isNaN(obj)) { return "nan"; } return "number"; case 'String': case 'Boolean': case 'Array': case 'Date': case 'RegExp': case 'Function': return type.toLowerCase(); } if (typeof obj === "object") { return "object"; } return undefined; }, push: function(result, actual, expected, message) { if (!config.current) { throw new Error("assertion outside test context, was " + sourceFromStacktrace()); } var details = { result: result, message: message, actual: actual, expected: expected }; message = escapeInnerText(message) || (result ? "okay" : "failed"); message = '<span class="test-message">' + message + "</span>"; var output = message; if (!result) { expected = escapeInnerText(QUnit.jsDump.parse(expected)); actual = escapeInnerText(QUnit.jsDump.parse(actual)); output += '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>'; if (actual != expected) { output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>'; output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) +'</pre></td></tr>'; } var source = sourceFromStacktrace(); if (source) { details.source = source; output += '<tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr>'; } output += "</table>"; } runLoggingCallbacks( 'log', QUnit, details ); config.current.assertions.push({ result: !!result, message: output }); }, pushFailure: function(message, source) { var details = { result: false, message: message }; var output = escapeInnerText(message); if (source) { details.source = source; output += '<table><tr class="test-source"><th>Source: </th><td><pre>' + escapeInnerText(source) + '</pre></td></tr></table>'; } runLoggingCallbacks( 'log', QUnit, details ); config.current.assertions.push({ result: false, message: output }); }, url: function( params ) { params = extend( extend( {}, QUnit.urlParams ), params ); var querystring = "?", key; for ( key in params ) { if ( !hasOwn.call( params, key ) ) { continue; } querystring += encodeURIComponent( key ) + "=" + encodeURIComponent( params[ key ] ) + "&"; } return window.location.pathname + querystring.slice( 0, -1 ); }, extend: extend, id: id, addEvent: addEvent }); //QUnit.constructor is set to the empty F() above so that we can add to it's prototype later //Doing this allows us to tell if the following methods have been overwritten on the actual //QUnit object, which is a deprecated way of using the callbacks. extend(QUnit.constructor.prototype, { // Logging callbacks; all receive a single argument with the listed properties // run test/logs.html for any related changes begin: registerLoggingCallback('begin'), // done: { failed, passed, total, runtime } done: registerLoggingCallback('done'), // log: { result, actual, expected, message } log: registerLoggingCallback('log'), // testStart: { name } testStart: registerLoggingCallback('testStart'), // testDone: { name, failed, passed, total } testDone: registerLoggingCallback('testDone'), // moduleStart: { name } moduleStart: registerLoggingCallback('moduleStart'), // moduleDone: { name, failed, passed, total } moduleDone: registerLoggingCallback('moduleDone') }); if ( typeof document === "undefined" || document.readyState === "complete" ) { config.autorun = true; } QUnit.load = function() { runLoggingCallbacks( 'begin', QUnit, {} ); // Initialize the config, saving the execution queue var oldconfig = extend({}, config); QUnit.init(); extend(config, oldconfig); config.blocking = false; var urlConfigHtml = '', len = config.urlConfig.length; for ( var i = 0, val; i < len; i++ ) { val = config.urlConfig[i]; config[val] = QUnit.urlParams[val]; urlConfigHtml += '<label><input name="' + val + '" type="checkbox"' + ( config[val] ? ' checked="checked"' : '' ) + '>' + val + '</label>'; } var userAgent = id("qunit-userAgent"); if ( userAgent ) { userAgent.innerHTML = navigator.userAgent; } var banner = id("qunit-header"); if ( banner ) { banner.innerHTML = '<a href="' + QUnit.url({ filter: undefined }) + '"> ' + banner.innerHTML + '</a> ' + urlConfigHtml; addEvent( banner, "change", function( event ) { var params = {}; params[ event.target.name ] = event.target.checked ? true : undefined; window.location = QUnit.url( params ); }); } var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { var filter = document.createElement("input"); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; addEvent( filter, "click", function() { var ol = document.getElementById("qunit-tests"); if ( filter.checked ) { ol.className = ol.className + " hidepass"; } else { var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " "; ol.className = tmp.replace(/ hidepass /, " "); } if ( defined.sessionStorage ) { if (filter.checked) { sessionStorage.setItem("qunit-filter-passed-tests", "true"); } else { sessionStorage.removeItem("qunit-filter-passed-tests"); } } }); if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) { filter.checked = true; var ol = document.getElementById("qunit-tests"); ol.className = ol.className + " hidepass"; } toolbar.appendChild( filter ); var label = document.createElement("label"); label.setAttribute("for", "qunit-filter-pass"); label.innerHTML = "Hide passed tests"; toolbar.appendChild( label ); } var main = id('qunit-fixture'); if ( main ) { config.fixture = main.innerHTML; } if (config.autostart) { QUnit.start(); } }; addEvent(window, "load", QUnit.load); // addEvent(window, "error") gives us a useless event object window.onerror = function( message, file, line ) { if ( QUnit.config.current ) { QUnit.pushFailure( message, file + ":" + line ); } else { QUnit.test( "global failure", function() { QUnit.pushFailure( message, file + ":" + line ); }); } }; function done() { config.autorun = true; // Log the last module results if ( config.currentModule ) { runLoggingCallbacks( 'moduleDone', QUnit, { name: config.currentModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all } ); } var banner = id("qunit-banner"), tests = id("qunit-tests"), runtime = +new Date() - config.started, passed = config.stats.all - config.stats.bad, html = [ 'Tests completed in ', runtime, ' milliseconds.<br/>', '<span class="passed">', passed, '</span> tests of <span class="total">', config.stats.all, '</span> passed, <span class="failed">', config.stats.bad, '</span> failed.' ].join(''); if ( banner ) { banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass"); } if ( tests ) { id( "qunit-testresult" ).innerHTML = html; } if ( config.altertitle && typeof document !== "undefined" && document.title ) { // show for good, for bad suite result in title // use escape sequences in case file gets loaded with non-utf-8-charset document.title = [ (config.stats.bad ? "\u2716" : "\u2714"), document.title.replace(/^[\u2714\u2716] /i, "") ].join(" "); } // clear own sessionStorage items if all tests passed if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) { for (var key in sessionStorage) { if (sessionStorage.hasOwnProperty(key) && key.indexOf("qunit-test-") === 0 ) { sessionStorage.removeItem(key); } } } runLoggingCallbacks( 'done', QUnit, { failed: config.stats.bad, passed: passed, total: config.stats.all, runtime: runtime } ); } function validTest( name ) { var filter = config.filter, run = false; if ( !filter ) { return true; } var not = filter.charAt( 0 ) === "!"; if ( not ) { filter = filter.slice( 1 ); } if ( name.indexOf( filter ) !== -1 ) { return !not; } if ( not ) { run = true; } return run; } // so far supports only Firefox, Chrome and Opera (buggy) // could be extended in the future to use something like path_to_url function extractStacktrace( e, offset ) { offset = offset || 3; if (e.stacktrace) { // Opera return e.stacktrace.split("\n")[offset + 3]; } else if (e.stack) { // Firefox, Chrome var stack = e.stack.split("\n"); if (/^error$/i.test(stack[0])) { stack.shift(); } return stack[offset]; } else if (e.sourceURL) { // Safari, PhantomJS // hopefully one day Safari provides actual stacktraces // exclude useless self-reference for generated Error objects if ( /qunit.js$/.test( e.sourceURL ) ) { return; } // for actual exceptions, this is useful return e.sourceURL + ":" + e.line; } } function sourceFromStacktrace(offset) { try { throw new Error(); } catch ( e ) { return extractStacktrace( e, offset ); } } function escapeInnerText(s) { if (!s) { return ""; } s = s + ""; return s.replace(/[\&<>]/g, function(s) { switch(s) { case "&": return "&amp;"; case "<": return "&lt;"; case ">": return "&gt;"; default: return s; } }); } function synchronize( callback, last ) { config.queue.push( callback ); if ( config.autorun && !config.blocking ) { process(last); } } function process( last ) { function next() { process( last ); } var start = new Date().getTime(); config.depth = config.depth ? config.depth + 1 : 1; while ( config.queue.length && !config.blocking ) { if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) { config.queue.shift()(); } else { window.setTimeout( next, 13 ); break; } } config.depth--; if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { done(); } } function saveGlobal() { config.pollution = []; if ( config.noglobals ) { for ( var key in window ) { if ( !hasOwn.call( window, key ) ) { continue; } config.pollution.push( key ); } } } function checkPollution( name ) { var old = config.pollution; saveGlobal(); var newGlobals = diff( config.pollution, old ); if ( newGlobals.length > 0 ) { QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") ); } var deletedGlobals = diff( old, config.pollution ); if ( deletedGlobals.length > 0 ) { QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") ); } } // returns a new Array with the elements that are in a but not in b function diff( a, b ) { var result = a.slice(); for ( var i = 0; i < result.length; i++ ) { for ( var j = 0; j < b.length; j++ ) { if ( result[i] === b[j] ) { result.splice(i, 1); i--; break; } } } return result; } function extend(a, b) { for ( var prop in b ) { if ( b[prop] === undefined ) { delete a[prop]; // Avoid "Member not found" error in IE8 caused by setting window.constructor } else if ( prop !== "constructor" || a !== window ) { a[prop] = b[prop]; } } return a; } function addEvent(elem, type, fn) { if ( elem.addEventListener ) { elem.addEventListener( type, fn, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, fn ); } else { fn(); } } function id(name) { return !!(typeof document !== "undefined" && document && document.getElementById) && document.getElementById( name ); } function registerLoggingCallback(key){ return function(callback){ config[key].push( callback ); }; } // Supports deprecated method of completely overwriting logging callbacks function runLoggingCallbacks(key, scope, args) { //debugger; var callbacks; if ( QUnit.hasOwnProperty(key) ) { QUnit[key].call(scope, args); } else { callbacks = config[key]; for( var i = 0; i < callbacks.length; i++ ) { callbacks[i].call( scope, args ); } } } // Test for equality any JavaScript type. // Author: Philippe Rath <prathe@gmail.com> QUnit.equiv = (function() { var innerEquiv; // the real equiv function var callers = []; // stack to decide between skip/abort functions var parents = []; // stack to avoiding loops from circular referencing // Call the o related callback with the given arguments. function bindCallbacks(o, callbacks, args) { var prop = QUnit.objectType(o); if (prop) { if (QUnit.objectType(callbacks[prop]) === "function") { return callbacks[prop].apply(callbacks, args); } else { return callbacks[prop]; // or undefined } } } var getProto = Object.getPrototypeOf || function (obj) { return obj.__proto__; }; var callbacks = (function () { // for string, boolean, number and null function useStrictEquality(b, a) { if (b instanceof a.constructor || a instanceof b.constructor) { // to catch short annotaion VS 'new' annotation of a // declaration // e.g. var i = 1; // var j = new Number(1); return a == b; } else { return a === b; } } return { "string" : useStrictEquality, "boolean" : useStrictEquality, "number" : useStrictEquality, "null" : useStrictEquality, "undefined" : useStrictEquality, "nan" : function(b) { return isNaN(b); }, "date" : function(b, a) { return QUnit.objectType(b) === "date" && a.valueOf() === b.valueOf(); }, "regexp" : function(b, a) { return QUnit.objectType(b) === "regexp" && // the regex itself a.source === b.source && // and its modifers a.global === b.global && // (gmi) ... a.ignoreCase === b.ignoreCase && a.multiline === b.multiline; }, // - skip when the property is a method of an instance (OOP) // - abort otherwise, // initial === would have catch identical references anyway "function" : function() { var caller = callers[callers.length - 1]; return caller !== Object && typeof caller !== "undefined"; }, "array" : function(b, a) { var i, j, loop; var len; // b could be an object literal here if (QUnit.objectType(b) !== "array") { return false; } len = a.length; if (len !== b.length) { // safe and faster return false; } // track reference to avoid circular references parents.push(a); for (i = 0; i < len; i++) { loop = false; for (j = 0; j < parents.length; j++) { if (parents[j] === a[i]) { loop = true;// dont rewalk array } } if (!loop && !innerEquiv(a[i], b[i])) { parents.pop(); return false; } } parents.pop(); return true; }, "object" : function(b, a) { var i, j, loop; var eq = true; // unless we can proove it var aProperties = [], bProperties = []; // collection of // strings // comparing constructors is more strict than using // instanceof if (a.constructor !== b.constructor) { // Allow objects with no prototype to be equivalent to // objects with Object as their constructor. if (!((getProto(a) === null && getProto(b) === Object.prototype) || (getProto(b) === null && getProto(a) === Object.prototype))) { return false; } } // stack constructor before traversing properties callers.push(a.constructor); // track reference to avoid circular references parents.push(a); for (i in a) { // be strict: don't ensures hasOwnProperty // and go deep loop = false; for (j = 0; j < parents.length; j++) { if (parents[j] === a[i]) { // don't go down the same path twice loop = true; } } aProperties.push(i); // collect a's properties if (!loop && !innerEquiv(a[i], b[i])) { eq = false; break; } } callers.pop(); // unstack, we are done parents.pop(); for (i in b) { bProperties.push(i); // collect b's properties } // Ensures identical properties name return eq && innerEquiv(aProperties.sort(), bProperties.sort()); } }; }()); innerEquiv = function() { // can take multiple arguments var args = Array.prototype.slice.apply(arguments); if (args.length < 2) { return true; // end transition } return (function(a, b) { if (a === b) { return true; // catch the most you can } else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || QUnit.objectType(a) !== QUnit.objectType(b)) { return false; // don't lose time with error prone cases } else { return bindCallbacks(a, callbacks, [ b, a ]); } // apply transition with (1..n) arguments }(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length - 1))); }; return innerEquiv; }()); /** * (path_to_url Date: 5/15/2008 * * @projectDescription Advanced and extensible data dumping for Javascript. * @version 1.0.0 * @author Ariel Flesler * @link {path_to_url} */ QUnit.jsDump = (function() { function quote( str ) { return '"' + str.toString().replace(/"/g, '\\"') + '"'; } function literal( o ) { return o + ''; } function join( pre, arr, post ) { var s = jsDump.separator(), base = jsDump.indent(), inner = jsDump.indent(1); if ( arr.join ) { arr = arr.join( ',' + s + inner ); } if ( !arr ) { return pre + post; } return [ pre, inner + arr, base + post ].join(s); } function array( arr, stack ) { var i = arr.length, ret = new Array(i); this.up(); while ( i-- ) { ret[i] = this.parse( arr[i] , undefined , stack); } this.down(); return join( '[', ret, ']' ); } var reName = /^function (\w+)/; var jsDump = { parse: function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance stack = stack || [ ]; var parser = this.parsers[ type || this.typeOf(obj) ]; type = typeof parser; var inStack = inArray(obj, stack); if (inStack != -1) { return 'recursion('+(inStack - stack.length)+')'; } //else if (type == 'function') { stack.push(obj); var res = parser.call( this, obj, stack ); stack.pop(); return res; } // else return (type == 'string') ? parser : this.parsers.error; }, typeOf: function( obj ) { var type; if ( obj === null ) { type = "null"; } else if (typeof obj === "undefined") { type = "undefined"; } else if (QUnit.is("RegExp", obj)) { type = "regexp"; } else if (QUnit.is("Date", obj)) { type = "date"; } else if (QUnit.is("Function", obj)) { type = "function"; } else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") { type = "window"; } else if (obj.nodeType === 9) { type = "document"; } else if (obj.nodeType) { type = "node"; } else if ( // native arrays toString.call( obj ) === "[object Array]" || // NodeList objects ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) ) ) { type = "array"; } else { type = typeof obj; } return type; }, separator: function() { return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? '&nbsp;' : ' '; }, indent: function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing if ( !this.multiline ) { return ''; } var chr = this.indentChar; if ( this.HTML ) { chr = chr.replace(/\t/g,' ').replace(/ /g,'&nbsp;'); } return new Array( this._depth_ + (extra||0) ).join(chr); }, up: function( a ) { this._depth_ += a || 1; }, down: function( a ) { this._depth_ -= a || 1; }, setParser: function( name, parser ) { this.parsers[name] = parser; }, // The next 3 are exposed so you can use them quote: quote, literal: literal, join: join, // _depth_: 1, // This is the list of parsers, to modify them, use jsDump.setParser parsers: { window: '[Window]', document: '[Document]', error: '[ERROR]', //when no parser is found, shouldn't happen unknown: '[Unknown]', 'null': 'null', 'undefined': 'undefined', 'function': function( fn ) { var ret = 'function', name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE if ( name ) { ret += ' ' + name; } ret += '('; ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join(''); return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' ); }, array: array, nodelist: array, 'arguments': array, object: function( map, stack ) { var ret = [ ], keys, key, val, i; QUnit.jsDump.up(); if (Object.keys) { keys = Object.keys( map ); } else { keys = []; for (key in map) { keys.push( key ); } } keys.sort(); for (i = 0; i < keys.length; i++) { key = keys[ i ]; val = map[ key ]; ret.push( QUnit.jsDump.parse( key, 'key' ) + ': ' + QUnit.jsDump.parse( val, undefined, stack ) ); } QUnit.jsDump.down(); return join( '{', ret, '}' ); }, node: function( node ) { var open = QUnit.jsDump.HTML ? '&lt;' : '<', close = QUnit.jsDump.HTML ? '&gt;' : '>'; var tag = node.nodeName.toLowerCase(), ret = open + tag; for ( var a in QUnit.jsDump.DOMAttrs ) { var val = node[QUnit.jsDump.DOMAttrs[a]]; if ( val ) { ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' ); } } return ret + close + open + '/' + tag + close; }, functionArgs: function( fn ) {//function calls it internally, it's the arguments part of the function var l = fn.length; if ( !l ) { return ''; } var args = new Array(l); while ( l-- ) { args[l] = String.fromCharCode(97+l);//97 is 'a' } return ' ' + args.join(', ') + ' '; }, key: quote, //object calls it internally, the key part of an item in a map functionCode: '[code]', //function calls it internally, it's the content of the function attribute: quote, //node calls it internally, it's an html attribute value string: quote, date: quote, regexp: literal, //regex number: literal, 'boolean': literal }, DOMAttrs:{//attributes to dump from nodes, name=>realName id:'id', name:'name', 'class':'className' }, HTML:false,//if true, entities are escaped ( <, >, \t, space and \n ) indentChar:' ',//indentation unit multiline:true //if true, items in a collection, are separated by a \n, else just a space. }; return jsDump; }()); // from Sizzle.js function getText( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += getText( elem.childNodes ); } } return ret; } //from jquery.js function inArray( elem, array ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( array[ i ] === elem ) { return i; } } return -1; } /* * Javascript Diff Algorithm * By John Resig (path_to_url * Modified by Chu Alan "sprite" * * Released under the MIT license. * * More Info: * path_to_url * * Usage: QUnit.diff(expected, actual) * * QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over" */ QUnit.diff = (function() { function diff(o, n) { var ns = {}; var os = {}; var i; for (i = 0; i < n.length; i++) { if (ns[n[i]] == null) { ns[n[i]] = { rows: [], o: null }; } ns[n[i]].rows.push(i); } for (i = 0; i < o.length; i++) { if (os[o[i]] == null) { os[o[i]] = { rows: [], n: null }; } os[o[i]].rows.push(i); } for (i in ns) { if ( !hasOwn.call( ns, i ) ) { continue; } if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) { n[ns[i].rows[0]] = { text: n[ns[i].rows[0]], row: os[i].rows[0] }; o[os[i].rows[0]] = { text: o[os[i].rows[0]], row: ns[i].rows[0] }; } } for (i = 0; i < n.length - 1; i++) { if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null && n[i + 1] == o[n[i].row + 1]) { n[i + 1] = { text: n[i + 1], row: n[i].row + 1 }; o[n[i].row + 1] = { text: o[n[i].row + 1], row: i + 1 }; } } for (i = n.length - 1; i > 0; i--) { if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null && n[i - 1] == o[n[i].row - 1]) { n[i - 1] = { text: n[i - 1], row: n[i].row - 1 }; o[n[i].row - 1] = { text: o[n[i].row - 1], row: i - 1 }; } } return { o: o, n: n }; } return function(o, n) { o = o.replace(/\s+$/, ''); n = n.replace(/\s+$/, ''); var out = diff(o === "" ? [] : o.split(/\s+/), n === "" ? [] : n.split(/\s+/)); var str = ""; var i; var oSpace = o.match(/\s+/g); if (oSpace == null) { oSpace = [" "]; } else { oSpace.push(" "); } var nSpace = n.match(/\s+/g); if (nSpace == null) { nSpace = [" "]; } else { nSpace.push(" "); } if (out.n.length === 0) { for (i = 0; i < out.o.length; i++) { str += '<del>' + out.o[i] + oSpace[i] + "</del>"; } } else { if (out.n[0].text == null) { for (n = 0; n < out.o.length && out.o[n].text == null; n++) { str += '<del>' + out.o[n] + oSpace[n] + "</del>"; } } for (i = 0; i < out.n.length; i++) { if (out.n[i].text == null) { str += '<ins>' + out.n[i] + nSpace[i] + "</ins>"; } else { var pre = ""; for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) { pre += '<del>' + out.o[n] + oSpace[n] + "</del>"; } str += " " + out.n[i].text + nSpace[i] + pre; } } } return str; }; }()); // for CommonJS enviroments, export everything if ( typeof exports !== "undefined" || typeof require !== "undefined" ) { extend(exports, QUnit); } // get at whatever the global object is, like window in browsers }( (function() {return this;}.call()) )); ```
/content/code_sandbox/public/vendor/jquery-backstretch/libs/qunit/qunit.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
12,222
```javascript /* * Backstretch * path_to_url * */ ;(function ($, window, undefined) { 'use strict'; /* PLUGIN DEFINITION * ========================= */ $.fn.backstretch = function (images, options) { // We need at least one image or method name if (images === undefined || images.length === 0) { $.error("No images were supplied for Backstretch"); } /* * Scroll the page one pixel to get the right window height on iOS * Pretty harmless for everyone else */ if ($(window).scrollTop() === 0 ) { window.scrollTo(0, 0); } return this.each(function () { var $this = $(this) , obj = $this.data('backstretch'); // Do we already have an instance attached to this element? if (obj) { // Is this a method they're trying to execute? if (typeof images == 'string' && typeof obj[images] == 'function') { // Call the method obj[images](options); // No need to do anything further return; } // Merge the old options with the new options = $.extend(obj.options, options); // Remove the old instance obj.destroy(true); } obj = new Backstretch(this, images, options); $this.data('backstretch', obj); }); }; // If no element is supplied, we'll attach to body $.backstretch = function (images, options) { // Return the instance return $('body') .backstretch(images, options) .data('backstretch'); }; // Custom selector $.expr[':'].backstretch = function(elem) { return $(elem).data('backstretch') !== undefined; }; /* DEFAULTS * ========================= */ $.fn.backstretch.defaults = { centeredX: true // Should we center the image on the X axis? , centeredY: true // Should we center the image on the Y axis? , duration: 5000 // Amount of time in between slides (if slideshow) , fade: 0 // Speed of fade transition between slides }; /* STYLES * * Baked-in styles that we'll apply to our elements. * In an effort to keep the plugin simple, these are not exposed as options. * That said, anyone can override these in their own stylesheet. * ========================= */ var styles = { wrap: { left: 0 , top: 0 , overflow: 'hidden' , margin: 0 , padding: 0 , height: '100%' , width: '100%' , zIndex: -999999 } , img: { position: 'absolute' , display: 'none' , margin: 0 , padding: 0 , border: 'none' , width: 'auto' , height: 'auto' , maxHeight: 'none' , maxWidth: 'none' , zIndex: -999999 } }; /* CLASS DEFINITION * ========================= */ var Backstretch = function (container, images, options) { this.options = $.extend({}, $.fn.backstretch.defaults, options || {}); /* In its simplest form, we allow Backstretch to be called on an image path. * e.g. $.backstretch('/path/to/image.jpg') * So, we need to turn this back into an array. */ this.images = $.isArray(images) ? images : [images]; // Preload images $.each(this.images, function () { $('<img />')[0].src = this; }); // Convenience reference to know if the container is body. this.isBody = container === document.body; /* We're keeping track of a few different elements * * Container: the element that Backstretch was called on. * Wrap: a DIV that we place the image into, so we can hide the overflow. * Root: Convenience reference to help calculate the correct height. */ this.$container = $(container); this.$root = this.isBody ? supportsFixedPosition ? $(window) : $(document) : this.$container; // Don't create a new wrap if one already exists (from a previous instance of Backstretch) var $existing = this.$container.children(".backstretch").first(); this.$wrap = $existing.length ? $existing : $('<div class="backstretch"></div>').css(styles.wrap).appendTo(this.$container); // Non-body elements need some style adjustments if (!this.isBody) { // If the container is statically positioned, we need to make it relative, // and if no zIndex is defined, we should set it to zero. var position = this.$container.css('position') , zIndex = this.$container.css('zIndex'); this.$container.css({ position: position === 'static' ? 'relative' : position , zIndex: zIndex === 'auto' ? 0 : zIndex , background: 'none' }); // Needs a higher z-index this.$wrap.css({zIndex: -999998}); } // Fixed or absolute positioning? this.$wrap.css({ position: this.isBody && supportsFixedPosition ? 'fixed' : 'absolute' }); // Set the first image this.index = 0; this.show(this.index); // Listen for resize $(window).on('resize.backstretch', $.proxy(this.resize, this)) .on('orientationchange.backstretch', $.proxy(function () { // Need to do this in order to get the right window height if (this.isBody && window.pageYOffset === 0) { window.scrollTo(0, 1); this.resize(); } }, this)); }; /* PUBLIC METHODS * ========================= */ Backstretch.prototype = { resize: function () { try { var bgCSS = {left: 0, top: 0} , rootWidth = this.isBody ? this.$root.width() : this.$root.innerWidth() , bgWidth = rootWidth , rootHeight = this.isBody ? ( window.innerHeight ? window.innerHeight : this.$root.height() ) : this.$root.innerHeight() , bgHeight = bgWidth / this.$img.data('ratio') , bgOffset; // Make adjustments based on image ratio if (bgHeight >= rootHeight) { bgOffset = (bgHeight - rootHeight) / 2; if(this.options.centeredY) { bgCSS.top = '-' + bgOffset + 'px'; } } else { bgHeight = rootHeight; bgWidth = bgHeight * this.$img.data('ratio'); bgOffset = (bgWidth - rootWidth) / 2; if(this.options.centeredX) { bgCSS.left = '-' + bgOffset + 'px'; } } this.$wrap.css({width: rootWidth, height: rootHeight}) .find('img:not(.deleteable)').css({width: bgWidth, height: bgHeight}).css(bgCSS); } catch(err) { // IE7 seems to trigger resize before the image is loaded. // This try/catch block is a hack to let it fail gracefully. } return this; } // Show the slide at a certain position , show: function (newIndex) { // Validate index if (Math.abs(newIndex) > this.images.length - 1) { return; } // Vars var self = this , oldImage = self.$wrap.find('img').addClass('deleteable') , evtOptions = { relatedTarget: self.$container[0] }; // Trigger the "before" event self.$container.trigger($.Event('backstretch.before', evtOptions), [self, newIndex]); // Set the new index this.index = newIndex; // Pause the slideshow clearInterval(self.interval); // New image self.$img = $('<img />') .css(styles.img) .bind('load', function (e) { var imgWidth = this.width || $(e.target).width() , imgHeight = this.height || $(e.target).height(); // Save the ratio $(this).data('ratio', imgWidth / imgHeight); // Show the image, then delete the old one // "speed" option has been deprecated, but we want backwards compatibilty $(this).fadeIn(self.options.speed || self.options.fade, function () { oldImage.remove(); // Resume the slideshow if (!self.paused) { self.cycle(); } // Trigger the "after" and "show" events // "show" is being deprecated $(['after', 'show']).each(function () { self.$container.trigger($.Event('backstretch.' + this, evtOptions), [self, newIndex]); }); }); // Resize self.resize(); }) .appendTo(self.$wrap); // Hack for IE img onload event self.$img.attr('src', self.images[newIndex]); return self; } , next: function () { // Next slide return this.show(this.index < this.images.length - 1 ? this.index + 1 : 0); } , prev: function () { // Previous slide return this.show(this.index === 0 ? this.images.length - 1 : this.index - 1); } , pause: function () { // Pause the slideshow this.paused = true; return this; } , resume: function () { // Resume the slideshow this.paused = false; this.next(); return this; } , cycle: function () { // Start/resume the slideshow if(this.images.length > 1) { // Clear the interval, just in case clearInterval(this.interval); this.interval = setInterval($.proxy(function () { // Check for paused slideshow if (!this.paused) { this.next(); } }, this), this.options.duration); } return this; } , destroy: function (preserveBackground) { // Stop the resize events $(window).off('resize.backstretch orientationchange.backstretch'); // Clear the interval clearInterval(this.interval); // Remove Backstretch if(!preserveBackground) { this.$wrap.remove(); } this.$container.removeData('backstretch'); } }; /* SUPPORTS FIXED POSITION? * * Based on code from jQuery Mobile 1.1.0 * path_to_url * * In a nutshell, we need to figure out if fixed positioning is supported. * Unfortunately, this is very difficult to do on iOS, and usually involves * injecting content, scrolling the page, etc.. It's ugly. * jQuery Mobile uses this workaround. It's not ideal, but works. * * Modified to detect IE6 * ========================= */ var supportsFixedPosition = (function () { var ua = navigator.userAgent , platform = navigator.platform // Rendering engine is Webkit, and capture major version , wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ) , wkversion = !!wkmatch && wkmatch[ 1 ] , ffmatch = ua.match( /Fennec\/([0-9]+)/ ) , ffversion = !!ffmatch && ffmatch[ 1 ] , operammobilematch = ua.match( /Opera Mobi\/([0-9]+)/ ) , omversion = !!operammobilematch && operammobilematch[ 1 ] , iematch = ua.match( /MSIE ([0-9]+)/ ) , ieversion = !!iematch && iematch[ 1 ]; return !( // iOS 4.3 and older : Platform is iPhone/Pad/Touch and Webkit version is less than 534 (ios5) ((platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ) && wkversion && wkversion < 534) || // Opera Mini (window.operamini && ({}).toString.call( window.operamini ) === "[object OperaMini]") || (operammobilematch && omversion < 7458) || //Android lte 2.1: Platform is Android and Webkit version is less than 533 (Android 2.2) (ua.indexOf( "Android" ) > -1 && wkversion && wkversion < 533) || // Firefox Mobile before 6.0 - (ffversion && ffversion < 6) || // WebOS less than 3 ("palmGetResource" in window && wkversion && wkversion < 534) || // MeeGo (ua.indexOf( "MeeGo" ) > -1 && ua.indexOf( "NokiaBrowser/8.5.0" ) > -1) || // IE6 (ieversion && ieversion <= 6) ); }()); }(jQuery, window)); ```
/content/code_sandbox/public/vendor/jquery-backstretch/src/jquery.backstretch.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
2,898
```javascript ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('af'); test('parse', function (assert) { var tests = 'Januarie Jan_Februarie Feb_Maart Mar_April Apr_Mei Mei_Junie Jun_Julie Jul_Augustus Aug_September Sep_Oktober Okt_November Nov_Desember Des'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Sondag, Februarie 14de 2010, 3:25:50 nm'], ['ddd, hA', 'Son, 3NM'], ['M Mo MM MMMM MMM', '2 2de 02 Februarie Feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14de 14'], ['d do dddd ddd dd', '0 0de Sondag Son So'], ['DDD DDDo DDDD', '45 45ste 045'], ['w wo ww', '6 6de 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'nm NM'], ['[the] DDDo [day of the year]', 'the 45ste day of the year'], ['LT', '15:25'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 Februarie 2010'], ['LLL', '14 Februarie 2010 15:25'], ['LLLL', 'Sondag, 14 Februarie 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 Feb 2010'], ['lll', '14 Feb 2010 15:25'], ['llll', 'Son, 14 Feb 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1ste', '1ste'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2de', '2de'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3de', '3de'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4de', '4de'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5de', '5de'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6de', '6de'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7de', '7de'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8ste', '8ste'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9de', '9de'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10de', '10de'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11de', '11de'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12de', '12de'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13de', '13de'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14de', '14de'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15de', '15de'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16de', '16de'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17de', '17de'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18de', '18de'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19de', '19de'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20ste', '20ste'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21ste', '21ste'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22ste', '22ste'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23ste', '23ste'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24ste', '24ste'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25ste', '25ste'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26ste', '26ste'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27ste', '27ste'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28ste', '28ste'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29ste', '29ste'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30ste', '30ste'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31ste', '31ste'); }); test('format month', function (assert) { var expected = 'Januarie Jan_Februarie Feb_Maart Mar_April Apr_Mei Mei_Junie Jun_Julie Jul_Augustus Aug_September Sep_Oktober Okt_November Nov_Desember Des'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Sondag Son So_Maandag Maa Ma_Dinsdag Din Di_Woensdag Woe Wo_Donderdag Don Do_Vrydag Vry Vr_Saterdag Sat Sa'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), '\'n paar sekondes', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '\'n minuut', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '\'n minuut', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minute', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minute', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '\'n uur', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '\'n uur', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ure', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ure', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ure', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '\'n dag', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '\'n dag', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dae', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '\'n dag', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dae', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dae', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '\'n maand', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '\'n maand', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '\'n maand', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 maande', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 maande', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 maande', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '\'n maand', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 maande', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '\'n jaar', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 jaar', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '\'n jaar', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 jaar', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'oor \'n paar sekondes', 'prefix'); assert.equal(moment(0).from(30000), '\'n paar sekondes gelede', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), '\'n paar sekondes gelede', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'oor \'n paar sekondes', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'oor 5 dae', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Vandag om 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Vandag om 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Vandag om 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Mre om 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Vandag om 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Gister om 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [om] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [om] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [om] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[Laas] dddd [om] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[Laas] dddd [om] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[Laas] dddd [om] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52ste', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1ste', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1ste', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2de', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2de', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('ar-ma'); test('parse', function (assert) { var tests = ':_:_:_:_:_:_:_:_:_:_:_:'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(':'); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', ', 14 2010, 3:25:50 pm'], ['ddd, hA', ', 3PM'], ['M Mo MM MMMM MMM', '2 2 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '8 8 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LT', '15:25'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 2010'], ['LLL', '14 2010 15:25'], ['LLLL', ' 14 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 2010'], ['lll', '14 2010 15:25'], ['llll', ' 14 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), '', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' 5 ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 31]).format('w ww wo'), '1 01 1', 'Dec 31 2011 should be week 1'); assert.equal(moment([2012, 0, 6]).format('w ww wo'), '1 01 1', 'Jan 6 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '2 02 2', 'Jan 7 2012 should be week 2'); assert.equal(moment([2012, 0, 13]).format('w ww wo'), '2 02 2', 'Jan 13 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '3 03 3', 'Jan 14 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('ar-sa'); test('parse', function (assert) { var tests = ':_:_:_:_:_:_:_:_:_:_:_:'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1) + ' instead is month ' + moment(input, mmm).month()); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(':'); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', ' :: '], ['ddd, hA', ' '], ['M Mo MM MMMM MMM', ' '], ['YYYY YY', ' '], ['D Do DD', ' '], ['d do dddd ddd dd', ' '], ['DDD DDDo DDDD', ' '], ['w wo ww', ' '], ['h hh', ' '], ['H HH', ' '], ['m mm', ' '], ['s ss', ' '], ['a A', ' '], ['[the] DDDo [day of the year]', 'the day of the year'], ['LT', ':'], ['LTS', '::'], ['L', '//'], ['LL', ' '], ['LLL', ' :'], ['LLLL', ' :'], ['l', '//'], ['ll', ' '], ['lll', ' :'], ['llll', ' :'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '', '31'); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), '', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), ' ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), ' ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), ' ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), ' ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), ' ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), ' ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), ' ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), ' ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), ' ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), ' ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), ' ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), ' ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), ' ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), ' ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' :', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' :', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' :', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' :', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' :', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' :', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting wednesday custom', function (assert) { assert.equal(moment('2003 1 6', 'gggg w d').format('YYYY-MM-DD'), '--', 'Week 1 of 2003 should be Dec 28 2002'); assert.equal(moment('2003 1 0', 'gggg w e').format('YYYY-MM-DD'), '--', 'Week 1 of 2003 should be Dec 28 2002'); assert.equal(moment('2003 1 6', 'gggg w d').format('gggg w d'), ' ', 'Saturday of week 1 of 2003 parsed should be formatted as 2003 1 6'); assert.equal(moment('2003 1 0', 'gggg w e').format('gggg w e'), ' ', '1st day of week 1 of 2003 parsed should be formatted as 2003 1 0'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 31]).format('w ww wo'), ' ', 'Dec 31 2011 should be week 1'); assert.equal(moment([2012, 0, 6]).format('w ww wo'), ' ', 'Jan 6 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), ' ', 'Jan 7 2012 should be week 2'); assert.equal(moment([2012, 0, 13]).format('w ww wo'), ' ', 'Jan 13 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), ' ', 'Jan 14 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('ar-tn'); test('parse', function (assert) { var tests = ':_:_:_:_:_:_:_:_:_:_:_:'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(':'); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', ', 14 2010, 3:25:50 pm'], ['ddd, hA', ', 3PM'], ['M Mo MM MMMM MMM', '2 2 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '6 6 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LT', '15:25'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 2010'], ['LLL', '14 2010 15:25'], ['LLLL', ' 14 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 2010'], ['lll', '14 2010 15:25'], ['llll', ' 14 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({ s: 44 }), true), '', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({ s: 45 }), true), '', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({ s: 89 }), true), '', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({ s: 90 }), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({ m: 44 }), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({ m: 45 }), true), '', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({ m: 89 }), true), '', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({ m: 90 }), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({ h: 5 }), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({ h: 21 }), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({ h: 22 }), true), '', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({ h: 35 }), true), '', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({ h: 36 }), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 1 }), true), '', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 5 }), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 25 }), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 26 }), true), '', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 30 }), true), '', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 43 }), true), '', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 46 }), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 74 }), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 76 }), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({ M: 1 }), true), '', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({ M: 5 }), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 345 }), true), '', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 548 }), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({ y: 1 }), true), '', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({ y: 5 }), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({ s: 30 }).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({ d: 5 }).fromNow(), ' 5 ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({ d: i }); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({ d: i }); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({ w: 1 }), weeksFromNow = moment().add({ w: 1 }); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({ w: 2 }); weeksFromNow = moment().add({ w: 2 }); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('ar'); var months = [ ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' ]; test('parse', function (assert) { var tests = months, i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1) + ' instead is month ' + moment(input, mmm).month()); } for (i = 0; i < 12; i++) { equalTest(tests[i], 'MMM', i); equalTest(tests[i], 'MMM', i); equalTest(tests[i], 'MMMM', i); equalTest(tests[i], 'MMMM', i); equalTest(tests[i].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', ' :: '], ['ddd, hA', ' '], ['M Mo MM MMMM MMM', ' '], ['YYYY YY', ' '], ['D Do DD', ' '], ['d do dddd ddd dd', ' '], ['DDD DDDo DDDD', ' '], ['w wo ww', ' '], ['h hh', ' '], ['H HH', ' '], ['m mm', ' '], ['s ss', ' '], ['a A', ' '], ['[the] DDDo [day of the year]', 'the day of the year'], ['LT', ':'], ['LTS', '::'], ['L', '/\u200f/\u200f'], ['LL', ' '], ['LLL', ' :'], ['LLLL', ' :'], ['l', '/\u200f/\u200f'], ['ll', ' '], ['lll', ' :'], ['llll', ' :'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '', '31'); }); test('format month', function (assert) { var expected = months, i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM'), expected[i], expected[i]); assert.equal(moment([2011, i, 1]).format('MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), ' ', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), ' ', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), ' ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), ' ', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), ' ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), ' ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), ' ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), ' ', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), ' ', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), ' ', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), ' ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), ' ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), ' ', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), ' ', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), ' ', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), ' ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), ' ', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), ' ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), ' ', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), ' ', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), ' ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' :', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' :', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' :', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' :', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' :', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' :', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting wednesday custom', function (assert) { assert.equal(moment('2003 1 6', 'gggg w d').format('YYYY-MM-DD'), '--', 'Week 1 of 2003 should be Dec 28 2002'); assert.equal(moment('2003 1 0', 'gggg w e').format('YYYY-MM-DD'), '--', 'Week 1 of 2003 should be Dec 28 2002'); assert.equal(moment('2003 1 6', 'gggg w d').format('gggg w d'), ' ', 'Saturday of week 1 of 2003 parsed should be formatted as 2003 1 6'); assert.equal(moment('2003 1 0', 'gggg w e').format('gggg w e'), ' ', '1st day of week 1 of 2003 parsed should be formatted as 2003 1 0'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 31]).format('w ww wo'), ' ', 'Dec 31 2011 should be week 1'); assert.equal(moment([2012, 0, 6]).format('w ww wo'), ' ', 'Jan 6 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), ' ', 'Jan 7 2012 should be week 2'); assert.equal(moment([2012, 0, 13]).format('w ww wo'), ' ', 'Jan 13 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), ' ', 'Jan 14 2012 should be week 3'); }); test('no leading zeros in long date formats', function (assert) { var i, j, longDateStr, shortDateStr; for (i = 1; i <= 9; ++i) { for (j = 1; j <= 9; ++j) { longDateStr = moment([2014, i, j]).format('L'); shortDateStr = moment([2014, i, j]).format('l'); assert.equal(longDateStr, shortDateStr, 'should not have leading zeros in month or day'); } } }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('az'); test('parse', function (assert) { var tests = 'yanvar yan_fevral fev_mart mar_Aprel apr_may may_iyun iyn_iyul iyl_Avqust avq_sentyabr sen_oktyabr okt_noyabr noy_dekabr dek'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, D MMMM YYYY, HH:mm:ss', 'Bazar, 14 fevral 2010, 15:25:50'], ['ddd, A h', 'Baz, gndz 3'], ['M Mo MM MMMM MMM', '2 2-nci 02 fevral fev'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14-nc 14'], ['d do dddd ddd dd', '0 0-nc Bazar Baz Bz'], ['DDD DDDo DDDD', '45 45-inci 045'], ['w wo ww', '7 7-nci 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'gndz gndz'], ['[ilin] DDDo [gn]', 'ilin 45-inci gn'], ['LT', '15:25'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14 fevral 2010'], ['LLL', '14 fevral 2010 15:25'], ['LLLL', 'Bazar, 14 fevral 2010 15:25'], ['l', '14.2.2010'], ['ll', '14 fev 2010'], ['lll', '14 fev 2010 15:25'], ['llll', 'Baz, 14 fev 2010 15:25'] ], DDDo = [ [359, '360-nc'], [199, '200-nc'], [149, '150-nci'] ], dt = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), DDDoDt, i; for (i = 0; i < a.length; i++) { assert.equal(dt.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } for (i = 0; i < DDDo.length; i++) { DDDoDt = moment([2010]); assert.equal(DDDoDt.add(DDDo[i][0], 'days').format('DDDo'), DDDo[i][1], DDDo[i][0] + ' ---> ' + DDDo[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1-inci', '1st'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2-nci', '2nd'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3-nc', '3rd'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4-nc', '4th'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5-inci', '5th'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6-nc', '6th'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7-nci', '7th'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8-inci', '8th'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9-uncu', '9th'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10-uncu', '10th'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11-inci', '11th'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12-nci', '12th'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13-nc', '13th'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14-nc', '14th'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15-inci', '15th'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16-nc', '16th'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17-nci', '17th'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18-inci', '18th'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19-uncu', '19th'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20-nci', '20th'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21-inci', '21th'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22-nci', '22th'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23-nc', '23th'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24-nc', '24th'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25-inci', '25th'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26-nc', '26th'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27-nci', '27th'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28-inci', '28th'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29-uncu', '29th'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30-uncu', '30th'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31-inci', '31st'); }); test('format month', function (assert) { var expected = 'yanvar yan_fevral fev_mart mar_aprel apr_may may_iyun iyn_iyul iyl_avqust avq_sentyabr sen_oktyabr okt_noyabr noy_dekabr dek'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Bazar Baz Bz_Bazar ertsi BzE BE_rnb axam Ax A_rnb r _Cm axam CAx CA_Cm Cm C_nb n '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'birne saniyy', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'bir dqiq', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'bir dqiq', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 dqiq', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 dqiq', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'bir saat', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'bir saat', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 saat', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 saat', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 saat', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'bir gn', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'bir gn', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 gn', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'bir gn', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 gn', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 gn', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'bir ay', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'bir ay', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ay', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ay', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ay', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'bir ay', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ay', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'bir il', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 il', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'bir il', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 il', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'birne saniyy sonra', 'prefix'); assert.equal(moment(0).from(30000), 'birne saniyy vvl', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'birne saniyy vvl', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'birne saniyy sonra', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), '5 gn sonra', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'bugn saat 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'bugn saat 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'bugn saat 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'sabah saat 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'bugn saat 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'dnn 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('[gln hft] dddd [saat] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[gln hft] dddd [saat] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[gln hft] dddd [saat] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[ken hft] dddd [saat] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[ken hft] dddd [saat] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[ken hft] dddd [saat] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1-inci', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1-inci', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2-nci', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2-nci', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-nc', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('be'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, HH:mm:ss', ', 14- 2010, 15:25:50'], ['ddd, h A', ', 3 '], ['M Mo MM MMMM MMM', '2 2- 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14- 14'], ['d do dddd ddd dd', '0 0- '], ['DDD DDDo DDDD', '45 45- 045'], ['w wo ww', '7 7- 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', ' '], ['DDDo [ ]', '45- '], ['LT', '15:25'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14 2010 .'], ['LLL', '14 2010 ., 15:25'], ['LLLL', ', 14 2010 ., 15:25'], ['l', '14.2.2010'], ['ll', '14 2010 .'], ['lll', '14 2010 ., 15:25'], ['llll', ', 14 2010 ., 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format meridiem', function (assert) { assert.equal(moment([2012, 11, 28, 0, 0]).format('A'), '', 'night'); assert.equal(moment([2012, 11, 28, 3, 59]).format('A'), '', 'night'); assert.equal(moment([2012, 11, 28, 4, 0]).format('A'), '', 'morning'); assert.equal(moment([2012, 11, 28, 11, 59]).format('A'), '', 'morning'); assert.equal(moment([2012, 11, 28, 12, 0]).format('A'), '', 'afternoon'); assert.equal(moment([2012, 11, 28, 16, 59]).format('A'), '', 'afternoon'); assert.equal(moment([2012, 11, 28, 17, 0]).format('A'), '', 'evening'); assert.equal(moment([2012, 11, 28, 23, 59]).format('A'), '', 'evening'); }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1-', '1-'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2-', '2-'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3-', '3-'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4-', '4-'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5-', '5-'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6-', '6-'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7-', '7-'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8-', '8-'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9-', '9-'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10-', '10-'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11-', '11-'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12-', '12-'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13-', '13-'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14-', '14-'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15-', '15-'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16-', '16-'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17-', '17-'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18-', '18-'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19-', '19-'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20-', '20-'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21-', '21-'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22-', '22-'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23-', '23-'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24-', '24-'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25-', '25-'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26-', '26-'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27-', '27-'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28-', '28-'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29-', '29-'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30-', '30-'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31-', '31-'); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format month case', function (assert) { var months = { 'nominative': '___________'.split('_'), 'accusative': '___________'.split('_') }, i; for (i = 0; i < 12; i++) { assert.equal(moment([2011, i, 1]).format('D MMMM'), '1 ' + months.accusative[i], '1 ' + months.accusative[i]); assert.equal(moment([2011, i, 1]).format('MMMM'), months.nominative[i], '1 ' + months.nominative[i]); } }); test('format month case with escaped symbols', function (assert) { var months = { 'nominative': '___________'.split('_'), 'accusative': '___________'.split('_') }, i; for (i = 0; i < 12; i++) { assert.equal(moment([2013, i, 1]).format('D[] MMMM'), '1 ' + months.accusative[i], '1 ' + months.accusative[i]); assert.equal(moment([2013, i, 1]).format('[<i>]D[</i>] [<b>]MMMM[</b>]'), '<i>1</i> <b>' + months.accusative[i] + '</b>', '1 <b>' + months.accusative[i] + '</b>'); assert.equal(moment([2013, i, 1]).format('D[- ] MMMM'), '1- ' + months.accusative[i], '1- ' + months.accusative[i]); assert.equal(moment([2013, i, 1]).format('D, MMMM'), '1, ' + months.nominative[i], '1, ' + months.nominative[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 31}), true), '31 ', '31 minutes = 31 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 11}), true), '11 ', '11 days = 11 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 21}), true), '21 ', '21 days = 21 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' 5 ', 'in 5 days'); assert.equal(moment().add({m: 31}).fromNow(), ' 31 ', 'in 31 minutes = in 31 minutes'); assert.equal(moment().subtract({m: 31}).fromNow(), '31 ', '31 minutes ago = 31 minutes ago'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; function makeFormat(d) { return '[] dddd [] LT'; } for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; function makeFormat(d) { switch (d.day()) { case 0: case 3: case 5: case 6: return '[ ] dddd [] LT'; case 1: case 2: case 4: return '[ ] dddd [] LT'; } } for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1-', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1-', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2-', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2-', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('bg'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, H:mm:ss', ', 14- 2010, 15:25:50'], ['ddd, hA', ', 3PM'], ['M Mo MM MMMM MMM', '2 2- 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14- 14'], ['d do dddd ddd dd', '0 0- '], ['DDD DDDo DDDD', '45 45- 045'], ['w wo ww', '7 7- 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45- day of the year'], ['LT', '15:25'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14 2010'], ['LLL', '14 2010 15:25'], ['LLLL', ', 14 2010 15:25'], ['l', '14.2.2010'], ['ll', '14 2010'], ['lll', '14 2010 15:25'], ['llll', ', 14 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1-', '1-'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2-', '2-'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3-', '3-'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4-', '4-'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5-', '5-'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6-', '6-'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7-', '7-'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8-', '8-'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9-', '9-'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10-', '10-'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11-', '11-'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12-', '12-'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13-', '13-'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14-', '14-'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15-', '15-'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16-', '16-'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17-', '17-'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18-', '18-'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19-', '19-'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20-', '20-'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21-', '21-'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22-', '22-'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23-', '23-'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24-', '24-'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25-', '25-'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26-', '26-'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27-', '27-'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28-', '28-'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29-', '29-'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30-', '30-'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31-', '31-'); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' 5 ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; function makeFormat(d) { switch (d.day()) { case 0: case 3: case 6: return '[ ] dddd [] LT'; case 1: case 2: case 4: case 5: return '[ ] dddd [] LT'; } } for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1-', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1-', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2-', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2-', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('bn'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, a h:mm:ss ', ', , :: '], ['ddd, a h ', ', '], ['M Mo MM MMMM MMM', ' '], ['YYYY YY', ' '], ['D Do DD', ' '], ['d do dddd ddd dd', ' '], ['DDD DDDo DDDD', ' '], ['w wo ww', ' '], ['h hh', ' '], ['H HH', ' '], ['m mm', ' '], ['s ss', ' '], ['a A', ' '], ['LT', ' : '], ['LTS', ' :: '], ['L', '//'], ['LL', ' '], ['LLL', ' , : '], ['LLLL', ', , : '], ['l', '//'], ['ll', ' '], ['lll', ' , : '], ['llll', ', , : '] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 2]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 3]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 4]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 5]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 6]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 7]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 8]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 9]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 10]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 11]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 12]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 13]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 14]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 15]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 16]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 17]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 18]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 19]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 20]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 21]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 22]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 23]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 24]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 25]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 26]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 27]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 28]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 29]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 30]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 31]).format('DDDo'), '', ''); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), ' ', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), ' ', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), ' ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), ' ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), ' ', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), ' ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), ' ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), ' ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), ' ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), ' ', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), ' ', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), ' ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), ' ', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), ' ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), ' ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), ' ', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), ' ', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), ' ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), ' ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), ' ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), ' ', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), ' ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), ' ', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), ' ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), ' ', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), ' ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', ' '); assert.equal(moment().add({d: 5}).fromNow(), ' ', ' '); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' : ', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' : ', 'Now plus 25 min'); assert.equal(moment(a).add({h: 3}).calendar(), ' : ', 'Now plus 3 hours'); assert.equal(moment(a).add({d: 1}).calendar(), ' : ', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' : ', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' : ', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('meridiem', function (assert) { assert.equal(moment([2011, 2, 23, 2, 30]).format('a'), '', 'before dawn'); assert.equal(moment([2011, 2, 23, 9, 30]).format('a'), '', 'morning'); assert.equal(moment([2011, 2, 23, 14, 30]).format('a'), '', 'during day'); assert.equal(moment([2011, 2, 23, 17, 30]).format('a'), '', 'evening'); assert.equal(moment([2011, 2, 23, 19, 30]).format('a'), '', 'late evening'); assert.equal(moment([2011, 2, 23, 21, 20]).format('a'), '', 'night'); assert.equal(moment([2011, 2, 23, 2, 30]).format('A'), '', 'before dawn'); assert.equal(moment([2011, 2, 23, 9, 30]).format('A'), '', 'morning'); assert.equal(moment([2011, 2, 23, 14, 30]).format('A'), '', ' during day'); assert.equal(moment([2011, 2, 23, 17, 30]).format('A'), '', 'evening'); assert.equal(moment([2011, 2, 23, 19, 30]).format('A'), '', 'late evening'); assert.equal(moment([2011, 2, 23, 21, 20]).format('A'), '', 'night'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), ' ', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), ' ', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), ' ', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), ' ', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), ' ', 'Jan 15 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('bo'); test('parse', function (assert) { var tests = ' ._ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, a h:mm:ss ', ', , :: '], ['ddd, a h ', ', '], ['M Mo MM MMMM MMM', ' '], ['YYYY YY', ' '], ['D Do DD', ' '], ['d do dddd ddd dd', ' '], ['DDD DDDo DDDD', ' '], ['w wo ww', ' '], ['h hh', ' '], ['H HH', ' '], ['m mm', ' '], ['s ss', ' '], ['a A', ' '], ['LT', ' :'], ['LTS', ' ::'], ['L', '//'], ['LL', ' '], ['LLL', ' , :'], ['LLLL', ', , :'], ['l', '//'], ['ll', ' '], ['lll', ' , :'], ['llll', ', , :'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 2]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 3]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 4]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 5]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 6]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 7]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 8]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 9]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 10]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 11]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 12]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 13]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 14]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 15]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 16]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 17]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 18]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 19]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 20]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 21]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 22]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 23]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 24]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 25]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 26]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 27]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 28]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 29]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 30]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 31]).format('DDDo'), '', ''); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), '', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), ' ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), ' ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), ' ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), ' ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), ' ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), ' ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), ' ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), ' ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), ' ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), ' ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), ' ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), ' ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), ' ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), ' ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', ' '); assert.equal(moment().add({d: 5}).fromNow(), ' ', ' '); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' :', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' :', 'Now plus 25 min'); assert.equal(moment(a).add({h: 3}).calendar(), ' :', 'Now plus 3 hours'); assert.equal(moment(a).add({d: 1}).calendar(), ' :', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' :', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' :', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('[][,] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[][,] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[][,] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('meridiem', function (assert) { assert.equal(moment([2011, 2, 23, 2, 30]).format('a'), '', 'before dawn'); assert.equal(moment([2011, 2, 23, 9, 30]).format('a'), '', 'morning'); assert.equal(moment([2011, 2, 23, 14, 30]).format('a'), '', 'during day'); assert.equal(moment([2011, 2, 23, 17, 30]).format('a'), '', 'evening'); assert.equal(moment([2011, 2, 23, 19, 30]).format('a'), '', 'late evening'); assert.equal(moment([2011, 2, 23, 21, 20]).format('a'), '', 'night'); assert.equal(moment([2011, 2, 23, 2, 30]).format('A'), '', 'before dawn'); assert.equal(moment([2011, 2, 23, 9, 30]).format('A'), '', 'morning'); assert.equal(moment([2011, 2, 23, 14, 30]).format('A'), '', ' during day'); assert.equal(moment([2011, 2, 23, 17, 30]).format('A'), '', 'evening'); assert.equal(moment([2011, 2, 23, 19, 30]).format('A'), '', 'late evening'); assert.equal(moment([2011, 2, 23, 21, 20]).format('A'), '', 'night'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), ' ', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), ' ', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), ' ', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), ' ', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), ' ', 'Jan 15 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('br'); test('parse', function (assert) { var tests = 'Genver Gen_C\'hwevrer C\'hwe_Meurzh Meu_Ebrel Ebr_Mae Mae_Mezheven Eve_Gouere Gou_Eost Eos_Gwengolo Gwe_Here Her_Du Du_Kerzu Ker'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { moment.locale('br'); var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Sul, C\'hwevrer 14vet 2010, 3:25:50 pm'], ['ddd, h A', 'Sul, 3 PM'], ['M Mo MM MMMM MMM', '2 2vet 02 C\'hwevrer C\'hwe'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14vet 14'], ['d do dddd ddd dd', '0 0vet Sul Sul Su'], ['DDD DDDo DDDD', '45 45vet 045'], ['w wo ww', '6 6vet 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['DDDo [devezh] [ar] [vloaz]', '45vet devezh ar vloaz'], ['L', '14/02/2010'], ['LL', '14 a viz C\'hwevrer 2010'], ['LLL', '14 a viz C\'hwevrer 2010 3e25 PM'], ['LLLL', 'Sul, 14 a viz C\'hwevrer 2010 3e25 PM'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { moment.locale('br'); assert.equal(moment([2011, 0, 1]).format('DDDo'), '1a', '1a'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2vet', '2vet'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3vet', '3vet'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4vet', '4vet'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5vet', '5vet'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6vet', '6vet'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7vet', '7vet'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8vet', '8vet'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9vet', '9vet'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10vet', '10vet'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11vet', '11vet'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12vet', '12vet'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13vet', '13vet'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14vet', '14vet'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15vet', '15vet'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16vet', '16vet'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17vet', '17vet'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18vet', '18vet'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19vet', '19vet'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20vet', '20vet'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21vet', '21vet'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22vet', '22vet'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23vet', '23vet'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24vet', '24vet'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25vet', '25vet'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26vet', '26vet'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27vet', '27vet'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28vet', '28vet'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29vet', '29vet'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30vet', '30vet'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31vet', '31vet'); }); test('format month', function (assert) { moment.locale('br'); var expected = 'Genver Gen_C\'hwevrer C\'hwe_Meurzh Meu_Ebrel Ebr_Mae Mae_Mezheven Eve_Gouere Gou_Eost Eos_Gwengolo Gwe_Here Her_Du Du_Kerzu Ker'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { moment.locale('br'); var expected = 'Sul Sul Su_Lun Lun Lu_Meurzh Meu Me_Merc\'her Mer Mer_Yaou Yao Ya_Gwener Gwe Gw_Sadorn Sad Sa'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { moment.locale('br'); var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'un nebeud segondenno', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'ur vunutenn', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'ur vunutenn', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 vunutenn', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 munutenn', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'un eur', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'un eur', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 eur', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 eur', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 eur', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'un devezh', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'un devezh', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 zevezh', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'un devezh', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 devezh', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 devezh', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'ur miz', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'ur miz', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'ur miz', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 viz', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 viz', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 miz', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'ur miz', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 miz', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'ur bloaz', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 vloaz', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'ur bloaz', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 bloaz', '5 years = 5 years'); }); test('suffix', function (assert) { moment.locale('br'); assert.equal(moment(30000).from(0), 'a-benn un nebeud segondenno', 'prefix'); assert.equal(moment(0).from(30000), 'un nebeud segondenno \'zo', 'suffix'); }); test('now from now', function (assert) { moment.locale('br'); assert.equal(moment().fromNow(), 'un nebeud segondenno \'zo', 'now from now should display as in the past'); }); test('fromNow', function (assert) { moment.locale('br'); assert.equal(moment().add({s: 30}).fromNow(), 'a-benn un nebeud segondenno', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'a-benn 5 devezh', 'in 5 days'); }); test('calendar day', function (assert) { moment.locale('br'); var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Hiziv da 12e00 PM', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Hiziv da 12e25 PM', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Hiziv da 1e00 PM', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Warc\'hoazh da 12e00 PM', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Hiziv da 11e00 AM', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Dec\'h da 12e00 PM', 'yesterday at the same time'); }); test('calendar next week', function (assert) { moment.locale('br'); var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [da] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [da] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [da] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { moment.locale('br'); var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [paset da] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [paset da] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [paset da] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { moment.locale('br'); var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('special mutations for years', function (assert) { moment.locale('br'); var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'ur bloaz', 'mutation 1 year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 2}), true), '2 vloaz', 'mutation 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 3}), true), '3 bloaz', 'mutation 3 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 4}), true), '4 bloaz', 'mutation 4 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 bloaz', 'mutation 5 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 9}), true), '9 bloaz', 'mutation 9 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 10}), true), '10 vloaz', 'mutation 10 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 21}), true), '21 bloaz', 'mutation 21 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 22}), true), '22 vloaz', 'mutation 22 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 133}), true), '133 bloaz', 'mutation 133 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 148}), true), '148 vloaz', 'mutation 148 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 261}), true), '261 bloaz', 'mutation 261 years'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('bs'); test('parse', function (assert) { var tests = 'januar jan._februar feb._mart mar._april apr._maj maj._juni jun._juli jul._august aug._septembar sep._oktobar okt._novembar nov._decembar dec.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1) + ' inp ' + mmm); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, h:mm:ss a', 'nedjelja, 14. februar 2010, 3:25:50 pm'], ['ddd, hA', 'ned., 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 februar feb.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. nedjelja ned. ne'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '7 7. 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['LTS', '15:25:50'], ['L', '14. 02. 2010'], ['LL', '14. februar 2010'], ['LLL', '14. februar 2010 15:25'], ['LLLL', 'nedjelja, 14. februar 2010 15:25'], ['l', '14. 2. 2010'], ['ll', '14. feb. 2010'], ['lll', '14. feb. 2010 15:25'], ['llll', 'ned., 14. feb. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'januar jan._februar feb._mart mar._april apr._maj maj._juni jun._juli jul._august aug._septembar sep._oktobar okt._novembar nov._decembar dec.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'nedjelja ned. ne_ponedjeljak pon. po_utorak uto. ut_srijeda sri. sr_etvrtak et. e_petak pet. pe_subota sub. su'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'par sekundi', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'jedna minuta', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'jedna minuta', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minute', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minuta', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'jedan sat', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'jedan sat', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 sata', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 sati', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 sati', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'dan', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'dan', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dana', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'dan', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dana', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dana', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'mjesec', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'mjesec', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'mjesec', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mjeseca', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mjeseca', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mjeseca', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'mjesec', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mjeseci', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'godinu', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 godine', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'godinu', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 godina', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'za par sekundi', 'prefix'); assert.equal(moment(0).from(30000), 'prije par sekundi', 'prefix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'prije par sekundi', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'za par sekundi', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'za 5 dana', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'danas u 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'danas u 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'danas u 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'sutra u 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'danas u 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'juer u 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; function makeFormat(d) { switch (d.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'; } } for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; function makeFormat(d) { switch (d.day()) { case 0: case 3: return '[prolu] dddd [u] LT'; case 6: return '[prole] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[proli] dddd [u] LT'; } } for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1.', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1.', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2.', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2.', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3.', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('ca'); test('parse', function (assert) { var tests = 'gener gen._febrer febr._mar mar._abril abr._maig mai._juny jun._juliol jul._agost ag._setembre set._octubre oct._novembre nov._desembre des.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, h:mm:ss a', 'diumenge, 14 febrer 2010, 3:25:50 pm'], ['ddd, hA', 'dg., 3PM'], ['M Mo MM MMMM MMM', '2 2n 02 febrer febr.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 diumenge dg. Dg'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '6 6a 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 febrer 2010'], ['LLL', '14 febrer 2010 15:25'], ['LLLL', 'diumenge 14 febrer 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 febr. 2010'], ['lll', '14 febr. 2010 15:25'], ['llll', 'dg. 14 febr. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1r', '1r'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2n', '2n'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3r', '3r'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4t', '4t'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = 'gener gen._febrer febr._mar mar._abril abr._maig mai._juny jun._juliol jul._agost ag._setembre set._octubre oct._novembre nov._desembre des.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'diumenge dg. Dg_dilluns dl. Dl_dimarts dt. Dt_dimecres dc. Dc_dijous dj. Dj_divendres dv. Dv_dissabte ds. Ds'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'uns segons', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'un minut', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'un minut', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minuts', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minuts', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'una hora', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'una hora', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 hores', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 hores', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 hores', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'un dia', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'un dia', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dies', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'un dia', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dies', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dies', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'un mes', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'un mes', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'un mes', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mesos', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mesos', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mesos', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'un mes', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mesos', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'un any', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 anys', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'un any', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 anys', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'en uns segons', 'prefix'); assert.equal(moment(0).from(30000), 'fa uns segons', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'fa uns segons', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'en uns segons', 'en uns segons'); assert.equal(moment().add({d: 5}).fromNow(), 'en 5 dies', 'en 5 dies'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'avui a les 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'avui a les 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'avui a les 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'dem a les 12:00', 'tomorrow at the same time'); assert.equal(moment(a).add({d: 1, h : -1}).calendar(), 'dem a les 11:00', 'tomorrow minus 1 hour'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'avui a les 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'ahir a les 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [a ' + ((m.hours() !== 1) ? 'les' : 'la') + '] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [a ' + ((m.hours() !== 1) ? 'les' : 'la') + '] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [a ' + ((m.hours() !== 1) ? 'les' : 'la') + '] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[el] dddd [passat a ' + ((m.hours() !== 1) ? 'les' : 'la') + '] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[el] dddd [passat a ' + ((m.hours() !== 1) ? 'les' : 'la') + '] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[el] dddd [passat a ' + ((m.hours() !== 1) ? 'les' : 'la') + '] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52a', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1a', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1a', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2a', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2a', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('cs'); test('parse', function (assert) { var tests = 'leden led_nor no_bezen be_duben dub_kvten kv_erven vn_ervenec vc_srpen srp_z z_jen j_listopad lis_prosinec pro'.split('_'), i; function equalTest(input, mmm, monthIndex) { assert.equal(moment(input, mmm).month(), monthIndex, input + ' ' + mmm + ' should be month ' + (monthIndex + 1)); } function equalTestStrict(input, mmm, monthIndex) { assert.equal(moment(input, mmm, true).month(), monthIndex, input + ' ' + mmm + ' should be strict month ' + (monthIndex + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); equalTestStrict(tests[i][1], 'MMM', i); equalTestStrict(tests[i][0], 'MMMM', i); equalTestStrict(tests[i][1].toLocaleLowerCase(), 'MMM', i); equalTestStrict(tests[i][1].toLocaleUpperCase(), 'MMM', i); equalTestStrict(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTestStrict(tests[i][0].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss', 'nedle, nor 14. 2010, 3:25:50'], ['ddd, h', 'ne, 3'], ['M Mo MM MMMM MMM', '2 2. 02 nor no'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. nedle ne ne'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['DDDo [den v roce]', '45. den v roce'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14. nor 2010'], ['LLL', '14. nor 2010 15:25'], ['LLLL', 'nedle 14. nor 2010 15:25'], ['l', '14.2.2010'], ['ll', '14. no 2010'], ['lll', '14. no 2010 15:25'], ['llll', 'ne 14. no 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'leden led_nor no_bezen be_duben dub_kvten kv_erven vn_ervenec vc_srpen srp_z z_jen j_listopad lis_prosinec pro'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'nedle ne ne_pondl po po_ter t t_steda st st_tvrtek t t_ptek p p_sobota so so'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'pr sekund', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'minuta', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'minuta', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minuty', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minut', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'hodina', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'hodina', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 hodiny', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 hodin', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 hodin', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'den', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'den', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dny', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'den', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dn', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dn', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'msc', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'msc', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'msc', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 msce', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 msce', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 msce', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'msc', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 msc', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'rok', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 roky', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'rok', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 let', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'za pr sekund', 'prefix'); assert.equal(moment(0).from(30000), 'ped pr sekundami', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'ped pr sekundami', 'now from now should display as in the past'); }); test('fromNow (future)', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'za pr sekund', 'in a few seconds'); assert.equal(moment().add({m: 1}).fromNow(), 'za minutu', 'in a minute'); assert.equal(moment().add({m: 3}).fromNow(), 'za 3 minuty', 'in 3 minutes'); assert.equal(moment().add({m: 10}).fromNow(), 'za 10 minut', 'in 10 minutes'); assert.equal(moment().add({h: 1}).fromNow(), 'za hodinu', 'in an hour'); assert.equal(moment().add({h: 3}).fromNow(), 'za 3 hodiny', 'in 3 hours'); assert.equal(moment().add({h: 10}).fromNow(), 'za 10 hodin', 'in 10 hours'); assert.equal(moment().add({d: 1}).fromNow(), 'za den', 'in a day'); assert.equal(moment().add({d: 3}).fromNow(), 'za 3 dny', 'in 3 days'); assert.equal(moment().add({d: 10}).fromNow(), 'za 10 dn', 'in 10 days'); assert.equal(moment().add({M: 1}).fromNow(), 'za msc', 'in a month'); assert.equal(moment().add({M: 3}).fromNow(), 'za 3 msce', 'in 3 months'); assert.equal(moment().add({M: 10}).fromNow(), 'za 10 msc', 'in 10 months'); assert.equal(moment().add({y: 1}).fromNow(), 'za rok', 'in a year'); assert.equal(moment().add({y: 3}).fromNow(), 'za 3 roky', 'in 3 years'); assert.equal(moment().add({y: 10}).fromNow(), 'za 10 let', 'in 10 years'); }); test('fromNow (past)', function (assert) { assert.equal(moment().subtract({s: 30}).fromNow(), 'ped pr sekundami', 'a few seconds ago'); assert.equal(moment().subtract({m: 1}).fromNow(), 'ped minutou', 'a minute ago'); assert.equal(moment().subtract({m: 3}).fromNow(), 'ped 3 minutami', '3 minutes ago'); assert.equal(moment().subtract({m: 10}).fromNow(), 'ped 10 minutami', '10 minutes ago'); assert.equal(moment().subtract({h: 1}).fromNow(), 'ped hodinou', 'an hour ago'); assert.equal(moment().subtract({h: 3}).fromNow(), 'ped 3 hodinami', '3 hours ago'); assert.equal(moment().subtract({h: 10}).fromNow(), 'ped 10 hodinami', '10 hours ago'); assert.equal(moment().subtract({d: 1}).fromNow(), 'ped dnem', 'a day ago'); assert.equal(moment().subtract({d: 3}).fromNow(), 'ped 3 dny', '3 days ago'); assert.equal(moment().subtract({d: 10}).fromNow(), 'ped 10 dny', '10 days ago'); assert.equal(moment().subtract({M: 1}).fromNow(), 'ped mscem', 'a month ago'); assert.equal(moment().subtract({M: 3}).fromNow(), 'ped 3 msci', '3 months ago'); assert.equal(moment().subtract({M: 10}).fromNow(), 'ped 10 msci', '10 months ago'); assert.equal(moment().subtract({y: 1}).fromNow(), 'ped rokem', 'a year ago'); assert.equal(moment().subtract({y: 3}).fromNow(), 'ped 3 lety', '3 years ago'); assert.equal(moment().subtract({y: 10}).fromNow(), 'ped 10 lety', '10 years ago'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'dnes v 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'dnes v 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'dnes v 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'ztra v 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'dnes v 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'vera v 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m, nextDay; for (i = 2; i < 7; i++) { m = moment().add({d: i}); nextDay = ''; switch (m.day()) { case 0: nextDay = 'v nedli'; break; case 1: nextDay = 'v pondl'; break; case 2: nextDay = 'v ter'; break; case 3: nextDay = 've stedu'; break; case 4: nextDay = 've tvrtek'; break; case 5: nextDay = 'v ptek'; break; case 6: nextDay = 'v sobotu'; break; } assert.equal(m.calendar(), m.format('[' + nextDay + '] [v] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[' + nextDay + '] [v] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[' + nextDay + '] [v] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m, lastDay; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); lastDay = ''; switch (m.day()) { case 0: lastDay = 'minulou nedli'; break; case 1: lastDay = 'minul pondl'; break; case 2: lastDay = 'minul ter'; break; case 3: lastDay = 'minulou stedu'; break; case 4: lastDay = 'minul tvrtek'; break; case 5: lastDay = 'minul ptek'; break; case 6: lastDay = 'minulou sobotu'; break; } assert.equal(m.calendar(), m.format('[' + lastDay + '] [v] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[' + lastDay + '] [v] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[' + lastDay + '] [v] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('humanize duration', function (assert) { assert.equal(moment.duration(1, 'minutes').humanize(), 'minuta', 'a minute (future)'); assert.equal(moment.duration(1, 'minutes').humanize(true), 'za minutu', 'in a minute'); assert.equal(moment.duration(-1, 'minutes').humanize(), 'minuta', 'a minute (past)'); assert.equal(moment.duration(-1, 'minutes').humanize(true), 'ped minutou', 'a minute ago'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('cv'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', ', 14- 2010, 3:25:50 pm'], ['ddd, hA', ', 3PM'], ['M Mo MM MMMM MMM', '2 2- 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14- 14'], ['d do dddd ddd dd', '0 0- '], ['DDD DDDo DDDD', '45 45- 045'], ['w wo ww', '7 7- 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], [' DDDo ', ' 45- '], ['LTS', '15:25:50'], ['L', '14-02-2010'], ['LL', '2010 14-'], ['LLL', '2010 14-, 15:25'], ['LLLL', ', 2010 14-, 15:25'], ['l', '14-2-2010'], ['ll', '2010 14-'], ['lll', '2010 14-, 15:25'], ['llll', ', 2010 14-, 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1-', '1-'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2-', '2-'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3-', '3-'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4-', '4-'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5-', '5-'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6-', '6-'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7-', '7-'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8-', '8-'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9-', '9-'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10-', '10-'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11-', '11-'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12-', '12-'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13-', '13-'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14-', '14-'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15-', '15-'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16-', '16-'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17-', '17-'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18-', '18-'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19-', '19-'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20-', '20-'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21-', '21-'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22-', '22-'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23-', '23-'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24-', '24-'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25-', '25-'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26-', '26-'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27-', '27-'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28-', '28-'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29-', '29-'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30-', '30-'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31-', '31-'); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), '- ', '44 sekunder = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), ' ', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), ' ', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), ' ', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), ' ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), ' ', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), ' ', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), ' ', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), ' ', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), ' ', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), ' ', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), ' ', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), ' ', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), ' ', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), '- ', 'prefix'); assert.equal(moment(0).from(30000), '- ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), '- ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), '- ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), '5 ', 'in 5 days'); assert.equal(moment().add({h: 2}).fromNow(), '2 ', 'in 2 hours, the right suffix!'); assert.equal(moment().add({y: 3}).fromNow(), '3 ', 'in 3 years, the right suffix!'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00 ', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25 ', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00 ', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00 ', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00 ', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00 ', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('[] dddd LT []'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd LT []'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd LT []'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[] dddd LT []'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd LT []'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd LT []'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); // Monday is the first day of the week. // The week that contains Jan 1st is the first week of the year. test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1-', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1-', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2-', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2-', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('cy'); test('parse', function (assert) { var tests = 'Ionawr Ion_Chwefror Chwe_Mawrth Maw_Ebrill Ebr_Mai Mai_Mehefin Meh_Gorffennaf Gor_Awst Aws_Medi Med_Hydref Hyd_Tachwedd Tach_Rhagfyr Rhag'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Dydd Sul, Chwefror 14eg 2010, 3:25:50 pm'], ['ddd, hA', 'Sul, 3PM'], ['M Mo MM MMMM MMM', '2 2il 02 Chwefror Chwe'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14eg 14'], ['d do dddd ddd dd', '0 0 Dydd Sul Sul Su'], ['DDD DDDo DDDD', '45 45ain 045'], ['w wo ww', '6 6ed 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45ain day of the year'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 Chwefror 2010'], ['LLL', '14 Chwefror 2010 15:25'], ['LLLL', 'Dydd Sul, 14 Chwefror 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 Chwe 2010'], ['lll', '14 Chwe 2010 15:25'], ['llll', 'Sul, 14 Chwe 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1af', '1af'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2il', '2il'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3ydd', '3ydd'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4ydd', '4ydd'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5ed', '5ed'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6ed', '6ed'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7ed', '7ed'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8fed', '8fed'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9fed', '9fed'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10fed', '10fed'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11eg', '11eg'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12fed', '12fed'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13eg', '13eg'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14eg', '14eg'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15fed', '15fed'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16eg', '16eg'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17eg', '17eg'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18fed', '18fed'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19eg', '19eg'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20fed', '20fed'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21ain', '21ain'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22ain', '22ain'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23ain', '23ain'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24ain', '24ain'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25ain', '25ain'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26ain', '26ain'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27ain', '27ain'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28ain', '28ain'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29ain', '29ain'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30ain', '30ain'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31ain', '31ain'); }); test('format month', function (assert) { var expected = 'Ionawr Ion_Chwefror Chwe_Mawrth Maw_Ebrill Ebr_Mai Mai_Mehefin Meh_Gorffennaf Gor_Awst Aws_Medi Med_Hydref Hyd_Tachwedd Tach_Rhagfyr Rhag'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Dydd Sul Sul Su_Dydd Llun Llun Ll_Dydd Mawrth Maw Ma_Dydd Mercher Mer Me_Dydd Iau Iau Ia_Dydd Gwener Gwe Gw_Dydd Sadwrn Sad Sa'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'ychydig eiliadau', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'munud', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'munud', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 munud', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 munud', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'awr', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'awr', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 awr', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 awr', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 awr', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'diwrnod', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'diwrnod', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 diwrnod', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'diwrnod', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 diwrnod', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 diwrnod', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'mis', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'mis', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'mis', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mis', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mis', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mis', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'mis', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mis', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'blwyddyn', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 flynedd', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'blwyddyn', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 flynedd', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'mewn ychydig eiliadau', 'prefix'); assert.equal(moment(0).from(30000), 'ychydig eiliadau yn l', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'mewn ychydig eiliadau', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'mewn 5 diwrnod', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Heddiw am 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Heddiw am 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Heddiw am 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Yfory am 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Heddiw am 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Ddoe am 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [am] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [am] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [am] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [diwethaf am] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [diwethaf am] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [diwethaf am] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52ain', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1af', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1af', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2il', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2il', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('da'); test('parse', function (assert) { var tests = 'januar jan_februar feb_marts mar_april apr_maj maj_juni jun_juli jul_august aug_september sep_oktober okt_november nov_december dec'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd [den] Do MMMM YYYY, h:mm:ss a', 'sndag den 14. februar 2010, 3:25:50 pm'], ['ddd hA', 'sn 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 februar feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. sndag sn s'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[den] DDDo [dag p ret]', 'den 45. dag p ret'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14. februar 2010'], ['LLL', '14. februar 2010 15:25'], ['LLLL', 'sndag d. 14. februar 2010 15:25'], ['l', '14/2/2010'], ['ll', '14. feb 2010'], ['lll', '14. feb 2010 15:25'], ['llll', 'sn d. 14. feb 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'januar jan_februar feb_marts mar_april apr_maj maj_juni jun_juli jul_august aug_september sep_oktober okt_november nov_december dec'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'sndag sn s_mandag man ma_tirsdag tir ti_onsdag ons on_torsdag tor to_fredag fre fr_lrdag lr l'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'f sekunder', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'et minut', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'et minut', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutter', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutter', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'en time', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'en time', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 timer', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 timer', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 timer', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'en dag', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'en dag', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dage', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'en dag', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dage', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dage', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'en mned', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'en mned', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'en mned', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mneder', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mneder', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mneder', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'en mned', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mneder', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'et r', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 r', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'et r', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 r', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'om f sekunder', 'prefix'); assert.equal(moment(0).from(30000), 'f sekunder siden', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'f sekunder siden', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'om f sekunder', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'om 5 dage', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'I dag kl. 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'I dag kl. 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'I dag kl. 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'I morgen kl. 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'I dag kl. 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'I gr kl. 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [kl.] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [kl.] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [kl.] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[sidste] dddd [kl] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[sidste] dddd [kl] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[sidste] dddd [kl] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('de-at'); test('parse', function (assert) { var tests = 'Jnner Jn._Februar Febr._Mrz Mrz._April Apr._Mai Mai_Juni Jun._Juli Jul._August Aug._September Sept._Oktober Okt._November Nov._Dezember Dez.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, h:mm:ss a', 'Sonntag, 14. Februar 2010, 3:25:50 pm'], ['ddd, hA', 'So., 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 Februar Febr.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. Sonntag So. So'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14. Februar 2010'], ['LLL', '14. Februar 2010 15:25'], ['LLLL', 'Sonntag, 14. Februar 2010 15:25'], ['l', '14.2.2010'], ['ll', '14. Febr. 2010'], ['lll', '14. Febr. 2010 15:25'], ['llll', 'So., 14. Febr. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'Jnner Jn._Februar Febr._Mrz Mrz._April Apr._Mai Mai_Juni Jun._Juli Jul._August Aug._September Sept._Oktober Okt._November Nov._Dezember Dez.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Sonntag So. So_Montag Mo. Mo_Dienstag Di. Di_Mittwoch Mi. Mi_Donnerstag Do. Do_Freitag Fr. Fr_Samstag Sa. Sa'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'ein paar Sekunden', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'eine Minute', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'eine Minute', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 Minuten', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 Minuten', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'eine Stunde', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'eine Stunde', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 Stunden', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 Stunden', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 Stunden', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'ein Tag', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'ein Tag', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 Tage', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'ein Tag', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 Tage', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 Tage', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'ein Monat', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'ein Monat', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 Monate', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 Monate', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 Monate', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'ein Monat', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 Monate', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'ein Jahr', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 Jahre', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'ein Jahr', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 Jahre', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'in ein paar Sekunden', 'prefix'); assert.equal(moment(0).from(30000), 'vor ein paar Sekunden', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'in ein paar Sekunden', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'in 5 Tagen', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'heute um 12:00 Uhr', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'heute um 12:25 Uhr', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'heute um 13:00 Uhr', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'morgen um 12:00 Uhr', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'heute um 11:00 Uhr', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'gestern um 12:00 Uhr', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [um] LT [Uhr]'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [um] LT [Uhr]'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [um] LT [Uhr]'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[letzten] dddd [um] LT [Uhr]'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[letzten] dddd [um] LT [Uhr]'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[letzten] dddd [um] LT [Uhr]'), 'Today + ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('de'); test('parse', function (assert) { var tests = 'Januar Jan._Februar Febr._Mrz Mrz._April Apr._Mai Mai_Juni Jun._Juli Jul._August Aug._September Sept._Oktober Okt._November Nov._Dezember Dez.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, h:mm:ss a', 'Sonntag, 14. Februar 2010, 3:25:50 pm'], ['ddd, hA', 'So., 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 Februar Febr.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. Sonntag So. So'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14. Februar 2010'], ['LLL', '14. Februar 2010 15:25'], ['LLLL', 'Sonntag, 14. Februar 2010 15:25'], ['l', '14.2.2010'], ['ll', '14. Febr. 2010'], ['lll', '14. Febr. 2010 15:25'], ['llll', 'So., 14. Febr. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'Januar Jan._Februar Febr._Mrz Mrz._April Apr._Mai Mai_Juni Jun._Juli Jul._August Aug._September Sept._Oktober Okt._November Nov._Dezember Dez.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Sonntag So. So_Montag Mo. Mo_Dienstag Di. Di_Mittwoch Mi. Mi_Donnerstag Do. Do_Freitag Fr. Fr_Samstag Sa. Sa'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'ein paar Sekunden', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'eine Minute', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'eine Minute', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 Minuten', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 Minuten', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'eine Stunde', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'eine Stunde', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 Stunden', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 Stunden', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 Stunden', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'ein Tag', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'ein Tag', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 Tage', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'ein Tag', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 Tage', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 Tage', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'ein Monat', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'ein Monat', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'ein Monat', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 Monate', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 Monate', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 Monate', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'ein Monat', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 Monate', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'ein Jahr', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 Jahre', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'ein Jahr', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 Jahre', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'in ein paar Sekunden', 'prefix'); assert.equal(moment(0).from(30000), 'vor ein paar Sekunden', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'in ein paar Sekunden', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'in 5 Tagen', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'heute um 12:00 Uhr', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'heute um 12:25 Uhr', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'heute um 13:00 Uhr', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'morgen um 12:00 Uhr', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'heute um 11:00 Uhr', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'gestern um 12:00 Uhr', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [um] LT [Uhr]'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [um] LT [Uhr]'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [um] LT [Uhr]'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[letzten] dddd [um] LT [Uhr]'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[letzten] dddd [um] LT [Uhr]'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[letzten] dddd [um] LT [Uhr]'), 'Today + ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('dv'); test('parse', function (assert) { var i, tests = [ '', '', '', '', '', '', '', '', '', '', '', '' ]; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { equalTest(tests[i], 'MMM', i); equalTest(tests[i], 'MMMM', i); equalTest(tests[i].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', ' 14 2010 3:25:50 '], ['ddd, hA', ' 3'], ['M Mo MM MMMM MMM', '2 2 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '8 8 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', ' '], ['LTS', '15:25:50'], ['L', '14/2/2010'], ['LL', '14 2010'], ['LLL', '14 2010 15:25'], ['LLLL', ' 14 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 2010'], ['lll', '14 2010 15:25'], ['llll', ' 14 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format month', function (assert) { var i, expected = [ '', '', '', '', '', '', '', '', '', '', '', '' ]; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM'), expected[i]); } }); test('format week', function (assert) { var i, expected = [ '', '', '', '', '', '', '' ]; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd'), expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), '', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), ' 2', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), ' 44', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), ' 2', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), ' 5', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), ' 21', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), ' 2', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), ' 5', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), ' 25', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), ' 2', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), ' 2', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), ' 3', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), ' 5', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), ' 2', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), ' 5', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' 5', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[] dddd LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('el'); test('parse', function (assert) { var i, tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'); function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('parse meridiem', function (assert) { var i, b = moment(), meridiemTests = [ // h a patterns, expected hours, isValid ['10 ', 10, true], ['10 ', 22, true], ['10 ..', 10, true], ['10 ..', 22, true], ['10 ', 10, true], ['10 ', 22, true], ['10 ', 10, true], ['10 ', 22, true], ['10 ..', 10, true], ['10 ..', 22, true], ['10 ', 10, true], ['10 ', 22, true], ['10 am', 10, false], ['10 pm', 10, false] ], parsed; // test that a formatted moment including meridiem string can be parsed back to the same moment assert.ok(b.isSame(moment(b.format('h:mm:ss a'), 'h:mm:ss a', 'el', true), 'seconds'), b.format('h:mm:ss a') + ' should be equal to ' + moment(b.format('h:mm:ss a'), 'h:mm:ss a', 'el', true).format('h:mm:ss a')); // test that a formatted moment having a meridiem string can be parsed with strict flag assert.ok(moment(b.format('h:mm:ss a'), 'h:mm:ss a', 'el', true).isValid(), b.format('h:mm:ss a') + ' should be parsed as valid'); for (i = 0; i < meridiemTests.length; i++) { parsed = moment(meridiemTests[i][0], 'h a', 'el', true); assert.equal(parsed.isValid(), meridiemTests[i][2], 'validity for ' + meridiemTests[i][0]); if (parsed.isValid()) { assert.equal(parsed.hours(), meridiemTests[i][1], 'hours for ' + meridiemTests[i][0]); } } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', ', 14 2010, 3:25:50 '], ['dddd, D MMMM YYYY, h:mm:ss a', ', 14 2010, 3:25:50 '], ['ddd, hA', ', 3'], ['dddd, MMMM YYYY', ', 2010'], ['M Mo MM MMMM MMM', '2 2 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '6 6 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', ' '], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LTS', '3:25:50 '], ['L', '14/02/2010'], ['LL', '14 2010'], ['LLL', '14 2010 3:25 '], ['LLLL', ', 14 2010 3:25 '], ['l', '14/2/2010'], ['ll', '14 2010'], ['lll', '14 2010 3:25 '], ['llll', ', 14 2010 3:25 '] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var i, expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var i, expected = ' _ _ _ _ _ _ '.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), ' ', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), ' ', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), ' ', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), ' ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), ' ', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), ' ', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), ' ', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), ' ', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), ' ', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), ' ', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), ' ', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), ' ', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), ' ', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' 5 ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00 ', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25 ', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 1:00 ', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00 ', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00 ', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00 ', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [' + (m.hours() % 12 === 1 ? '' : '') + '] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m, dayString; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); dayString = m.day() === 6 ? '[ ]' : '[ ] dddd'; assert.equal(m.calendar(), m.format(dayString + ' [' + (m.hours() % 12 === 1 ? '' : '') + '] LT'), 'Today - ' + i + ' days current time'); m.hours(1).minutes(30).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(dayString + ' [] LT'), 'Today - ' + i + ' days one o clock'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(dayString + ' [] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(dayString + ' [] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday format', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('en-au'); test('parse', function (assert) { var tests = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Sunday, February 14th 2010, 3:25:50 pm'], ['ddd, hA', 'Sun, 3PM'], ['M Mo MM MMMM MMM', '2 2nd 02 February Feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14th 14'], ['d do dddd ddd dd', '0 0th Sunday Sun Su'], ['DDD DDDo DDDD', '45 45th 045'], ['w wo ww', '6 6th 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45th day of the year'], ['LTS', '3:25:50 PM'], ['L', '14/02/2010'], ['LL', '14 February 2010'], ['LLL', '14 February 2010 3:25 PM'], ['LLLL', 'Sunday, 14 February 2010 3:25 PM'], ['l', '14/2/2010'], ['ll', '14 Feb 2010'], ['lll', '14 Feb 2010 3:25 PM'], ['llll', 'Sun, 14 Feb 2010 3:25 PM'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1st', '1st'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2nd', '2nd'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3rd', '3rd'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4th', '4th'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5th', '5th'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6th', '6th'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7th', '7th'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8th', '8th'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9th', '9th'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10th', '10th'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11th', '11th'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12th', '12th'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13th', '13th'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14th', '14th'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15th', '15th'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16th', '16th'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17th', '17th'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18th', '18th'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19th', '19th'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20th', '20th'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21st', '21st'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22nd', '22nd'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23rd', '23rd'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24th', '24th'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25th', '25th'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26th', '26th'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27th', '27th'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28th', '28th'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29th', '29th'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30th', '30th'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31st', '31st'); }); test('format month', function (assert) { var expected = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Sunday Sun Su_Monday Mon Mo_Tuesday Tue Tu_Wednesday Wed We_Thursday Thu Th_Friday Fri Fr_Saturday Sat Sa'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'a few seconds', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'a minute', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'a minute', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutes', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutes', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'an hour', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'an hour', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 hours', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 hours', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 hours', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'a day', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'a day', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 days', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'a day', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 days', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 days', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'a month', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'a month', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'a month', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 months', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 months', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 months', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'a month', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 months', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'a year', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 years', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'a year', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 years', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'in a few seconds', 'prefix'); assert.equal(moment(0).from(30000), 'a few seconds ago', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'a few seconds ago', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'in a few seconds', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'in 5 days', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Today at 12:00 PM', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Today at 12:25 PM', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Today at 1:00 PM', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Tomorrow at 12:00 PM', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Today at 11:00 AM', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Yesterday at 12:00 PM', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52nd', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1st', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1st', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2nd', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2nd', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('en-ca'); test('parse', function (assert) { var i, tests = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split('_'); function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Sunday, February 14th 2010, 3:25:50 pm'], ['ddd, hA', 'Sun, 3PM'], ['M Mo MM MMMM MMM', '2 2nd 02 February Feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14th 14'], ['d do dddd ddd dd', '0 0th Sunday Sun Su'], ['DDD DDDo DDDD', '45 45th 045'], ['w wo ww', '8 8th 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45th day of the year'], ['L', '2010-02-14'], ['LTS', '3:25:50 PM'], ['LL', 'February 14, 2010'], ['LLL', 'February 14, 2010 3:25 PM'], ['LLLL', 'Sunday, February 14, 2010 3:25 PM'], ['l', '2010-2-14'], ['ll', 'Feb 14, 2010'], ['lll', 'Feb 14, 2010 3:25 PM'], ['llll', 'Sun, Feb 14, 2010 3:25 PM'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1st', '1st'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2nd', '2nd'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3rd', '3rd'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4th', '4th'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5th', '5th'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6th', '6th'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7th', '7th'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8th', '8th'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9th', '9th'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10th', '10th'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11th', '11th'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12th', '12th'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13th', '13th'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14th', '14th'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15th', '15th'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16th', '16th'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17th', '17th'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18th', '18th'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19th', '19th'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20th', '20th'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21st', '21st'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22nd', '22nd'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23rd', '23rd'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24th', '24th'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25th', '25th'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26th', '26th'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27th', '27th'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28th', '28th'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29th', '29th'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30th', '30th'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31st', '31st'); }); test('format month', function (assert) { var i, expected = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var i, expected = 'Sunday Sun Su_Monday Mon Mo_Tuesday Tue Tu_Wednesday Wed We_Thursday Thu Th_Friday Fri Fr_Saturday Sat Sa'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'a few seconds', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'a minute', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'a minute', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutes', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutes', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'an hour', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'an hour', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 hours', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 hours', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 hours', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'a day', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'a day', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 days', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'a day', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 days', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 days', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'a month', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'a month', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'a month', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 months', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 months', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 months', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'a month', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 months', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'a year', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 years', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'a year', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 years', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'in a few seconds', 'prefix'); assert.equal(moment(0).from(30000), 'a few seconds ago', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'a few seconds ago', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'in a few seconds', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'in 5 days', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Today at 12:00 PM', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Today at 12:25 PM', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Today at 1:00 PM', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Tomorrow at 12:00 PM', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Today at 11:00 AM', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Yesterday at 12:00 PM', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday format', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1st', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1st', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2nd', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2nd', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3rd', 'Jan 15 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('en-gb'); test('parse', function (assert) { var tests = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Sunday, February 14th 2010, 3:25:50 pm'], ['ddd, hA', 'Sun, 3PM'], ['M Mo MM MMMM MMM', '2 2nd 02 February Feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14th 14'], ['d do dddd ddd dd', '0 0th Sunday Sun Su'], ['DDD DDDo DDDD', '45 45th 045'], ['w wo ww', '6 6th 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45th day of the year'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 February 2010'], ['LLL', '14 February 2010 15:25'], ['LLLL', 'Sunday, 14 February 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 Feb 2010'], ['lll', '14 Feb 2010 15:25'], ['llll', 'Sun, 14 Feb 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1st', '1st'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2nd', '2nd'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3rd', '3rd'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4th', '4th'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5th', '5th'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6th', '6th'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7th', '7th'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8th', '8th'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9th', '9th'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10th', '10th'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11th', '11th'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12th', '12th'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13th', '13th'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14th', '14th'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15th', '15th'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16th', '16th'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17th', '17th'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18th', '18th'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19th', '19th'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20th', '20th'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21st', '21st'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22nd', '22nd'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23rd', '23rd'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24th', '24th'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25th', '25th'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26th', '26th'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27th', '27th'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28th', '28th'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29th', '29th'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30th', '30th'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31st', '31st'); }); test('format month', function (assert) { var expected = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Sunday Sun Su_Monday Mon Mo_Tuesday Tue Tu_Wednesday Wed We_Thursday Thu Th_Friday Fri Fr_Saturday Sat Sa'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'a few seconds', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'a minute', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'a minute', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutes', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutes', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'an hour', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'an hour', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 hours', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 hours', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 hours', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'a day', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'a day', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 days', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'a day', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 days', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 days', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'a month', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'a month', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'a month', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 months', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 months', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 months', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'a month', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 months', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'a year', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 years', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'a year', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 years', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'in a few seconds', 'prefix'); assert.equal(moment(0).from(30000), 'a few seconds ago', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'a few seconds ago', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'in a few seconds', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'in 5 days', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Today at 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Today at 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Today at 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Tomorrow at 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Today at 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Yesterday at 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52nd', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1st', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1st', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2nd', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2nd', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('en-ie'); test('parse', function (assert) { var tests = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Sunday, February 14th 2010, 3:25:50 pm'], ['ddd, hA', 'Sun, 3PM'], ['M Mo MM MMMM MMM', '2 2nd 02 February Feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14th 14'], ['d do dddd ddd dd', '0 0th Sunday Sun Su'], ['DDD DDDo DDDD', '45 45th 045'], ['w wo ww', '6 6th 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45th day of the year'], ['LTS', '15:25:50'], ['L', '14-02-2010'], ['LL', '14 February 2010'], ['LLL', '14 February 2010 15:25'], ['LLLL', 'Sunday 14 February 2010 15:25'], ['l', '14-2-2010'], ['ll', '14 Feb 2010'], ['lll', '14 Feb 2010 15:25'], ['llll', 'Sun 14 Feb 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1st', '1st'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2nd', '2nd'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3rd', '3rd'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4th', '4th'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5th', '5th'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6th', '6th'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7th', '7th'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8th', '8th'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9th', '9th'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10th', '10th'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11th', '11th'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12th', '12th'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13th', '13th'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14th', '14th'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15th', '15th'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16th', '16th'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17th', '17th'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18th', '18th'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19th', '19th'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20th', '20th'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21st', '21st'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22nd', '22nd'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23rd', '23rd'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24th', '24th'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25th', '25th'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26th', '26th'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27th', '27th'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28th', '28th'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29th', '29th'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30th', '30th'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31st', '31st'); }); test('format month', function (assert) { var expected = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Sunday Sun Su_Monday Mon Mo_Tuesday Tue Tu_Wednesday Wed We_Thursday Thu Th_Friday Fri Fr_Saturday Sat Sa'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'a few seconds', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'a minute', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'a minute', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutes', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutes', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'an hour', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'an hour', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 hours', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 hours', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 hours', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'a day', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'a day', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 days', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'a day', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 days', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 days', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'a month', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'a month', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'a month', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 months', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 months', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 months', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'a month', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 months', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'a year', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 years', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'a year', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 years', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'in a few seconds', 'prefix'); assert.equal(moment(0).from(30000), 'a few seconds ago', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'a few seconds ago', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'in a few seconds', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'in 5 days', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Today at 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Today at 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Today at 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Tomorrow at 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Today at 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Yesterday at 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52nd', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1st', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1st', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2nd', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2nd', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('en-nz'); test('parse', function (assert) { var tests = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Sunday, February 14th 2010, 3:25:50 pm'], ['ddd, hA', 'Sun, 3PM'], ['M Mo MM MMMM MMM', '2 2nd 02 February Feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14th 14'], ['d do dddd ddd dd', '0 0th Sunday Sun Su'], ['DDD DDDo DDDD', '45 45th 045'], ['w wo ww', '6 6th 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45th day of the year'], ['LTS', '3:25:50 PM'], ['L', '14/02/2010'], ['LL', '14 February 2010'], ['LLL', '14 February 2010 3:25 PM'], ['LLLL', 'Sunday, 14 February 2010 3:25 PM'], ['l', '14/2/2010'], ['ll', '14 Feb 2010'], ['lll', '14 Feb 2010 3:25 PM'], ['llll', 'Sun, 14 Feb 2010 3:25 PM'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1st', '1st'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2nd', '2nd'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3rd', '3rd'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4th', '4th'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5th', '5th'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6th', '6th'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7th', '7th'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8th', '8th'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9th', '9th'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10th', '10th'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11th', '11th'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12th', '12th'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13th', '13th'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14th', '14th'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15th', '15th'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16th', '16th'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17th', '17th'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18th', '18th'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19th', '19th'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20th', '20th'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21st', '21st'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22nd', '22nd'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23rd', '23rd'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24th', '24th'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25th', '25th'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26th', '26th'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27th', '27th'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28th', '28th'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29th', '29th'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30th', '30th'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31st', '31st'); }); test('format month', function (assert) { var expected = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Sunday Sun Su_Monday Mon Mo_Tuesday Tue Tu_Wednesday Wed We_Thursday Thu Th_Friday Fri Fr_Saturday Sat Sa'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'a few seconds', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'a minute', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'a minute', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutes', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutes', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'an hour', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'an hour', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 hours', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 hours', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 hours', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'a day', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'a day', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 days', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'a day', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 days', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 days', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'a month', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'a month', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'a month', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 months', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 months', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 months', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'a month', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 months', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'a year', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 years', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'a year', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 years', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'in a few seconds', 'prefix'); assert.equal(moment(0).from(30000), 'a few seconds ago', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'a few seconds ago', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'in a few seconds', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'in 5 days', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Today at 12:00 PM', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Today at 12:25 PM', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Today at 1:00 PM', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Tomorrow at 12:00 PM', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Today at 11:00 AM', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Yesterday at 12:00 PM', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52nd', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1st', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1st', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2nd', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2nd', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('en'); test('parse', function (assert) { var i, tests = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split('_'); function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Sunday, February 14th 2010, 3:25:50 pm'], ['ddd, hA', 'Sun, 3PM'], ['M Mo MM MMMM MMM', '2 2nd 02 February Feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14th 14'], ['d do dddd ddd dd', '0 0th Sunday Sun Su'], ['DDD DDDo DDDD', '45 45th 045'], ['w wo ww', '8 8th 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45th day of the year'], ['LTS', '3:25:50 PM'], ['L', '02/14/2010'], ['LL', 'February 14, 2010'], ['LLL', 'February 14, 2010 3:25 PM'], ['LLLL', 'Sunday, February 14, 2010 3:25 PM'], ['l', '2/14/2010'], ['ll', 'Feb 14, 2010'], ['lll', 'Feb 14, 2010 3:25 PM'], ['llll', 'Sun, Feb 14, 2010 3:25 PM'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1st', '1st'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2nd', '2nd'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3rd', '3rd'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4th', '4th'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5th', '5th'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6th', '6th'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7th', '7th'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8th', '8th'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9th', '9th'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10th', '10th'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11th', '11th'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12th', '12th'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13th', '13th'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14th', '14th'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15th', '15th'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16th', '16th'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17th', '17th'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18th', '18th'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19th', '19th'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20th', '20th'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21st', '21st'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22nd', '22nd'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23rd', '23rd'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24th', '24th'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25th', '25th'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26th', '26th'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27th', '27th'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28th', '28th'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29th', '29th'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30th', '30th'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31st', '31st'); }); test('format month', function (assert) { var i, expected = 'January Jan_February Feb_March Mar_April Apr_May May_June Jun_July Jul_August Aug_September Sep_October Oct_November Nov_December Dec'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var i, expected = 'Sunday Sun Su_Monday Mon Mo_Tuesday Tue Tu_Wednesday Wed We_Thursday Thu Th_Friday Fri Fr_Saturday Sat Sa'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'a few seconds', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'a minute', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'a minute', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutes', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutes', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'an hour', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'an hour', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 hours', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 hours', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 hours', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'a day', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'a day', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 days', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'a day', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 days', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 days', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'a month', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'a month', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'a month', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 months', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 months', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 months', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'a month', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 months', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'a year', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 years', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'a year', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 years', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'in a few seconds', 'prefix'); assert.equal(moment(0).from(30000), 'a few seconds ago', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'a few seconds ago', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'in a few seconds', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'in 5 days', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Today at 12:00 PM', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Today at 12:25 PM', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Today at 1:00 PM', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Tomorrow at 12:00 PM', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Today at 11:00 AM', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Yesterday at 12:00 PM', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [at] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[Last] dddd [at] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday format', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1st', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1st', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2nd', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2nd', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3rd', 'Jan 15 2012 should be week 3'); }); test('weekdays strict parsing', function (assert) { var m = moment('2015-01-01T12', moment.ISO_8601, true), enLocale = moment.localeData('en'); for (var i = 0; i < 7; ++i) { assert.equal(moment(enLocale.weekdays(m.day(i), ''), 'dddd', true).isValid(), true, 'parse weekday ' + i); assert.equal(moment(enLocale.weekdaysShort(m.day(i), ''), 'ddd', true).isValid(), true, 'parse short weekday ' + i); assert.equal(moment(enLocale.weekdaysMin(m.day(i), ''), 'dd', true).isValid(), true, 'parse min weekday ' + i); // negative tests assert.equal(moment(enLocale.weekdaysMin(m.day(i), ''), 'ddd', true).isValid(), false, 'parse short weekday ' + i); assert.equal(moment(enLocale.weekdaysShort(m.day(i), ''), 'dd', true).isValid(), false, 'parse min weekday ' + i); } }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('eo'); test('parse', function (assert) { var tests = 'januaro jan_februaro feb_marto mar_aprilo apr_majo maj_junio jun_julio jul_agusto ag_septembro sep_oktobro okt_novembro nov_decembro dec'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Dimano, februaro 14a 2010, 3:25:50 p.t.m.'], ['ddd, hA', 'Dim, 3P.T.M.'], ['M Mo MM MMMM MMM', '2 2a 02 februaro feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14a 14'], ['d do dddd ddd dd', '0 0a Dimano Dim Di'], ['DDD DDDo DDDD', '45 45a 045'], ['w wo ww', '7 7a 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'p.t.m. P.T.M.'], ['[la] DDDo [tago] [de] [la] [jaro]', 'la 45a tago de la jaro'], ['LTS', '15:25:50'], ['L', '2010-02-14'], ['LL', '14-an de februaro, 2010'], ['LLL', '14-an de februaro, 2010 15:25'], ['LLLL', 'Dimano, la 14-an de februaro, 2010 15:25'], ['l', '2010-2-14'], ['ll', '14-an de feb, 2010'], ['lll', '14-an de feb, 2010 15:25'], ['llll', 'Dim, la 14-an de feb, 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1a', '1a'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2a', '2a'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3a', '3a'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4a', '4a'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5a', '5a'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6a', '6a'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7a', '7a'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8a', '8a'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9a', '9a'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10a', '10a'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11a', '11a'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12a', '12a'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13a', '13a'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14a', '14a'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15a', '15a'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16a', '16a'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17a', '17a'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18a', '18a'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19a', '19a'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20a', '20a'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21a', '21a'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22a', '22a'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23a', '23a'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24a', '24a'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25a', '25a'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26a', '26a'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27a', '27a'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28a', '28a'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29a', '29a'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30a', '30a'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31a', '31a'); }); test('format month', function (assert) { var expected = 'januaro jan_februaro feb_marto mar_aprilo apr_majo maj_junio jun_julio jul_agusto ag_septembro sep_oktobro okt_novembro nov_decembro dec'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Dimano Dim Di_Lundo Lun Lu_Mardo Mard Ma_Merkredo Merk Me_ado a a_Vendredo Ven Ve_Sabato Sab Sa'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'sekundoj', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'minuto', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'minuto', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutoj', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutoj', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'horo', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'horo', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 horoj', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 horoj', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 horoj', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'tago', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'tago', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 tagoj', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'tago', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 tagoj', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 tagoj', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'monato', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'monato', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'monato', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 monatoj', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 monatoj', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 monatoj', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'monato', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 monatoj', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'jaro', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 jaroj', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'jaro', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 jaroj', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'je sekundoj', 'je prefix'); assert.equal(moment(0).from(30000), 'anta sekundoj', 'anta prefix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'anta sekundoj', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'je sekundoj', 'je sekundoj'); assert.equal(moment().add({d: 5}).fromNow(), 'je 5 tagoj', 'je 5 tagoj'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Hodia je 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Hodia je 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Hodia je 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Morga je 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Hodia je 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Hiera je 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [je] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [je] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [je] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[pasinta] dddd [je] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[pasinta] dddd [je] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[pasinta] dddd [je] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1a', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1a', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2a', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2a', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3a', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('es'); test('parse', function (assert) { var tests = 'enero ene._febrero feb._marzo mar._abril abr._mayo may._junio jun._julio jul._agosto ago._septiembre sep._octubre oct._noviembre nov._diciembre dic.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'domingo, febrero 14 2010, 3:25:50 pm'], ['ddd, hA', 'dom., 3PM'], ['M Mo MM MMMM MMM', '2 2 02 febrero feb.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 domingo dom. do'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '6 6 06'], ['YYYY-MMM-DD', '2010-feb-14'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 de febrero de 2010'], ['LLL', '14 de febrero de 2010 15:25'], ['LLLL', 'domingo, 14 de febrero de 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 de feb. de 2010'], ['lll', '14 de feb. de 2010 15:25'], ['llll', 'dom., 14 de feb. de 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = 'enero ene._febrero feb._marzo mar._abril abr._mayo may._junio jun._julio jul._agosto ago._septiembre sep._octubre oct._noviembre nov._diciembre dic.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'domingo dom. do_lunes lun. lu_martes mar. ma_mircoles mi. mi_jueves jue. ju_viernes vie. vi_sbado sb. s'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'unos segundos', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'un minuto', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'un minuto', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutos', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutos', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'una hora', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'una hora', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 horas', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 horas', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 horas', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'un da', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'un da', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 das', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'un da', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 das', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 das', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'un mes', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'un mes', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'un mes', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 meses', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 meses', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 meses', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'un mes', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 meses', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'un ao', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 aos', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'un ao', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 aos', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'en unos segundos', 'prefix'); assert.equal(moment(0).from(30000), 'hace unos segundos', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'hace unos segundos', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'en unos segundos', 'en unos segundos'); assert.equal(moment().add({d: 5}).fromNow(), 'en 5 das', 'en 5 das'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'hoy a las 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'hoy a las 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'hoy a las 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'maana a las 12:00', 'tomorrow at the same time'); assert.equal(moment(a).add({d: 1, h : -1}).calendar(), 'maana a las 11:00', 'tomorrow minus 1 hour'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'hoy a las 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'ayer a las 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [a la' + ((m.hours() !== 1) ? 's' : '') + '] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [a la' + ((m.hours() !== 1) ? 's' : '') + '] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [a la' + ((m.hours() !== 1) ? 's' : '') + '] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[el] dddd [pasado a la' + ((m.hours() !== 1) ? 's' : '') + '] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[el] dddd [pasado a la' + ((m.hours() !== 1) ? 's' : '') + '] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[el] dddd [pasado a la' + ((m.hours() !== 1) ? 's' : '') + '] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('et'); test('parse', function (assert) { var tests = 'jaanuar jaan_veebruar veebr_mrts mrts_aprill apr_mai mai_juuni juuni_juuli juuli_august aug_september sept_oktoober okt_november nov_detsember dets'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' peaks olema kuu ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, H:mm:ss', 'phapev, 14. veebruar 2010, 15:25:50'], ['ddd, h', 'P, 3'], ['M Mo MM MMMM MMM', '2 2. 02 veebruar veebr'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. phapev P P'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[aasta] DDDo [pev]', 'aasta 45. pev'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14. veebruar 2010'], ['LLL', '14. veebruar 2010 15:25'], ['LLLL', 'phapev, 14. veebruar 2010 15:25'], ['l', '14.2.2010'], ['ll', '14. veebr 2010'], ['lll', '14. veebr 2010 15:25'], ['llll', 'P, 14. veebr 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'jaanuar jaan_veebruar veebr_mrts mrts_aprill apr_mai mai_juuni juuni_juuli juuli_august aug_september sept_oktoober okt_november nov_detsember dets'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'phapev P P_esmaspev E E_teisipev T T_kolmapev K K_neljapev N N_reede R R_laupev L L'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'paar sekundit', '44 seconds = paar sekundit'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'ks minut', '45 seconds = ks minut'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'ks minut', '89 seconds = ks minut'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutit', '90 seconds = 2 minutit'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutit', '44 minutes = 44 minutit'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'ks tund', '45 minutes = tund aega'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'ks tund', '89 minutes = ks tund'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 tundi', '90 minutes = 2 tundi'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 tundi', '5 hours = 5 tundi'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 tundi', '21 hours = 21 tundi'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'ks pev', '22 hours = ks pev'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'ks pev', '35 hours = ks pev'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 peva', '36 hours = 2 peva'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'ks pev', '1 day = ks pev'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 peva', '5 days = 5 peva'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 peva', '25 days = 25 peva'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'ks kuu', '26 days = ks kuu'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'ks kuu', '30 days = ks kuu'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'ks kuu', '43 days = ks kuu'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 kuud', '46 days = 2 kuud'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 kuud', '75 days = 2 kuud'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 kuud', '76 days = 3 kuud'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'ks kuu', '1 month = ks kuu'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 kuud', '5 months = 5 kuud'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'ks aasta', '345 days = ks aasta'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 aastat', '548 days = 2 aastat'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'ks aasta', '1 year = ks aasta'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 aastat', '5 years = 5 aastat'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'mne sekundi prast', 'prefix'); assert.equal(moment(0).from(30000), 'mni sekund tagasi', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'mni sekund tagasi', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'mne sekundi prast', 'in a few seconds'); assert.equal(moment().subtract({s: 30}).fromNow(), 'mni sekund tagasi', 'a few seconds ago'); assert.equal(moment().add({m: 1}).fromNow(), 'he minuti prast', 'in a minute'); assert.equal(moment().subtract({m: 1}).fromNow(), 'ks minut tagasi', 'a minute ago'); assert.equal(moment().add({m: 5}).fromNow(), '5 minuti prast', 'in 5 minutes'); assert.equal(moment().subtract({m: 5}).fromNow(), '5 minutit tagasi', '5 minutes ago'); assert.equal(moment().add({d: 1}).fromNow(), 'he peva prast', 'in one day'); assert.equal(moment().subtract({d: 1}).fromNow(), 'ks pev tagasi', 'one day ago'); assert.equal(moment().add({d: 5}).fromNow(), '5 peva prast', 'in 5 days'); assert.equal(moment().subtract({d: 5}).fromNow(), '5 peva tagasi', '5 days ago'); assert.equal(moment().add({M: 1}).fromNow(), 'kuu aja prast', 'in a month'); assert.equal(moment().subtract({M: 1}).fromNow(), 'kuu aega tagasi', 'a month ago'); assert.equal(moment().add({M: 5}).fromNow(), '5 kuu prast', 'in 5 months'); assert.equal(moment().subtract({M: 5}).fromNow(), '5 kuud tagasi', '5 months ago'); assert.equal(moment().add({y: 1}).fromNow(), 'he aasta prast', 'in a year'); assert.equal(moment().subtract({y: 1}).fromNow(), 'aasta tagasi', 'a year ago'); assert.equal(moment().add({y: 5}).fromNow(), '5 aasta prast', 'in 5 years'); assert.equal(moment().subtract({y: 5}).fromNow(), '5 aastat tagasi', '5 years ago'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Tna, 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Tna, 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Tna, 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Homme, 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Tna, 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Eile, 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('[Jrgmine] dddd LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[Jrgmine] dddd LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[Jrgmine] dddd LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[Eelmine] dddd LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[Eelmine] dddd LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[Eelmine] dddd LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 ndal tagasi'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), '1 ndala prast'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 ndalat tagasi'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), '2 ndala prast'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('eu'); test('parse', function (assert) { var tests = 'urtarrila urt._otsaila ots._martxoa mar._apirila api._maiatza mai._ekaina eka._uztaila uzt._abuztua abu._iraila ira._urria urr._azaroa aza._abendua abe.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'igandea, otsaila 14. 2010, 3:25:50 pm'], ['ddd, hA', 'ig., 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 otsaila ots.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. igandea ig. ig'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '7 7. 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['LTS', '15:25:50'], ['L', '2010-02-14'], ['LL', '2010ko otsailaren 14a'], ['LLL', '2010ko otsailaren 14a 15:25'], ['LLLL', 'igandea, 2010ko otsailaren 14a 15:25'], ['l', '2010-2-14'], ['ll', '2010ko ots. 14a'], ['lll', '2010ko ots. 14a 15:25'], ['llll', 'ig., 2010ko ots. 14a 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'urtarrila urt._otsaila ots._martxoa mar._apirila api._maiatza mai._ekaina eka._uztaila uzt._abuztua abu._iraila ira._urria urr._azaroa aza._abendua abe.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'igandea ig. ig_astelehena al. al_asteartea ar. ar_asteazkena az. az_osteguna og. og_ostirala ol. ol_larunbata lr. lr'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'segundo batzuk', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'minutu bat', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'minutu bat', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutu', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutu', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'ordu bat', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'ordu bat', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ordu', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ordu', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ordu', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'egun bat', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'egun bat', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 egun', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'egun bat', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 egun', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 egun', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'hilabete bat', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'hilabete bat', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'hilabete bat', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 hilabete', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 hilabete', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 hilabete', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'hilabete bat', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 hilabete', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'urte bat', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 urte', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'urte bat', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 urte', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'segundo batzuk barru', 'prefix'); assert.equal(moment(0).from(30000), 'duela segundo batzuk', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'duela segundo batzuk', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'segundo batzuk barru', 'in seconds'); assert.equal(moment().add({d: 5}).fromNow(), '5 egun barru', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'gaur 12:00etan', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'gaur 12:25etan', 'now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'gaur 13:00etan', 'now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'bihar 12:00etan', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'gaur 11:00etan', 'now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'atzo 12:00etan', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd LT[etan]'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd LT[etan]'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd LT[etan]'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[aurreko] dddd LT[etan]'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[aurreko] dddd LT[etan]'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[aurreko] dddd LT[etan]'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1.', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1.', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2.', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2.', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3.', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('fa'); test('parse', function (assert) { var tests = '___________'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1) + ' instead is month ' + moment(input, mmm).month()); } for (i = 0; i < 12; i++) { equalTest(tests[i], 'MMM', i); equalTest(tests[i], 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', '\u200c :: '], ['ddd, hA', '\u200c '], ['M Mo MM MMMM MMM', ' '], ['YYYY YY', ' '], ['D Do DD', ' '], ['d do dddd ddd dd', ' \u200c \u200c '], ['DDD DDDo DDDD', ' '], ['w wo ww', ' '], ['h hh', ' '], ['H HH', ' '], ['m mm', ' '], ['s ss', ' '], ['a A', ' '], ['DDDo [ ]', ' '], ['LTS', '::'], ['L', '//'], ['LL', ' '], ['LLL', ' :'], ['LLLL', '\u200c :'], ['l', '//'], ['ll', ' '], ['lll', ' :'], ['llll', '\u200c :'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '', '31'); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = '\u200c \u200c _ _\u200c \u200c _ _\u200c \u200c _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), ' ', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), ' ', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), ' ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), ' ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), ' ', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), ' ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), ' ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), ' ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), ' ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), ' ', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), ' ', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), ' ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), ' ', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), ' ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), ' ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), ' ', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), ' ', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), ' ', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), ' ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), ' ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), ' ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), ' ', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), ' ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), ' ', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), ' ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), ' ', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), ' ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' :', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' :', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' :', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' :', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' :', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' :', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [ ] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 31]).format('w ww wo'), ' ', 'Dec 31 2011 should be week 1'); assert.equal(moment([2012, 0, 6]).format('w ww wo'), ' ', 'Jan 6 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), ' ', 'Jan 7 2012 should be week 2'); assert.equal(moment([2012, 0, 13]).format('w ww wo'), ' ', 'Jan 13 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), ' ', 'Jan 14 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('fi'); test('parse', function (assert) { var tests = 'tammikuu tammi_helmikuu helmi_maaliskuu maalis_huhtikuu huhti_toukokuu touko_keskuu kes_heinkuu hein_elokuu elo_syyskuu syys_lokakuu loka_marraskuu marras_joulukuu joulu'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'sunnuntai, helmikuu 14. 2010, 3:25:50 pm'], ['ddd, hA', 'su, 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 helmikuu helmi'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. sunnuntai su su'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[vuoden] DDDo [piv]', 'vuoden 45. piv'], ['LTS', '15.25.50'], ['L', '14.02.2010'], ['LL', '14. helmikuuta 2010'], ['LLL', '14. helmikuuta 2010, klo 15.25'], ['LLLL', 'sunnuntai, 14. helmikuuta 2010, klo 15.25'], ['l', '14.2.2010'], ['ll', '14. helmi 2010'], ['lll', '14. helmi 2010, klo 15.25'], ['llll', 'su, 14. helmi 2010, klo 15.25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1st'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2nd'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3rd'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4th'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5th'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6th'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7th'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8th'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9th'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10th'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11th'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12th'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13th'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14th'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15th'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16th'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17th'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18th'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19th'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20th'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21st'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22nd'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23rd'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24th'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25th'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26th'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27th'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28th'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29th'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30th'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31st'); }); test('format month', function (assert) { var expected = 'tammikuu tammi_helmikuu helmi_maaliskuu maalis_huhtikuu huhti_toukokuu touko_keskuu kes_heinkuu hein_elokuu elo_syyskuu syys_lokakuu loka_marraskuu marras_joulukuu joulu'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'sunnuntai su su_maanantai ma ma_tiistai ti ti_keskiviikko ke ke_torstai to to_perjantai pe pe_lauantai la la'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'muutama sekunti', '44 seconds = few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'minuutti', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'minuutti', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), 'kaksi minuuttia', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minuuttia', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'tunti', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'tunti', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), 'kaksi tuntia', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), 'viisi tuntia', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 tuntia', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'piv', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'piv', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), 'kaksi piv', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'piv', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), 'viisi piv', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 piv', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'kuukausi', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'kuukausi', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'kuukausi', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), 'kaksi kuukautta', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), 'kaksi kuukautta', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), 'kolme kuukautta', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'kuukausi', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), 'viisi kuukautta', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'vuosi', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), 'kaksi vuotta', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'vuosi', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), 'viisi vuotta', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'muutaman sekunnin pst', 'prefix'); assert.equal(moment(0).from(30000), 'muutama sekunti sitten', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'muutama sekunti sitten', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'muutaman sekunnin pst', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'viiden pivn pst', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'tnn klo 12.00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'tnn klo 12.25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'tnn klo 13.00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'huomenna klo 12.00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'tnn klo 11.00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'eilen klo 12.00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [klo] LT'), 'today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [klo] LT'), 'today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [klo] LT'), 'today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[viime] dddd[na] [klo] LT'), 'today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[viime] dddd[na] [klo] LT'), 'today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[viime] dddd[na] [klo] LT'), 'today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), 'yksi viikko sitten'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'yhden viikon pst'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), 'kaksi viikkoa sitten'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'kaden viikon pst'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('fo'); test('parse', function (assert) { var tests = 'januar jan_februar feb_mars mar_aprl apr_mai mai_juni jun_juli jul_august aug_september sep_oktober okt_november nov_desember des'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd [tann] Do MMMM YYYY, h:mm:ss a', 'sunnudagur tann 14. februar 2010, 3:25:50 pm'], ['ddd hA', 'sun 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 februar feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. sunnudagur sun su'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[tann] DDDo [dagin rinum]', 'tann 45. dagin rinum'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 februar 2010'], ['LLL', '14 februar 2010 15:25'], ['LLLL', 'sunnudagur 14. februar, 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 feb 2010'], ['lll', '14 feb 2010 15:25'], ['llll', 'sun 14. feb, 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'januar jan_februar feb_mars mar_aprl apr_mai mai_juni jun_juli jul_august aug_september sep_oktober okt_november nov_desember des'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'sunnudagur sun su_mnadagur mn m_tsdagur ts t_mikudagur mik mi_hsdagur hs h_frggjadagur fr fr_leygardagur ley le'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'f sekund', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'ein minutt', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'ein minutt', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minuttir', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minuttir', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'ein tmi', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'ein tmi', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 tmar', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 tmar', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 tmar', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'ein dagur', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'ein dagur', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dagar', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'ein dagur', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dagar', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dagar', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'ein mnai', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'ein mnai', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'ein mnai', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mnair', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mnair', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mnair', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'ein mnai', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mnair', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'eitt r', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 r', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'eitt r', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 r', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'um f sekund', 'prefix'); assert.equal(moment(0).from(30000), 'f sekund sani', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'f sekund sani', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'um f sekund', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'um 5 dagar', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' dag kl. 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' dag kl. 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' dag kl. 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' morgin kl. 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' dag kl. 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' gjr kl. 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [kl.] LT'), 'today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [kl.] LT'), 'today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [kl.] LT'), 'today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[sstu] dddd [kl] LT'), 'today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[sstu] dddd [kl] LT'), 'today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[sstu] dddd [kl] LT'), 'today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), 'yksi viikko sitten'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'yhden viikon pst'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), 'kaksi viikkoa sitten'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'kaden viikon pst'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('fr-ca'); test('parse', function (assert) { var i, tests = 'janvier janv._fvrier fvr._mars mars_avril avr._mai mai_juin juin_juillet juil._aot aot_septembre sept._octobre oct._novembre nov._dcembre dc.'.split('_'); function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'dimanche, fvrier 14e 2010, 3:25:50 pm'], ['ddd, hA', 'dim., 3PM'], ['M Mo MM MMMM MMM', '2 2e 02 fvrier fvr.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14e 14'], ['d do dddd ddd dd', '0 0e dimanche dim. Di'], ['DDD DDDo DDDD', '45 45e 045'], ['w wo ww', '8 8e 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45e day of the year'], ['LTS', '15:25:50'], ['L', '2010-02-14'], ['LL', '14 fvrier 2010'], ['LLL', '14 fvrier 2010 15:25'], ['LLLL', 'dimanche 14 fvrier 2010 15:25'], ['l', '2010-2-14'], ['ll', '14 fvr. 2010'], ['lll', '14 fvr. 2010 15:25'], ['llll', 'dim. 14 fvr. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1er', '1er'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2e', '2e'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3e', '3e'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4e', '4e'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5e', '5e'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6e', '6e'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7e', '7e'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8e', '8e'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9e', '9e'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10e', '10e'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11e', '11e'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12e', '12e'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13e', '13e'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14e', '14e'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15e', '15e'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16e', '16e'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17e', '17e'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18e', '18e'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19e', '19e'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20e', '20e'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21e', '21e'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22e', '22e'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23e', '23e'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24e', '24e'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25e', '25e'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26e', '26e'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27e', '27e'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28e', '28e'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29e', '29e'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30e', '30e'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31e', '31e'); }); test('format month', function (assert) { var i, expected = 'janvier janv._fvrier fvr._mars mars_avril avr._mai mai_juin juin_juillet juil._aot aot_septembre sept._octobre oct._novembre nov._dcembre dc.'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var i, expected = 'dimanche dim. Di_lundi lun. Lu_mardi mar. Ma_mercredi mer. Me_jeudi jeu. Je_vendredi ven. Ve_samedi sam. Sa'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'quelques secondes', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'une minute', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'une minute', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutes', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutes', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'une heure', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'une heure', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 heures', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 heures', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 heures', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'un jour', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'un jour', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 jours', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'un jour', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 jours', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 jours', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'un mois', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'un mois', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'un mois', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mois', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mois', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mois', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'un mois', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mois', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'un an', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ans', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'un an', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ans', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'dans quelques secondes', 'prefix'); assert.equal(moment(0).from(30000), 'il y a quelques secondes', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'dans quelques secondes', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'dans 5 jours', 'in 5 days'); }); test('same day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Aujourd\'hui 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Aujourd\'hui 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Aujourd\'hui 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Demain 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Aujourd\'hui 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Hier 12:00', 'yesterday at the same time'); }); test('same next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days end of day'); } }); test('same last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [dernier ] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [dernier ] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [dernier ] LT'), 'Today - ' + i + ' days end of day'); } }); test('same all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday format', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1er', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1er', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2e', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2e', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3e', 'Jan 15 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('fr-ch'); test('parse', function (assert) { var i, tests = 'janvier janv._fvrier fvr._mars mars_avril avr._mai mai_juin juin_juillet juil._aot aot_septembre sept._octobre oct._novembre nov._dcembre dc.'.split('_'); function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'dimanche, fvrier 14e 2010, 3:25:50 pm'], ['ddd, hA', 'dim., 3PM'], ['M Mo MM MMMM MMM', '2 2e 02 fvrier fvr.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14e 14'], ['d do dddd ddd dd', '0 0e dimanche dim. Di'], ['DDD DDDo DDDD', '45 45e 045'], ['w wo ww', '6 6e 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45e day of the year'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14 fvrier 2010'], ['LLL', '14 fvrier 2010 15:25'], ['LLLL', 'dimanche 14 fvrier 2010 15:25'], ['l', '14.2.2010'], ['ll', '14 fvr. 2010'], ['lll', '14 fvr. 2010 15:25'], ['llll', 'dim. 14 fvr. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1er', '1er'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2e', '2e'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3e', '3e'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4e', '4e'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5e', '5e'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6e', '6e'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7e', '7e'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8e', '8e'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9e', '9e'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10e', '10e'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11e', '11e'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12e', '12e'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13e', '13e'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14e', '14e'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15e', '15e'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16e', '16e'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17e', '17e'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18e', '18e'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19e', '19e'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20e', '20e'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21e', '21e'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22e', '22e'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23e', '23e'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24e', '24e'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25e', '25e'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26e', '26e'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27e', '27e'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28e', '28e'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29e', '29e'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30e', '30e'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31e', '31e'); }); test('format month', function (assert) { var i, expected = 'janvier janv._fvrier fvr._mars mars_avril avr._mai mai_juin juin_juillet juil._aot aot_septembre sept._octobre oct._novembre nov._dcembre dc.'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var i, expected = 'dimanche dim. Di_lundi lun. Lu_mardi mar. Ma_mercredi mer. Me_jeudi jeu. Je_vendredi ven. Ve_samedi sam. Sa'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'quelques secondes', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'une minute', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'une minute', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutes', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutes', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'une heure', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'une heure', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 heures', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 heures', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 heures', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'un jour', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'un jour', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 jours', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'un jour', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 jours', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 jours', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'un mois', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'un mois', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'un mois', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mois', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mois', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mois', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'un mois', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mois', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'un an', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ans', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'un an', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ans', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'dans quelques secondes', 'prefix'); assert.equal(moment(0).from(30000), 'il y a quelques secondes', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'dans quelques secondes', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'dans 5 jours', 'in 5 days'); }); test('same day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Aujourd\'hui 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Aujourd\'hui 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Aujourd\'hui 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Demain 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Aujourd\'hui 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Hier 12:00', 'yesterday at the same time'); }); test('same next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days end of day'); } }); test('same last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [dernier ] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [dernier ] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [dernier ] LT'), 'Today - ' + i + ' days end of day'); } }); test('same all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52e', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1er', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1er', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2e', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2e', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('fr'); test('parse', function (assert) { var tests = 'janvier janv._fvrier fvr._mars mars_avril avr._mai mai_juin juin_juillet juil._aot aot_septembre sept._octobre oct._novembre nov._dcembre dc.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'dimanche, fvrier 14 2010, 3:25:50 pm'], ['ddd, hA', 'dim., 3PM'], ['M Mo MM MMMM MMM', '2 2 02 fvrier fvr.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 dimanche dim. Di'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '6 6 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 fvrier 2010'], ['LLL', '14 fvrier 2010 15:25'], ['LLLL', 'dimanche 14 fvrier 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 fvr. 2010'], ['lll', '14 fvr. 2010 15:25'], ['llll', 'dim. 14 fvr. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1er', '1er'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = 'janvier janv._fvrier fvr._mars mars_avril avr._mai mai_juin juin_juillet juil._aot aot_septembre sept._octobre oct._novembre nov._dcembre dc.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'dimanche dim. Di_lundi lun. Lu_mardi mar. Ma_mercredi mer. Me_jeudi jeu. Je_vendredi ven. Ve_samedi sam. Sa'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'quelques secondes', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'une minute', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'une minute', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutes', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutes', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'une heure', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'une heure', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 heures', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 heures', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 heures', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'un jour', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'un jour', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 jours', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'un jour', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 jours', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 jours', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'un mois', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'un mois', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'un mois', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mois', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mois', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mois', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'un mois', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mois', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'un an', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ans', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'un an', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ans', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'dans quelques secondes', 'prefix'); assert.equal(moment(0).from(30000), 'il y a quelques secondes', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'dans quelques secondes', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'dans 5 jours', 'in 5 days'); }); test('same day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Aujourd\'hui 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Aujourd\'hui 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Aujourd\'hui 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Demain 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Aujourd\'hui 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Hier 12:00', 'yesterday at the same time'); }); test('same next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days end of day'); } }); test('same last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [dernier ] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [dernier ] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [dernier ] LT'), 'Today - ' + i + ' days end of day'); } }); test('same all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1er', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1er', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('fy'); test('parse', function (assert) { var tests = 'jannewaris jan._febrewaris feb._maart mrt._april apr._maaie mai._juny jun._july jul._augustus aug._septimber sep._oktober okt._novimber nov._desimber des.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, HH:mm:ss', 'snein, febrewaris 14de 2010, 15:25:50'], ['ddd, HH', 'si., 15'], ['M Mo MM MMMM MMM', '2 2de 02 febrewaris feb.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14de 14'], ['d do dddd ddd dd', '0 0de snein si. Si'], ['DDD DDDo DDDD', '45 45ste 045'], ['w wo ww', '6 6de 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45ste day of the year'], ['LTS', '15:25:50'], ['L', '14-02-2010'], ['LL', '14 febrewaris 2010'], ['LLL', '14 febrewaris 2010 15:25'], ['LLLL', 'snein 14 febrewaris 2010 15:25'], ['l', '14-2-2010'], ['ll', '14 feb. 2010'], ['lll', '14 feb. 2010 15:25'], ['llll', 'si. 14 feb. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1ste', '1ste'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2de', '2de'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3de', '3de'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4de', '4de'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5de', '5de'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6de', '6de'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7de', '7de'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8ste', '8ste'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9de', '9de'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10de', '10de'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11de', '11de'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12de', '12de'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13de', '13de'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14de', '14de'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15de', '15de'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16de', '16de'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17de', '17de'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18de', '18de'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19de', '19de'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20ste', '20ste'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21ste', '21ste'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22ste', '22ste'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23ste', '23ste'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24ste', '24ste'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25ste', '25ste'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26ste', '26ste'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27ste', '27ste'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28ste', '28ste'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29ste', '29ste'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30ste', '30ste'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31ste', '31ste'); }); test('format month', function (assert) { var expected = 'jannewaris jan._febrewaris feb._maart mrt._april apr._maaie mai_juny jun._july jul._augustus aug._septimber sep._oktober okt._novimber nov._desimber des.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'snein si. Si_moandei mo. Mo_tiisdei ti. Ti_woansdei wo. Wo_tongersdei to. To_freed fr. Fr_sneon so. So'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'in pear sekonden', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'ien mint', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'ien mint', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minuten', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minuten', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'ien oere', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'ien oere', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 oeren', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 oeren', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 oeren', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'ien dei', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'ien dei', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dagen', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'ien dei', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dagen', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dagen', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'ien moanne', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'ien moanne', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'ien moanne', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 moannen', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 moannen', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 moannen', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'ien moanne', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 moannen', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'ien jier', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 jierren', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'ien jier', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 jierren', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'oer in pear sekonden', 'prefix'); assert.equal(moment(0).from(30000), 'in pear sekonden lyn', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'in pear sekonden lyn', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'oer in pear sekonden', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'oer 5 dagen', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'hjoed om 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'hjoed om 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'hjoed om 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'moarn om 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'hjoed om 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'juster om 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [om] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [om] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [om] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[frne] dddd [om] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[frne] dddd [om] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[frne] dddd [om] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('month abbreviation', function (assert) { assert.equal(moment([2012, 5, 23]).format('D-MMM-YYYY'), '23-jun-2012', 'format month abbreviation surrounded by dashes should not include a dot'); assert.equal(moment([2012, 5, 23]).format('D MMM YYYY'), '23 jun. 2012', 'format month abbreviation not surrounded by dashes should include a dot'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52ste', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1ste', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1ste', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2de', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2de', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('gd'); var months = [ 'Am Faoilleach,Faoi', 'An Gearran,Gear', 'Am Mrt,Mrt', 'An Giblean,Gibl', 'An Citean,Cit', 'An t-gmhios,gmh', 'An t-Iuchar,Iuch', 'An Lnastal,Ln', 'An t-Sultain,Sult', 'An Dmhair,Dmh', 'An t-Samhain,Samh', 'An Dbhlachd,Dbh' ]; test('parse', function (assert) { function equalTest(monthName, monthFormat, monthNum) { assert.equal(moment(monthName, monthFormat).month(), monthNum, monthName + ' should be month ' + (monthNum + 1)); } for (var i = 0; i < 12; i++) { var testMonth = months[i].split(','); equalTest(testMonth[0], 'MMM', i); equalTest(testMonth[1], 'MMM', i); equalTest(testMonth[0], 'MMMM', i); equalTest(testMonth[1], 'MMMM', i); equalTest(testMonth[0].toLocaleLowerCase(), 'MMMM', i); equalTest(testMonth[1].toLocaleLowerCase(), 'MMMM', i); equalTest(testMonth[0].toLocaleUpperCase(), 'MMMM', i); equalTest(testMonth[1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Didmhnaich, An Gearran 14mh 2010, 3:25:50 pm'], ['ddd, hA', 'Did, 3PM'], ['M Mo MM MMMM MMM', '2 2na 02 An Gearran Gear'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14mh 14'], ['d do dddd ddd dd', '0 0mh Didmhnaich Did D'], ['DDD DDDo DDDD', '45 45mh 045'], ['w wo ww', '6 6mh 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[an] DDDo [latha den bhliadhna]', 'an 45mh latha den bhliadhna'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 An Gearran 2010'], ['LLL', '14 An Gearran 2010 15:25'], ['LLLL', 'Didmhnaich, 14 An Gearran 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 Gear 2010'], ['lll', '14 Gear 2010 15:25'], ['llll', 'Did, 14 Gear 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1d', '1d'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2na', '2na'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3mh', '3mh'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4mh', '4mh'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5mh', '5mh'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6mh', '6mh'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7mh', '7mh'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8mh', '8mh'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9mh', '9mh'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10mh', '10mh'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11mh', '11mh'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12na', '12na'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13mh', '13mh'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14mh', '14mh'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15mh', '15mh'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16mh', '16mh'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17mh', '17mh'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18mh', '18mh'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19mh', '19mh'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20mh', '20mh'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21mh', '21mh'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22na', '22na'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23mh', '23mh'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24mh', '24mh'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25mh', '25mh'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26mh', '26mh'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27mh', '27mh'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28mh', '28mh'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29mh', '29mh'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30mh', '30mh'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31mh', '31mh'); }); test('format month', function (assert) { var expected = months; for (var i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM,MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ['Didmhnaich Did D', 'Diluain Dil Lu', 'Dimirt Dim M', 'Diciadain Dic Ci', 'Diardaoin Dia Ar', 'Dihaoine Dih Ha', 'Disathairne Dis Sa']; for (var i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'beagan diogan', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'mionaid', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'mionaid', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 mionaidean', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 mionaidean', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'uair', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'uair', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 uairean', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 uairean', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 uairean', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'latha', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'latha', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 latha', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'latha', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 latha', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 latha', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'mos', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'mos', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'mos', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mosan', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mosan', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mosan', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'mos', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mosan', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'bliadhna', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 bliadhna', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'bliadhna', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 bliadhna', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'ann an beagan diogan', 'prefix'); assert.equal(moment(0).from(30000), 'bho chionn beagan diogan', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'bho chionn beagan diogan', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'ann an beagan diogan', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'ann an 5 latha', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'An-diugh aig 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'An-diugh aig 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'An-diugh aig 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'A-mireach aig 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'An-diugh aig 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'An-d aig 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [aig] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [aig] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [aig] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [seo chaidh] [aig] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [seo chaidh] [aig] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [seo chaidh] [aig] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52na', 'Faoi 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1d', 'Faoi 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1d', 'Faoi 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2na', 'Faoi 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2na', 'Faoi 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('gl'); test('parse', function (assert) { var tests = 'Xaneiro Xan._Febreiro Feb._Marzo Mar._Abril Abr._Maio Mai._Xuo Xu._Xullo Xul._Agosto Ago._Setembro Set._Outubro Out._Novembro Nov._Decembro Dec.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Domingo, Febreiro 14 2010, 3:25:50 pm'], ['ddd, hA', 'Dom., 3PM'], ['M Mo MM MMMM MMM', '2 2 02 Febreiro Feb.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 Domingo Dom. Do'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '7 7 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 Febreiro 2010'], ['LLL', '14 Febreiro 2010 15:25'], ['LLLL', 'Domingo 14 Febreiro 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 Feb. 2010'], ['lll', '14 Feb. 2010 15:25'], ['llll', 'Dom. 14 Feb. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = 'Xaneiro Xan._Febreiro Feb._Marzo Mar._Abril Abr._Maio Mai._Xuo Xu._Xullo Xul._Agosto Ago._Setembro Set._Outubro Out._Novembro Nov._Decembro Dec.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Domingo Dom. Do_Luns Lun. Lu_Martes Mar. Ma_Mrcores Mr. M_Xoves Xov. Xo_Venres Ven. Ve_Sbado Sb. S'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'uns segundos', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'un minuto', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'un minuto', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutos', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutos', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'unha hora', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'unha hora', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 horas', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 horas', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 horas', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'un da', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'un da', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 das', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'un da', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 das', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 das', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'un mes', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'un mes', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'un mes', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 meses', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 meses', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 meses', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'un mes', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 meses', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'un ano', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 anos', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'un ano', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 anos', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'nuns segundos', 'prefix'); assert.equal(moment(0).from(30000), 'hai uns segundos', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'hai uns segundos', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'nuns segundos', 'en unos segundos'); assert.equal(moment().add({d: 5}).fromNow(), 'en 5 das', 'en 5 das'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'hoxe s 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'hoxe s 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'hoxe s 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'ma s 12:00', 'tomorrow at the same time'); assert.equal(moment(a).add({d: 1, h : -1}).calendar(), 'ma s 11:00', 'tomorrow minus 1 hour'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'hoxe s 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'onte 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [' + ((m.hours() !== 1) ? 's' : 'a') + '] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [' + ((m.hours() !== 1) ? 's' : 'a') + '] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [' + ((m.hours() !== 1) ? 's' : 'a') + '] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[o] dddd [pasado ' + ((m.hours() !== 1) ? 's' : 'a') + '] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[o] dddd [pasado ' + ((m.hours() !== 1) ? 's' : 'a') + '] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[o] dddd [pasado ' + ((m.hours() !== 1) ? 's' : 'a') + '] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('regression tests', function (assert) { var lastWeek = moment().subtract({d: 4}).hours(1); assert.equal(lastWeek.calendar(), lastWeek.format('[o] dddd [pasado a] LT'), '1 o\'clock bug'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('he'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', ', 14 2010, 3:25:50 "'], ['ddd, h A', ', 3 '], ['M Mo MM MMMM MMM', '2 2 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '8 8 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', '" '], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 2010'], ['LLL', '14 2010 15:25'], ['LLLL', ', 14 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 2010'], ['lll', '14 2010 15:25'], ['llll', ', 14 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' | | | | | | '.split('|'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 3699}), true), '10 ', '345 days = 10 years'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 7340}), true), '20 ', '548 days = 20 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' 5 ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[] dddd [ ] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd [ ] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd [ ] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday format', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('hi'); test('parse', function (assert) { var tests = ' ._ ._ _ ._ _ _ ._ ._ ._ ._ ._ .'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, a h:mm:ss ', ', , :: '], ['ddd, a h ', ', '], ['M Mo MM MMMM MMM', ' .'], ['YYYY YY', ' '], ['D Do DD', ' '], ['d do dddd ddd dd', ' '], ['DDD DDDo DDDD', ' '], ['w wo ww', ' '], ['h hh', ' '], ['H HH', ' '], ['m mm', ' '], ['s ss', ' '], ['a A', ' '], ['LTS', ' :: '], ['L', '//'], ['LL', ' '], ['LLL', ' , : '], ['LLLL', ', , : '], ['l', '//'], ['ll', ' . '], ['lll', ' . , : '], ['llll', ', . , : '] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 2]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 3]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 4]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 5]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 6]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 7]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 8]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 9]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 10]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 11]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 12]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 13]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 14]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 15]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 16]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 17]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 18]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 19]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 20]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 21]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 22]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 23]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 24]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 25]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 26]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 27]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 28]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 29]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 30]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 31]).format('DDDo'), '', ''); }); test('format month', function (assert) { var expected = ' ._ ._ _ ._ _ _ ._ ._ ._ ._ ._ .'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), ' ', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), ' ', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), ' ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), ' ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), ' ', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), ' ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), ' ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), ' ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), ' ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), ' ', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), ' ', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), ' ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), ' ', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), ' ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), ' ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), ' ', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), ' ', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), ' ', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), ' ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), ' ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), ' ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), ' ', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), ' ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), ' ', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), ' ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), ' ', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), ' ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', ' '); assert.equal(moment().add({d: 5}).fromNow(), ' ', ' '); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' : ', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' : ', 'Now plus 25 min'); assert.equal(moment(a).add({h: 3}).calendar(), ' : ', 'Now plus 3 hours'); assert.equal(moment(a).add({d: 1}).calendar(), ' : ', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' : ', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' : ', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('meridiem', function (assert) { assert.equal(moment([2011, 2, 23, 2, 30]).format('a'), '', 'before dawn'); assert.equal(moment([2011, 2, 23, 9, 30]).format('a'), '', 'morning'); assert.equal(moment([2011, 2, 23, 14, 30]).format('a'), '', 'during day'); assert.equal(moment([2011, 2, 23, 17, 30]).format('a'), '', 'evening'); assert.equal(moment([2011, 2, 23, 19, 30]).format('a'), '', 'late evening'); assert.equal(moment([2011, 2, 23, 21, 20]).format('a'), '', 'night'); assert.equal(moment([2011, 2, 23, 2, 30]).format('A'), '', 'before dawn'); assert.equal(moment([2011, 2, 23, 9, 30]).format('A'), '', 'morning'); assert.equal(moment([2011, 2, 23, 14, 30]).format('A'), '', ' during day'); assert.equal(moment([2011, 2, 23, 17, 30]).format('A'), '', 'evening'); assert.equal(moment([2011, 2, 23, 19, 30]).format('A'), '', 'late evening'); assert.equal(moment([2011, 2, 23, 21, 20]).format('A'), '', 'night'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), ' ', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), ' ', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), ' ', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), ' ', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), ' ', 'Jan 15 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('hr'); test('parse', function (assert) { var tests = 'sijeanj sij._veljaa velj._oujak ou._travanj tra._svibanj svi._lipanj lip._srpanj srp._kolovoz kol._rujan ruj._listopad lis._studeni stu._prosinac pro.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, h:mm:ss a', 'nedjelja, 14. veljae 2010, 3:25:50 pm'], ['ddd, hA', 'ned., 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 veljaa velj.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. nedjelja ned. ne'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '7 7. 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['LTS', '15:25:50'], ['L', '14. 02. 2010'], ['LL', '14. veljaa 2010'], ['LLL', '14. veljaa 2010 15:25'], ['LLLL', 'nedjelja, 14. veljaa 2010 15:25'], ['l', '14. 2. 2010'], ['ll', '14. velj. 2010'], ['lll', '14. velj. 2010 15:25'], ['llll', 'ned., 14. velj. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'sijeanj sij._veljaa velj._oujak ou._travanj tra._svibanj svi._lipanj lip._srpanj srp._kolovoz kol._rujan ruj._listopad lis._studeni stu._prosinac pro.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'nedjelja ned. ne_ponedjeljak pon. po_utorak uto. ut_srijeda sri. sr_etvrtak et. e_petak pet. pe_subota sub. su'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'par sekundi', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'jedna minuta', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'jedna minuta', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minute', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minuta', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'jedan sat', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'jedan sat', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 sata', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 sati', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 sati', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'dan', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'dan', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dana', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'dan', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dana', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dana', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'mjesec', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'mjesec', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'mjesec', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mjeseca', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mjeseca', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mjeseca', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'mjesec', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mjeseci', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'godinu', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 godine', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'godinu', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 godina', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'za par sekundi', 'prefix'); assert.equal(moment(0).from(30000), 'prije par sekundi', 'prefix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'prije par sekundi', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'za par sekundi', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'za 5 dana', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'danas u 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'danas u 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'danas u 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'sutra u 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'danas u 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'juer u 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; function makeFormat(d) { switch (d.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'; } } for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; function makeFormat(d) { switch (d.day()) { case 0: case 3: return '[prolu] dddd [u] LT'; case 6: return '[prole] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[proli] dddd [u] LT'; } } for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1.', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1.', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2.', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2.', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3.', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('hu'); test('parse', function (assert) { var tests = 'janur jan_februr feb_mrcius mrc_prilis pr_mjus mj_jnius jn_jlius jl_augusztus aug_szeptember szept_oktber okt_november nov_december dec'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, HH:mm:ss', 'vasrnap, februr 14. 2010, 15:25:50'], ['ddd, HH', 'vas, 15'], ['M Mo MM MMMM MMM', '2 2. 02 februr feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. vasrnap vas v'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '7 7. 07'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['[az v] DDDo [napja]', 'az v 45. napja'], ['LTS', '15:25:50'], ['L', '2010.02.14.'], ['LL', '2010. februr 14.'], ['LLL', '2010. februr 14. 15:25'], ['LLLL', '2010. februr 14., vasrnap 15:25'], ['l', '2010.2.14.'], ['ll', '2010. feb 14.'], ['lll', '2010. feb 14. 15:25'], ['llll', '2010. feb 14., vas 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('meridiem', function (assert) { assert.equal(moment([2011, 2, 23, 0, 0]).format('a'), 'de', 'am'); assert.equal(moment([2011, 2, 23, 11, 59]).format('a'), 'de', 'am'); assert.equal(moment([2011, 2, 23, 12, 0]).format('a'), 'du', 'pm'); assert.equal(moment([2011, 2, 23, 23, 59]).format('a'), 'du', 'pm'); assert.equal(moment([2011, 2, 23, 0, 0]).format('A'), 'DE', 'AM'); assert.equal(moment([2011, 2, 23, 11, 59]).format('A'), 'DE', 'AM'); assert.equal(moment([2011, 2, 23, 12, 0]).format('A'), 'DU', 'PM'); assert.equal(moment([2011, 2, 23, 23, 59]).format('A'), 'DU', 'PM'); }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'janur jan_februr feb_mrcius mrc_prilis pr_mjus mj_jnius jn_jlius jl_augusztus aug_szeptember szept_oktber okt_november nov_december dec'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'vasrnap vas_htf ht_kedd kedd_szerda sze_cstrtk cst_pntek pn_szombat szo'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'nhny msodperc', '44 msodperc = nhny msodperc'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'egy perc', '45 msodperc = egy perc'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'egy perc', '89 msodperc = egy perc'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 perc', '90 msodperc = 2 perc'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 perc', '44 perc = 44 perc'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'egy ra', '45 perc = egy ra'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'egy ra', '89 perc = egy ra'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ra', '90 perc = 2 ra'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ra', '5 ra = 5 ra'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ra', '21 ra = 21 ra'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'egy nap', '22 ra = egy nap'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'egy nap', '35 ra = egy nap'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 nap', '36 ra = 2 nap'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'egy nap', '1 nap = egy nap'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 nap', '5 nap = 5 nap'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 nap', '25 nap = 25 nap'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'egy hnap', '26 nap = egy hnap'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'egy hnap', '30 nap = egy hnap'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'egy hnap', '45 nap = egy hnap'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 hnap', '46 nap = 2 hnap'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 hnap', '75 nap = 2 hnap'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 hnap', '76 nap = 3 hnap'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'egy hnap', '1 hnap = egy hnap'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 hnap', '5 hnap = 5 hnap'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'egy v', '345 nap = egy v'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 v', '548 nap = 2 v'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'egy v', '1 v = egy v'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 v', '5 v = 5 v'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'nhny msodperc mlva', 'prefix'); assert.equal(moment(0).from(30000), 'nhny msodperce', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'nhny msodperce', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'nhny msodperc mlva', 'nhny msodperc mlva'); assert.equal(moment().add({d: 5}).fromNow(), '5 nap mlva', '5 nap mlva'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'ma 12:00-kor', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'ma 12:25-kor', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'ma 13:00-kor', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'holnap 12:00-kor', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'ma 11:00-kor', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'tegnap 12:00-kor', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m, days = 'vasrnap_htfn_kedden_szerdn_cstrtkn_pnteken_szombaton'.split('_'); for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('[' + days[m.day()] + '] LT[-kor]'), 'today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[' + days[m.day()] + '] LT[-kor]'), 'today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[' + days[m.day()] + '] LT[-kor]'), 'today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m, days = 'vasrnap_htfn_kedden_szerdn_cstrtkn_pnteken_szombaton'.split('_'); for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[mlt ' + days[m.day()] + '] LT[-kor]'), 'today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[mlt ' + days[m.day()] + '] LT[-kor]'), 'today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[mlt ' + days[m.day()] + '] LT[-kor]'), 'today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), 'egy hte'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'egy ht mlva'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 hete'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), '2 ht mlva'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1.', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1.', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2.', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2.', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3.', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('hy-am'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('parse exceptional case', function (assert) { assert.equal(moment('11 1989', ['DD MMMM YYYY']).format('DD-MM-YYYY'), '11-05-1989'); }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, HH:mm:ss', ', 14 2010, 15:25:50'], ['ddd, h A', ', 3 '], ['M Mo MM MMMM MMM', '2 2 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45- 045'], ['w wo ww', '7 7- 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', ' '], ['[] DDDo []', ' 45- '], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14 2010 .'], ['LLL', '14 2010 ., 15:25'], ['LLLL', ', 14 2010 ., 15:25'], ['l', '14.2.2010'], ['ll', '14 2010 .'], ['lll', '14 2010 ., 15:25'], ['llll', ', 14 2010 ., 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format meridiem', function (assert) { assert.equal(moment([2012, 11, 28, 0, 0]).format('A'), '', 'night'); assert.equal(moment([2012, 11, 28, 3, 59]).format('A'), '', 'night'); assert.equal(moment([2012, 11, 28, 4, 0]).format('A'), '', 'morning'); assert.equal(moment([2012, 11, 28, 11, 59]).format('A'), '', 'morning'); assert.equal(moment([2012, 11, 28, 12, 0]).format('A'), '', 'afternoon'); assert.equal(moment([2012, 11, 28, 16, 59]).format('A'), '', 'afternoon'); assert.equal(moment([2012, 11, 28, 17, 0]).format('A'), '', 'evening'); assert.equal(moment([2012, 11, 28, 23, 59]).format('A'), '', 'evening'); }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1-', '1-'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2-', '2-'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3-', '3-'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4-', '4-'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5-', '5-'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6-', '6-'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7-', '7-'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8-', '8-'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9-', '9-'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10-', '10-'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11-', '11-'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12-', '12-'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13-', '13-'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14-', '14-'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15-', '15-'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16-', '16-'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17-', '17-'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18-', '18-'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19-', '19-'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20-', '20-'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21-', '21-'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22-', '22-'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23-', '23-'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24-', '24-'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25-', '25-'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26-', '26-'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27-', '27-'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28-', '28-'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29-', '29-'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30-', '30-'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31-', '31-'); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format month case', function (assert) { var months = { 'nominative': '___________'.split('_'), 'accusative': '___________'.split('_') }, i; for (i = 0; i < 12; i++) { assert.equal(moment([2011, i, 1]).format('D MMMM'), '1 ' + months.accusative[i], '1 ' + months.accusative[i]); assert.equal(moment([2011, i, 1]).format('MMMM'), months.nominative[i], '1 ' + months.nominative[i]); } }); test('format month short case', function (assert) { var monthsShort = { 'nominative': '___________'.split('_'), 'accusative': '___________'.split('_') }, i; for (i = 0; i < 12; i++) { assert.equal(moment([2011, i, 1]).format('D MMM'), '1 ' + monthsShort.accusative[i], '1 ' + monthsShort.accusative[i]); assert.equal(moment([2011, i, 1]).format('MMM'), monthsShort.nominative[i], '1 ' + monthsShort.nominative[i]); } }); test('format month case with escaped symbols', function (assert) { var months = { 'nominative': '___________'.split('_'), 'accusative': '___________'.split('_') }, i; for (i = 0; i < 12; i++) { assert.equal(moment([2013, i, 1]).format('D[] MMMM'), '1 ' + months.accusative[i], '1 ' + months.accusative[i]); assert.equal(moment([2013, i, 1]).format('[<i>]D[</i>] [<b>]MMMM[</b>]'), '<i>1</i> <b>' + months.accusative[i] + '</b>', '1 <b>' + months.accusative[i] + '</b>'); assert.equal(moment([2013, i, 1]).format('D[- ] MMMM'), '1- ' + months.accusative[i], '1- ' + months.accusative[i]); assert.equal(moment([2013, i, 1]).format('D, MMMM'), '1, ' + months.nominative[i], '1, ' + months.nominative[i]); } }); test('format month short case with escaped symbols', function (assert) { var monthsShort = { 'nominative': '___________'.split('_'), 'accusative': '___________'.split('_') }, i; for (i = 0; i < 12; i++) { assert.equal(moment([2013, i, 1]).format('D[] MMM'), '1 ' + monthsShort.accusative[i], '1 ' + monthsShort.accusative[i]); assert.equal(moment([2013, i, 1]).format('[<i>]D[</i>] [<b>]MMM[</b>]'), '<i>1</i> <b>' + monthsShort.accusative[i] + '</b>', '1 <b>' + monthsShort.accusative[i] + '</b>'); assert.equal(moment([2013, i, 1]).format('D[- ] MMM'), '1- ' + monthsShort.accusative[i], '1- ' + monthsShort.accusative[i]); assert.equal(moment([2013, i, 1]).format('D, MMM'), '1, ' + monthsShort.nominative[i], '1, ' + monthsShort.nominative[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 11}), true), '11 ', '11 days = 11 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 21}), true), '21 ', '21 days = 21 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in seconds'); assert.equal(moment().add({d: 5}).fromNow(), '5 ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; function makeFormat(d) { return 'dddd [ ] LT'; } for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; function makeFormat(d) { return '[] dddd [ ] LT'; } for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1-', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1-', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2-', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2-', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('id'); test('parse', function (assert) { var tests = 'Januari Jan_Februari Feb_Maret Mar_April Apr_Mei Mei_Juni Jun_Juli Jul_Agustus Ags_September Sep_Oktober Okt_November Nov_Desember Des'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Minggu, Februari 14 2010, 3:25:50 sore'], ['ddd, hA', 'Min, 3sore'], ['M Mo MM MMMM MMM', '2 2 02 Februari Feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 Minggu Min Mg'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '7 7 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'sore sore'], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LTS', '15.25.50'], ['L', '14/02/2010'], ['LL', '14 Februari 2010'], ['LLL', '14 Februari 2010 pukul 15.25'], ['LLLL', 'Minggu, 14 Februari 2010 pukul 15.25'], ['l', '14/2/2010'], ['ll', '14 Feb 2010'], ['lll', '14 Feb 2010 pukul 15.25'], ['llll', 'Min, 14 Feb 2010 pukul 15.25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format month', function (assert) { var expected = 'Januari Jan_Februari Feb_Maret Mar_April Apr_Mei Mei_Juni Jun_Juli Jul_Agustus Ags_September Sep_Oktober Okt_November Nov_Desember Des'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Minggu Min Mg_Senin Sen Sn_Selasa Sel Sl_Rabu Rab Rb_Kamis Kam Km_Jumat Jum Jm_Sabtu Sab Sb'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'beberapa detik', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'semenit', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'semenit', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 menit', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 menit', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'sejam', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'sejam', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 jam', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 jam', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 jam', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'sehari', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'sehari', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 hari', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'sehari', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 hari', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 hari', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'sebulan', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'sebulan', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'sebulan', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 bulan', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 bulan', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 bulan', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'sebulan', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 bulan', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'setahun', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 tahun', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'setahun', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 tahun', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'dalam beberapa detik', 'prefix'); assert.equal(moment(0).from(30000), 'beberapa detik yang lalu', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'beberapa detik yang lalu', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'dalam beberapa detik', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'dalam 5 hari', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Hari ini pukul 12.00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Hari ini pukul 12.25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Hari ini pukul 13.00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Besok pukul 12.00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Hari ini pukul 11.00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Kemarin pukul 12.00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [pukul] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [pukul] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [pukul] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [lalu pukul] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [lalu pukul] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [lalu pukul] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('is'); test('parse', function (assert) { var tests = 'janar jan_febrar feb_mars mar_aprl apr_ma ma_jn jn_jl jl_gst g_september sep_oktber okt_nvember nv_desember des'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, h:mm:ss a', 'sunnudagur, 14. febrar 2010, 3:25:50 pm'], ['ddd, hA', 'sun, 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 febrar feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. sunnudagur sun Su'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14. febrar 2010'], ['LLL', '14. febrar 2010 kl. 15:25'], ['LLLL', 'sunnudagur, 14. febrar 2010 kl. 15:25'], ['l', '14.2.2010'], ['ll', '14. feb 2010'], ['lll', '14. feb 2010 kl. 15:25'], ['llll', 'sun, 14. feb 2010 kl. 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'janar jan_febrar feb_mars mar_aprl apr_ma ma_jn jn_jl jl_gst g_september sep_oktber okt_nvember nv_desember des'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'sunnudagur sun Su_mnudagur mn M_rijudagur ri r_mivikudagur mi Mi_fimmtudagur fim Fi_fstudagur fs F_laugardagur lau La'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'nokkrar sekndur', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'mnta', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'mnta', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 mntur', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 mntur', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 21}), true), '21 mnta', '21 minutes = 21 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'klukkustund', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'klukkustund', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 klukkustundir', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 klukkustundir', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 klukkustund', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'dagur', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'dagur', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dagar', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'dagur', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dagar', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dagar', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 11}), true), '11 dagar', '11 days = 11 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 21}), true), '21 dagur', '21 days = 21 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'mnuur', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'mnuur', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'mnuur', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mnuir', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mnuir', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mnuir', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'mnuur', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mnuir', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'r', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 r', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'r', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 r', '5 years = 5 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 21}), true), '21 r', '21 years = 21 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'eftir nokkrar sekndur', 'prefix'); assert.equal(moment(0).from(30000), 'fyrir nokkrum sekndum san', 'suffix'); assert.equal(moment().subtract({m: 1}).fromNow(), 'fyrir mntu san', 'a minute ago'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'fyrir nokkrum sekndum san', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'eftir nokkrar sekndur', 'in a few seconds'); assert.equal(moment().add({m: 1}).fromNow(), 'eftir mntu', 'in a minute'); assert.equal(moment().add({d: 5}).fromNow(), 'eftir 5 daga', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' dag kl. 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' dag kl. 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' dag kl. 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' morgun kl. 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' dag kl. 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' gr kl. 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [kl.] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [kl.] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [kl.] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[sasta] dddd [kl.] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[sasta] dddd [kl.] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[sasta] dddd [kl.] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('it'); test('parse', function (assert) { var tests = 'gennaio gen_febbraio feb_marzo mar_aprile apr_maggio mag_giugno giu_luglio lug_agosto ago_settembre set_ottobre ott_novembre nov_dicembre dic'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Domenica, febbraio 14 2010, 3:25:50 pm'], ['ddd, hA', 'Dom, 3PM'], ['M Mo MM MMMM MMM', '2 2 02 febbraio feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 Domenica Dom Do'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '6 6 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 febbraio 2010'], ['LLL', '14 febbraio 2010 15:25'], ['LLLL', 'Domenica, 14 febbraio 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 feb 2010'], ['lll', '14 feb 2010 15:25'], ['llll', 'Dom, 14 feb 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = 'gennaio gen_febbraio feb_marzo mar_aprile apr_maggio mag_giugno giu_luglio lug_agosto ago_settembre set_ottobre ott_novembre nov_dicembre dic'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Domenica Dom Do_Luned Lun Lu_Marted Mar Ma_Mercoled Mer Me_Gioved Gio Gi_Venerd Ven Ve_Sabato Sab Sa'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'alcuni secondi', '44 seconds = seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'un minuto', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'un minuto', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minuti', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minuti', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'un\'ora', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'un\'ora', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ore', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ore', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ore', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'un giorno', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'un giorno', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 giorni', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'un giorno', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 giorni', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 giorni', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'un mese', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'un mese', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'un mese', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mesi', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mesi', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mesi', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'un mese', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mesi', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'un anno', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 anni', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'un anno', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 anni', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'in alcuni secondi', 'prefix'); assert.equal(moment(0).from(30000), 'alcuni secondi fa', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'in alcuni secondi', 'in seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'tra 5 giorni', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Oggi alle 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Oggi alle 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Oggi alle 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Domani alle 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Oggi alle 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Ieri alle 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [alle] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [alle] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [alle] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m, weekday, datestring; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); // Different date string weekday = parseInt(m.format('d'), 10); datestring = (weekday === 0) ? '[la scorsa] dddd [alle] LT' : '[lo scorso] dddd [alle] LT'; assert.equal(m.calendar(), m.format(datestring), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(datestring), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(datestring), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('ja'); test('parse', function (assert) { var tests = '1 1_2 2_3 3_4 4_5 5_6 6_7 7_8 8_9 9_10 10_11 11_12 12'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, a h:mm:ss', ', 2 14 2010, 3:25:50'], ['ddd, Ah', ', 3'], ['M Mo MM MMMM MMM', '2 2 02 2 2'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '8 8 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', ' '], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LTS', '32550'], ['L', '2010/02/14'], ['LL', '2010214'], ['LLL', '2010214325'], ['LLLL', '2010214325 '], ['l', '2010/2/14'], ['ll', '2010214'], ['lll', '2010214325'], ['llll', '2010214325 '] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format month', function (assert) { var expected = '1 1_2 2_3 3_4 4_5 5_6 6_7 7_8 8_9 9_10 10_11 11_12 12'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), '', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '1', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '1', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '1', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '1', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '1', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '1', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '1', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '1', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '1', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '1', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '1', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '1', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '1', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), '', 'prefix'); assert.equal(moment(0).from(30000), '', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), '', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), '', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), '5', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 120', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 1225', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 10', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 120', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 110', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 120', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('[]dddd LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[]dddd LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[]dddd LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[]dddd LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[]dddd LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[]dddd LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday format', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('jv'); test('parse', function (assert) { var tests = 'Januari Jan_Februari Feb_Maret Mar_April Apr_Mei Mei_Juni Jun_Juli Jul_Agustus Ags_September Sep_Oktober Okt_Nopember Nop_Desember Des'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Minggu, Februari 14 2010, 3:25:50 sonten'], ['ddd, hA', 'Min, 3sonten'], ['M Mo MM MMMM MMM', '2 2 02 Februari Feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 Minggu Min Mg'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '7 7 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'sonten sonten'], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LTS', '15.25.50'], ['L', '14/02/2010'], ['LL', '14 Februari 2010'], ['LLL', '14 Februari 2010 pukul 15.25'], ['LLLL', 'Minggu, 14 Februari 2010 pukul 15.25'], ['l', '14/2/2010'], ['ll', '14 Feb 2010'], ['lll', '14 Feb 2010 pukul 15.25'], ['llll', 'Min, 14 Feb 2010 pukul 15.25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format month', function (assert) { var expected = 'Januari Jan_Februari Feb_Maret Mar_April Apr_Mei Mei_Juni Jun_Juli Jul_Agustus Ags_September Sep_Oktober Okt_Nopember Nop_Desember Des'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Minggu Min Mg_Senen Sen Sn_Seloso Sel Sl_Rebu Reb Rb_Kemis Kem Km_Jemuwah Jem Jm_Septu Sep Sp'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'sawetawis detik', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'setunggal menit', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'setunggal menit', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 menit', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 menit', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'setunggal jam', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'setunggal jam', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 jam', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 jam', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 jam', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'sedinten', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'sedinten', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dinten', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'sedinten', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dinten', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dinten', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'sewulan', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'sewulan', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'sewulan', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 wulan', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 wulan', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 wulan', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'sewulan', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 wulan', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'setaun', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 taun', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'setaun', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 taun', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'wonten ing sawetawis detik', 'prefix'); assert.equal(moment(0).from(30000), 'sawetawis detik ingkang kepengker', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'sawetawis detik ingkang kepengker', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'wonten ing sawetawis detik', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'wonten ing 5 dinten', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Dinten puniko pukul 12.00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Dinten puniko pukul 12.25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Dinten puniko pukul 13.00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Mbenjang pukul 12.00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Dinten puniko pukul 11.00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Kala wingi pukul 12.00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [pukul] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [pukul] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [pukul] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [kepengker pukul] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [kepengker pukul] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [kepengker pukul] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); // Monday is the first day of the week. // The week that contains Jan 1st is the first week of the year. test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('ka'); test('parse', function (assert) { var i, tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'); function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', ', -14 2010, 3:25:50 pm'], ['ddd, hA', ', 3PM'], ['M Mo MM MMMM MMM', '2 -2 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 -14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45- 045'], ['w wo ww', '7 -7 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], [' DDDo ', ' 45- '], ['LTS', '3:25:50 PM'], ['L', '14/02/2010'], ['LL', '14 2010'], ['LLL', '14 2010 3:25 PM'], ['LLLL', ', 14 2010 3:25 PM'], ['l', '14/2/2010'], ['ll', '14 2010'], ['lll', '14 2010 3:25 PM'], ['llll', ', 14 2010 3:25 PM'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1-', '1-'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '-2', '-2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '-3', '-3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '-4', '-4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '-5', '-5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '-6', '-6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '-7', '-7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '-8', '-8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '-9', '-9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '-10', '-10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '-11', '-11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '-12', '-12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '-13', '-13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '-14', '-14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '-15', '-15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '-16', '-16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '-17', '-17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '-18', '-18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '-19', '-19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '-20', '-20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21-', '21-'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22-', '22-'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23-', '23-'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24-', '24-'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25-', '25-'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26-', '26-'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27-', '27-'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28-', '28-'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29-', '29-'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30-', '30-'); assert.equal(moment('2011 40', 'YYYY DDD').format('DDDo'), '-40', '-40'); assert.equal(moment('2011 50', 'YYYY DDD').format('DDDo'), '50-', '50-'); assert.equal(moment('2011 60', 'YYYY DDD').format('DDDo'), '-60', '-60'); assert.equal(moment('2011 100', 'YYYY DDD').format('DDDo'), '-100', '-100'); assert.equal(moment('2011 101', 'YYYY DDD').format('DDDo'), '101-', '101-'); }); test('format month', function (assert) { var i, expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var i, expected = ' _ _ _ _ _ _ '.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 = '); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '', '45 = '); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '', '89 = '); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 = 44 '); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '', '45 = '); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '', '89 = '); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 = 5 '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 = 21 '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '', '22 = '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '', '35 = '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '', '1 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 = 5 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 = 25 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '', '26 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '', '30 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '', '45 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 = 3 '); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '', '1 = '); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 = 5 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '', '345 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '', '1 = '); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 = 5 '); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', ' '); assert.equal(moment(0).from(30000), ' ', ' '); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', ' '); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', ' '); assert.equal(moment().add({d: 5}).fromNow(), '5 ', '5 '); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00 PM-', ' '); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25 PM-', ' 25 '); assert.equal(moment(a).add({h: 1}).calendar(), ' 1:00 PM-', ' 1 '); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00 PM-', ' '); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00 AM-', ' 1 '); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00 PM-', ' '); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('[] dddd LT[-]'), ' + ' + i + ' '); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd LT[-]'), ' + ' + i + ' '); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd LT[-]'), ' + ' + i + ' '); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[] dddd LT[-]'), ' - ' + i + ' '); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd LT[-]'), ' - ' + i + ' '); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd LT[-]'), ' - ' + i + ' '); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 '); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), '1 '); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 '); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), '2 '); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1-', ' 26 2011 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1-', ' 1 2012 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 -2', ' 2 2012 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 -2', ' 8 2012 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 -3', ' 9 2012 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('kk'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, HH:mm:ss', ', 14- 2010, 15:25:50'], ['ddd, hA', ', 3PM'], ['M Mo MM MMMM MMM', '2 2- 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14- 14'], ['d do dddd ddd dd', '0 0- '], ['DDD DDDo DDDD', '45 45- 045'], ['w wo ww', '7 7- 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[] DDDo []', ' 45- '], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14 2010'], ['LLL', '14 2010 15:25'], ['LLLL', ', 14 2010 15:25'], ['l', '14.2.2010'], ['ll', '14 2010'], ['lll', '14 2010 15:25'], ['llll', ', 14 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1-', '1st'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2-', '2nd'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3-', '3rd'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4-', '4th'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5-', '5th'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6-', '6th'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7-', '7th'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8-', '8th'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9-', '9th'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10-', '10th'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11-', '11th'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12-', '12th'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13-', '13th'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14-', '14th'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15-', '15th'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16-', '16th'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17-', '17th'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18-', '18th'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19-', '19th'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20-', '20th'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21-', '21st'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22-', '22nd'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23-', '23rd'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24-', '24th'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25-', '25th'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26-', '26th'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27-', '27th'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28-', '28th'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29-', '29th'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30-', '30th'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31-', '31st'); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), ' ', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), ' ', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), ' ', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), ' ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), ' ', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), ' ', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), ' ', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), ' ', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), ' ', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), ' ', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), ' ', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), ' ', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), ' ', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), '5 ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[ ] dddd [] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[ ] dddd [] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[ ] dddd [] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1-', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2-', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2-', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-', 'Jan 9 2012 should be week 3'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3-', 'Jan 15 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('km'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', ', 14 2010, 3:25:50 pm'], ['ddd, hA', ', 3PM'], ['M Mo MM MMMM MMM', '2 2 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '6 6 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 2010'], ['LLL', '14 2010 15:25'], ['LLLL', ', 14 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 2010'], ['lll', '14 2010 15:25'], ['llll', ', 14 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1st'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2nd'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3rd'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4th'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5th'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6th'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7th'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8th'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9th'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10th'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11th'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12th'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13th'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14th'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15th'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16th'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17th'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18th'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19th'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20th'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21st'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22nd'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23rd'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24th'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25th'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26th'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27th'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28th'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29th'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30th'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31st'); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), '', '44 seconds = '); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '', '45 seconds = '); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '', '89 seconds = '); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 '); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '', '45 minutes = '); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '', '89 minutes = '); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '', '22 hours = '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '', '35 hours = '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '', '1 day = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '', '26 days = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '', '30 days = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '', '43 days = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 '); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '', '1 month = '); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '', '345 days = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '', '1 year = '); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 '); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), '', 'prefix'); assert.equal(moment(0).from(30000), '', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), '', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({ s: 30 }).fromNow(), '', 'in a few seconds'); assert.equal(moment().add({ d: 5 }).fromNow(), '5 ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({ d: i }); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({ d: i }); assert.equal(m.calendar(), m.format('dddd [] [] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [] [] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [] [] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({ w: 1 }), weeksFromNow = moment().add({ w: 1 }); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({ w: 2 }); weeksFromNow = moment().add({ w: 2 }); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('ko'); test('parse', function (assert) { var tests = '1 1_2 2_3 3_4 4_5 5_6 6_7 7_8 8_9 9_10 10_11 11_12 12'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('parse meridiem', function (assert) { var elements = [{ expression : '1981 9 8 2 30', inputFormat : 'YYYY[] M[] D[] A h[] m[]', outputFormat : 'A', expected : '' }, { expression : '1981 9 8 2 30', inputFormat : 'YYYY[] M[] D[] A h[] m[]', outputFormat : 'A h', expected : ' 2' }, { expression : '14 30', inputFormat : 'H[] m[]', outputFormat : 'A', expected : '' }, { expression : ' 4', inputFormat : 'A h[]', outputFormat : 'H', expected : '16' }], i, l, it, actual; for (i = 0, l = elements.length; i < l; ++i) { it = elements[i]; actual = moment(it.expression, it.inputFormat).format(it.outputFormat); assert.equal( actual, it.expected, '\'' + it.outputFormat + '\' of \'' + it.expression + '\' must be \'' + it.expected + '\' but was \'' + actual + '\'.' ); } }); test('format', function (assert) { var a = [ ['YYYY MMMM Do dddd a h:mm:ss', '2010 2 14 3:25:50'], ['ddd A h', ' 3'], ['M Mo MM MMMM MMM', '2 2 02 2 2'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '8 8 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', ' '], [' DDDo ', ' 45 '], ['LTS', ' 3 25 50'], ['L', '2010.02.14'], ['LL', '2010 2 14'], ['LLL', '2010 2 14 3 25'], ['LLLL', '2010 2 14 3 25'], ['l', '2010.2.14'], ['ll', '2010 2 14'], ['lll', '2010 2 14 3 25'], ['llll', '2010 2 14 3 25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = '1 1_2 2_3 3_4 4_5 5_6 6_7 7_8 8_9 9_10 10_11 11_12 12'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 = '); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '', '45 = '); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '', '89 = '); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2', '90 = 2'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44', '44 = 44'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), ' ', '45 = '); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), ' ', '89 = '); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2', '90 = 2'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5', '5 = 5'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21', '21 = 21'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '', '22 = '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '', '35 = '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2', '36 = 2'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5', '5 = 5'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25', '25 = 25'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), ' ', '26 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), ' ', '30 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), ' ', '45 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2', '46 = 2'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2', '75 = 2'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3', '76 = 3'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), ' ', '1 = '); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5', '5 = 5'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), ' ', '345 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2', '548 = 2'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5', '5 = 5'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), '5 ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12 0', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12 25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 1 0', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12 0', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11 0', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12 0', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format(' dddd LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(' dddd LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(' dddd LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday format', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('ky'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, HH:mm:ss', ', 14- 2010, 15:25:50'], ['ddd, hA', ', 3PM'], ['M Mo MM MMMM MMM', '2 2- 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14- 14'], ['d do dddd ddd dd', '0 0- '], ['DDD DDDo DDDD', '45 45- 045'], ['w wo ww', '7 7- 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[] DDDo []', ' 45- '], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14 2010'], ['LLL', '14 2010 15:25'], ['LLLL', ', 14 2010 15:25'], ['l', '14.2.2010'], ['ll', '14 2010'], ['lll', '14 2010 15:25'], ['llll', ', 14 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1-', '1st'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2-', '2nd'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3-', '3rd'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4-', '4th'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5-', '5th'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6-', '6th'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7-', '7th'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8-', '8th'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9-', '9th'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10-', '10th'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11-', '11th'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12-', '12th'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13-', '13th'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14-', '14th'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15-', '15th'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16-', '16th'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17-', '17th'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18-', '18th'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19-', '19th'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20-', '20th'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21-', '21st'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22-', '22nd'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23-', '23rd'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24-', '24th'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25-', '25th'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26-', '26th'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27-', '27th'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28-', '28th'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29-', '29th'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30-', '30th'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31-', '31st'); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), ' ', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), ' ', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), ' ', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), ' ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), ' ', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), ' ', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), ' ', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), ' ', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), ' ', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), ' ', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), ' ', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), ' ', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), ' ', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), '5 ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[ ] dddd [] [] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[ ] dddd [] [] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[ ] dddd [] [] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1-', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2-', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2-', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-', 'Jan 9 2012 should be week 3'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3-', 'Jan 15 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('lb'); test('parse', function (assert) { var tests = 'Januar Jan._Februar Febr._Merz Mrz._Abrll Abr._Mee Mee_Juni Jun._Juli Jul._August Aug._September Sept._Oktober Okt._November Nov._Dezember Dez.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, HH:mm:ss', 'Sonndeg, 14. Februar 2010, 15:25:50'], ['ddd, HH:mm', 'So., 15:25'], ['M Mo MM MMMM MMM', '2 2. 02 Februar Febr.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. Sonndeg So. So'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['LTS', '15:25:50 Auer'], ['L', '14.02.2010'], ['LL', '14. Februar 2010'], ['LLL', '14. Februar 2010 15:25 Auer'], ['LLLL', 'Sonndeg, 14. Februar 2010 15:25 Auer'], ['l', '14.2.2010'], ['ll', '14. Febr. 2010'], ['lll', '14. Febr. 2010 15:25 Auer'], ['llll', 'So., 14. Febr. 2010 15:25 Auer'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format month', function (assert) { var expected = 'Januar Jan._Februar Febr._Merz Mrz._Abrll Abr._Mee Mee_Juni Jun._Juli Jul._August Aug._September Sept._Oktober Okt._November Nov._Dezember Dez.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Sonndeg So. So_Mindeg M. M_Dnschdeg D. D_Mttwoch M. M_Donneschdeg Do. Do_Freideg Fr. Fr_Samschdeg Sa. Sa'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'e puer Sekonnen', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'eng Minutt', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'eng Minutt', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 Minutten', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 Minutten', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'eng Stonn', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'eng Stonn', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 Stonnen', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 Stonnen', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 Stonnen', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'een Dag', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'een Dag', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 Deeg', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'een Dag', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 Deeg', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 Deeg', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'ee Mount', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'ee Mount', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'ee Mount', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 Mint', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 Mint', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 Mint', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'ee Mount', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 Mint', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'ee Joer', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 Joer', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'ee Joer', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 Joer', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'an e puer Sekonnen', 'prefix'); assert.equal(moment(0).from(30000), 'virun e puer Sekonnen', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'an e puer Sekonnen', 'in a few seconds'); assert.equal(moment().add({d: 1}).fromNow(), 'an engem Dag', 'in one day'); assert.equal(moment().add({d: 2}).fromNow(), 'an 2 Deeg', 'in 2 days'); assert.equal(moment().add({d: 3}).fromNow(), 'an 3 Deeg', 'in 3 days'); assert.equal(moment().add({d: 4}).fromNow(), 'a 4 Deeg', 'in 4 days'); assert.equal(moment().add({d: 5}).fromNow(), 'a 5 Deeg', 'in 5 days'); assert.equal(moment().add({d: 6}).fromNow(), 'a 6 Deeg', 'in 6 days'); assert.equal(moment().add({d: 7}).fromNow(), 'a 7 Deeg', 'in 7 days'); assert.equal(moment().add({d: 8}).fromNow(), 'an 8 Deeg', 'in 8 days'); assert.equal(moment().add({d: 9}).fromNow(), 'an 9 Deeg', 'in 9 days'); assert.equal(moment().add({d: 10}).fromNow(), 'an 10 Deeg', 'in 10 days'); assert.equal(moment().add({y: 100}).fromNow(), 'an 100 Joer', 'in 100 years'); assert.equal(moment().add({y: 400}).fromNow(), 'a 400 Joer', 'in 400 years'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Haut um 12:00 Auer', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Haut um 12:25 Auer', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Haut um 13:00 Auer', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Muer um 12:00 Auer', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Haut um 11:00 Auer', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Gschter um 12:00 Auer', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [um] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [um] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [um] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m, weekday, datestring; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); // Different date string for 'Dnschdeg' (Tuesday) and 'Donneschdeg' (Thursday) weekday = parseInt(m.format('d'), 10); datestring = (weekday === 2 || weekday === 4 ? '[Leschten] dddd [um] LT' : '[Leschte] dddd [um] LT'); assert.equal(m.calendar(), m.format(datestring), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(datestring), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(datestring), 'Today + ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday format', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1.', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2.', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('lo'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', ', 14 2010, 3:25:50 '], ['ddd, hA', ', 3'], ['M Mo MM MMMM MMM', '2 2 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '8 8 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', ' '], ['[]DDDo []', '45 '], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 2010'], ['LLL', '14 2010 15:25'], ['LLLL', ' 14 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 2010'], ['lll', '14 2010 15:25'], ['llll', ' 14 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), '', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '1 ', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '1 ', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '1 ', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '1 ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '1 ', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '1 ', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '1 ', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '1 ', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '1 ', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '1 ', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '1 ', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '1 ', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '1 ', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), '', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), '', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' 5 ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('[]dddd[] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[]dddd[] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[]dddd[] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[]dddd[] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[]dddd[] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[]dddd[] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday format', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('lt'); test('parse', function (assert) { var tests = 'sausis sau_vasaris vas_kovas kov_balandis bal_gegu geg_birelis bir_liepa lie_rugpjtis rgp_rugsjis rgs_spalis spa_lapkritis lap_gruodis grd'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, h:mm:ss a', 'sekmadienis, 14-oji vasario 2010, 3:25:50 pm'], ['ddd, hA', 'Sek, 3PM'], ['M Mo MM MMMM MMM', '2 2-oji 02 vasaris vas'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14-oji 14'], ['d do dddd ddd dd', '0 0-oji sekmadienis Sek S'], ['DDD DDDo DDDD', '45 45-oji 045'], ['w wo ww', '6 6-oji 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['DDDo [met diena]', '45-oji met diena'], ['LTS', '15:25:50'], ['L', '2010-02-14'], ['LL', '2010 m. vasaris 14 d.'], ['LLL', '2010 m. vasaris 14 d., 15:25 val.'], ['LLLL', '2010 m. vasaris 14 d., sekmadienis, 15:25 val.'], ['l', '2010-02-14'], ['ll', '2010 m. vasaris 14 d.'], ['lll', '2010 m. vasaris 14 d., 15:25 val.'], ['llll', '2010 m. vasaris 14 d., Sek, 15:25 val.'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1-oji', '1-oji'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2-oji', '2-oji'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3-oji', '3-oji'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4-oji', '4-oji'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5-oji', '5-oji'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6-oji', '6-oji'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7-oji', '7-oji'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8-oji', '8-oji'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9-oji', '9-oji'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10-oji', '10-oji'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11-oji', '11-oji'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12-oji', '12-oji'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13-oji', '13-oji'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14-oji', '14-oji'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15-oji', '15-oji'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16-oji', '16-oji'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17-oji', '17-oji'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18-oji', '18-oji'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19-oji', '19-oji'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20-oji', '20-oji'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21-oji', '21-oji'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22-oji', '22-oji'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23-oji', '23-oji'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24-oji', '24-oji'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25-oji', '25-oji'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26-oji', '26-oji'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27-oji', '27-oji'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28-oji', '28-oji'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29-oji', '29-oji'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30-oji', '30-oji'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31-oji', '31-oji'); }); test('format month', function (assert) { var expected = 'sausis sau_vasaris vas_kovas kov_balandis bal_gegu geg_birelis bir_liepa lie_rugpjtis rgp_rugsjis rgs_spalis spa_lapkritis lap_gruodis grd'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'sekmadienis Sek S_pirmadienis Pir P_antradienis Ant A_treiadienis Tre T_ketvirtadienis Ket K_penktadienis Pen Pn_etadienis e '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('format week on US calendar', function (assert) { // Tests, whether the weekday names are correct, even if the week does not start on Monday moment.updateLocale('lt', {week: {dow: 0, doy: 6}}); var expected = 'sekmadienis Sek S_pirmadienis Pir P_antradienis Ant A_treiadienis Tre T_ketvirtadienis Ket K_penktadienis Pen Pn_etadienis e '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } moment.updateLocale('lt', null); }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'kelios sekunds', '44 seconds = seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'minut', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'minut', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minuts', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 10}), true), '10 minui', '10 minutes = 10 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 11}), true), '11 minui', '11 minutes = 11 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 19}), true), '19 minui', '19 minutes = 19 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 20}), true), '20 minui', '20 minutes = 20 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minuts', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'valanda', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'valanda', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 valandos', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 valandos', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 10}), true), '10 valand', '10 hours = 10 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 valandos', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'diena', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'diena', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dienos', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'diena', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dienos', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 10}), true), '10 dien', '10 days = 10 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dienos', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'mnuo', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'mnuo', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'mnuo', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mnesiai', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mnesiai', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mnesiai', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'mnuo', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mnesiai', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 10}), true), '10 mnesi', '10 months = 10 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'metai', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 metai', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'metai', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 metai', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'po keli sekundi', 'prefix'); assert.equal(moment(0).from(30000), 'prie kelias sekundes', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'prie kelias sekundes', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'po keli sekundi', 'in seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'po 5 dien', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'iandien 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'iandien 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'iandien 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Rytoj 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'iandien 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Vakar 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[Prajus] dddd LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[Prajus] dddd LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[Prajus] dddd LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52-oji', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1-oji', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1-oji', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2-oji', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2-oji', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('lv'); test('parse', function (assert) { var tests = 'janvris jan_februris feb_marts mar_aprlis apr_maijs mai_jnijs jn_jlijs jl_augusts aug_septembris sep_oktobris okt_novembris nov_decembris dec'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, h:mm:ss a', 'svtdiena, 14. februris 2010, 3:25:50 pm'], ['ddd, hA', 'Sv, 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 februris feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. svtdiena Sv Sv'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['LTS', '15:25:50'], ['L', '14.02.2010.'], ['LL', '2010. gada 14. februris'], ['LLL', '2010. gada 14. februris, 15:25'], ['LLLL', '2010. gada 14. februris, svtdiena, 15:25'], ['l', '14.2.2010.'], ['ll', '2010. gada 14. feb'], ['lll', '2010. gada 14. feb, 15:25'], ['llll', '2010. gada 14. feb, Sv, 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'janvris jan_februris feb_marts mar_aprlis apr_maijs mai_jnijs jn_jlijs jl_augusts aug_septembris sep_oktobris okt_novembris nov_decembris dec'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'svtdiena Sv Sv_pirmdiena P P_otrdiena O O_trediena T T_ceturtdiena C C_piektdiena Pk Pk_sestdiena S S'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); // Includes testing the cases of withoutSuffix = true and false. test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'daas sekundes', '44 seconds = seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), false), 'pirms dam sekundm', '44 seconds with suffix = seconds ago'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'minte', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), false), 'pirms mintes', '45 seconds with suffix = a minute ago'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'minte', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: -89}), false), 'pc mintes', '89 seconds with suffix/prefix = in a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 mintes', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), false), 'pirms 2 mintm', '90 seconds with suffix = 2 minutes ago'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 mintes', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), false), 'pirms 44 mintm', '44 minutes with suffix = 44 minutes ago'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'stunda', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), false), 'pirms stundas', '45 minutes with suffix = an hour ago'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'stunda', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 stundas', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({m: -90}), false), 'pc 2 stundm', '90 minutes with suffix = in 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 stundas', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), false), 'pirms 5 stundm', '5 hours with suffix = 5 hours ago'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 stunda', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), false), 'pirms 21 stundas', '21 hours with suffix = 21 hours ago'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'diena', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), false), 'pirms dienas', '22 hours with suffix = a day ago'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'diena', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dienas', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), false), 'pirms 2 dienm', '36 hours with suffix = 2 days ago'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'diena', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dienas', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), false), 'pirms 5 dienm', '5 days with suffix = 5 days ago'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dienas', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), false), 'pirms 25 dienm', '25 days with suffix = 25 days ago'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'mnesis', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), false), 'pirms mnea', '26 days with suffix = a month ago'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'mnesis', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'mnesis', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mnei', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), false), 'pirms 2 mneiem', '46 days with suffix = 2 months ago'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mnei', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mnei', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), false), 'pirms 3 mneiem', '76 days with suffix = 3 months ago'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'mnesis', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mnei', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), false), 'pirms 5 mneiem', '5 months with suffix = 5 months ago'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'gads', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), false), 'pirms gada', '345 days with suffix = a year ago'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 gadi', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), false), 'pirms 2 gadiem', '548 days with suffix = 2 years ago'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'gads', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 gadi', '5 years = 5 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), false), 'pirms 5 gadiem', '5 years with suffix = 5 years ago'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'pc dam sekundm', 'prefix'); assert.equal(moment(0).from(30000), 'pirms dam sekundm', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'pirms dam sekundm', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'pc dam sekundm', 'in seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'pc 5 dienm', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'odien pulksten 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'odien pulksten 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'odien pulksten 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Rt pulksten 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'odien pulksten 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Vakar pulksten 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [pulksten] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [pulksten] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [pulksten] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[Pagju] dddd [pulksten] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[Pagju] dddd [pulksten] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[Pagju] dddd [pulksten] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('me'); test('parse', function (assert) { var tests = 'januar jan._februar feb._mart mar._april apr._maj maj_jun jun_jul jul_avgust avg._septembar sep._oktobar okt._novembar nov._decembar dec.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, h:mm:ss a', 'nedjelja, 14. februar 2010, 3:25:50 pm'], ['ddd, hA', 'ned., 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 februar feb.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. nedjelja ned. ne'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '7 7. 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['LTS', '15:25:50'], ['L', '14. 02. 2010'], ['LL', '14. februar 2010'], ['LLL', '14. februar 2010 15:25'], ['LLLL', 'nedjelja, 14. februar 2010 15:25'], ['l', '14. 2. 2010'], ['ll', '14. feb. 2010'], ['lll', '14. feb. 2010 15:25'], ['llll', 'ned., 14. feb. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'januar jan._februar feb._mart mar._april apr._maj maj_jun jun_jul jul_avgust avg._septembar sep._oktobar okt._novembar nov._decembar dec.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'nedjelja ned. ne_ponedjeljak pon. po_utorak uto. ut_srijeda sri. sr_etvrtak et. e_petak pet. pe_subota sub. su'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'nekoliko sekundi', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'jedan minut', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'jedan minut', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minuta', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minuta', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'jedan sat', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'jedan sat', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 sata', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 sati', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 sati', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'dan', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'dan', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dana', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'dan', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dana', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dana', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'mjesec', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'mjesec', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'mjesec', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mjeseca', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mjeseca', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mjeseca', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'mjesec', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mjeseci', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'godinu', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 godine', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'godinu', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 godina', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'za nekoliko sekundi', 'prefix'); assert.equal(moment(0).from(30000), 'prije nekoliko sekundi', 'prefix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'prije nekoliko sekundi', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'za nekoliko sekundi', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'za 5 dana', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'danas u 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'danas u 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'danas u 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'sjutra u 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'danas u 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'jue u 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; function makeFormat(d) { switch (d.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'; } } for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; function makeFormat(d) { var lastWeekDay = [ '[prole] [nedjelje] [u] LT', '[prolog] [ponedjeljka] [u] LT', '[prolog] [utorka] [u] LT', '[prole] [srijede] [u] LT', '[prolog] [etvrtka] [u] LT', '[prolog] [petka] [u] LT', '[prole] [subote] [u] LT' ]; return lastWeekDay[d.day()]; } for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); // Monday is the first day of the week. // The week that contains Jan 1st is the first week of the year. test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1.', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1.', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2.', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2.', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3.', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('mk'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, H:mm:ss', ', 14- 2010, 15:25:50'], ['ddd, hA', ', 3PM'], ['M Mo MM MMMM MMM', '2 2- 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14- 14'], ['d do dddd ddd dd', '0 0- e'], ['DDD DDDo DDDD', '45 45- 045'], ['w wo ww', '7 7- 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45- day of the year'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14 2010'], ['LLL', '14 2010 15:25'], ['LLLL', ', 14 2010 15:25'], ['l', '14.2.2010'], ['ll', '14 2010'], ['lll', '14 2010 15:25'], ['llll', ', 14 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1-', '1-'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2-', '2-'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3-', '3-'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4-', '4-'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5-', '5-'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6-', '6-'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7-', '7-'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8-', '8-'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9-', '9-'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10-', '10-'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11-', '11-'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12-', '12-'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13-', '13-'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14-', '14-'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15-', '15-'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16-', '16-'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17-', '17-'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18-', '18-'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19-', '19-'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20-', '20-'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21-', '21-'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22-', '22-'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23-', '23-'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24-', '24-'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25-', '25-'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26-', '26-'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27-', '27-'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28-', '28-'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29-', '29-'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30-', '30-'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31-', '31-'); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' e_ o_ _ _ _ _ a'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' 5 ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('[] dddd [] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd [] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd [] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; function makeFormat(d) { switch (d.day()) { case 0: case 3: case 6: return '[] dddd [] LT'; case 1: case 2: case 4: case 5: return '[] dddd [] LT'; } } for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1-', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1-', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2-', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2-', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('ml'); test('parse', function (assert) { var tests = ' ._ ._ ._ ._ _ _ ._ ._ ._ ._ ._ .'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, a h:mm:ss -', ', 14 2010, 3:25:50 -'], ['ddd, a h -', ', 3 -'], ['M Mo MM MMMM MMM', '2 2 02 .'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '8 8 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', ' '], ['LTS', ' 3:25:50 -'], ['L', '14/02/2010'], ['LL', '14 2010'], ['LLL', '14 2010, 3:25 -'], ['LLLL', ', 14 2010, 3:25 -'], ['l', '14/2/2010'], ['ll', '14 . 2010'], ['lll', '14 . 2010, 3:25 -'], ['llll', ', 14 . 2010, 3:25 -'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = ' ._ ._ ._ ._ _ _ ._ ._ ._ ._ ._ .'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), ' ', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), ' ', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), ' ', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), ' ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), ' ', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), ' ', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), ' ', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), ' ', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), ' ', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), ' ', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), ' ', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), ' ', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), ' ', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', ' '); assert.equal(moment().add({d: 5}).fromNow(), '5 ', '5 '); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00 -', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25 -', 'Now plus 25 min'); assert.equal(moment(a).add({h: 3}).calendar(), ' 3:00 -', 'Now plus 3 hours'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00 -', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00 -', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00 -', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('meridiem', function (assert) { assert.equal(moment([2011, 2, 23, 2, 30]).format('a'), '', 'before dawn'); assert.equal(moment([2011, 2, 23, 9, 30]).format('a'), '', 'morning'); assert.equal(moment([2011, 2, 23, 14, 30]).format('a'), ' ', 'during day'); assert.equal(moment([2011, 2, 23, 17, 30]).format('a'), '', 'evening'); assert.equal(moment([2011, 2, 23, 19, 30]).format('a'), '', 'late evening'); assert.equal(moment([2011, 2, 23, 21, 20]).format('a'), '', 'night'); assert.equal(moment([2011, 2, 23, 2, 30]).format('A'), '', 'before dawn'); assert.equal(moment([2011, 2, 23, 9, 30]).format('A'), '', 'morning'); assert.equal(moment([2011, 2, 23, 14, 30]).format('A'), ' ', ' during day'); assert.equal(moment([2011, 2, 23, 17, 30]).format('A'), '', 'evening'); assert.equal(moment([2011, 2, 23, 19, 30]).format('A'), '', 'late evening'); assert.equal(moment([2011, 2, 23, 21, 20]).format('A'), '', 'night'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('mr'); test('parse', function (assert) { var tests = ' ._ ._ ._ ._ ._ ._ ._ ._ ._ ._ ._ .'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, a h:mm:ss ', ', , :: '], ['ddd, a h ', ', '], ['M Mo MM MMMM MMM', ' .'], ['YYYY YY', ' '], ['D Do DD', ' '], ['d do dddd ddd dd', ' '], ['DDD DDDo DDDD', ' '], ['w wo ww', ' '], ['h hh', ' '], ['H HH', ' '], ['m mm', ' '], ['s ss', ' '], ['a A', ' '], ['LTS', ' :: '], ['L', '//'], ['LL', ' '], ['LLL', ' , : '], ['LLLL', ', , : '], ['l', '//'], ['ll', ' . '], ['lll', ' . , : '], ['llll', ', . , : '] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 2]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 3]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 4]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 5]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 6]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 7]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 8]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 9]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 10]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 11]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 12]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 13]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 14]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 15]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 16]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 17]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 18]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 19]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 20]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 21]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 22]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 23]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 24]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 25]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 26]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 27]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 28]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 29]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 30]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 31]).format('DDDo'), '', ''); }); test('format month', function (assert) { var expected = ' ._ ._ ._ ._ ._ ._ ._ ._ ._ ._ ._ .'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), ' ', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), ' ', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), ' ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), ' ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), ' ', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), ' ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), ' ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), ' ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), ' ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), ' ', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), ' ', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), ' ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), ' ', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), ' ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), ' ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), ' ', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), ' ', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), ' ', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), ' ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), ' ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), ' ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), ' ', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), ' ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), ' ', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), ' ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), ' ', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), ' ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' : ', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' : ', 'Now plus 25 min'); assert.equal(moment(a).add({h: 3}).calendar(), ' : ', 'Now plus 3 hours'); assert.equal(moment(a).add({d: 1}).calendar(), ' : ', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' : ', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' : ', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('meridiem', function (assert) { assert.equal(moment([2011, 2, 23, 2, 30]).format('a'), '', 'before dawn'); assert.equal(moment([2011, 2, 23, 9, 30]).format('a'), '', 'morning'); assert.equal(moment([2011, 2, 23, 14, 30]).format('a'), '', 'during day'); assert.equal(moment([2011, 2, 23, 17, 30]).format('a'), '', 'evening'); assert.equal(moment([2011, 2, 23, 19, 30]).format('a'), '', 'late evening'); assert.equal(moment([2011, 2, 23, 21, 20]).format('a'), '', 'night'); assert.equal(moment([2011, 2, 23, 2, 30]).format('A'), '', 'before dawn'); assert.equal(moment([2011, 2, 23, 9, 30]).format('A'), '', 'morning'); assert.equal(moment([2011, 2, 23, 14, 30]).format('A'), '', ' during day'); assert.equal(moment([2011, 2, 23, 17, 30]).format('A'), '', 'evening'); assert.equal(moment([2011, 2, 23, 19, 30]).format('A'), '', 'late evening'); assert.equal(moment([2011, 2, 23, 21, 20]).format('A'), '', 'night'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), ' ', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), ' ', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), ' ', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), ' ', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), ' ', 'Jan 15 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('ms-my'); test('parse', function (assert) { var i, tests = 'Januari Jan_Februari Feb_Mac Mac_April Apr_Mei Mei_Jun Jun_Julai Jul_Ogos Ogs_September Sep_Oktober Okt_November Nov_Disember Dis'.split('_'); function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' sepatutnya bulan ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Ahad, Februari 14 2010, 3:25:50 petang'], ['ddd, hA', 'Ahd, 3petang'], ['M Mo MM MMMM MMM', '2 2 02 Februari Feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 Ahad Ahd Ah'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '7 7 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'petang petang'], ['[hari] [ke] DDDo [tahun] ini', 'hari ke 45 tahun ini'], ['LTS', '15.25.50'], ['L', '14/02/2010'], ['LL', '14 Februari 2010'], ['LLL', '14 Februari 2010 pukul 15.25'], ['LLLL', 'Ahad, 14 Februari 2010 pukul 15.25'], ['l', '14/2/2010'], ['ll', '14 Feb 2010'], ['lll', '14 Feb 2010 pukul 15.25'], ['llll', 'Ahd, 14 Feb 2010 pukul 15.25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var i, expected = 'Januari Jan_Februari Feb_Mac Mac_April Apr_Mei Mei_Jun Jun_Julai Jul_Ogos Ogs_September Sep_Oktober Okt_November Nov_Disember Dis'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var i, expected = 'Ahad Ahd Ah_Isnin Isn Is_Selasa Sel Sl_Rabu Rab Rb_Khamis Kha Km_Jumaat Jum Jm_Sabtu Sab Sb'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'beberapa saat', '44 saat = beberapa saat'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'seminit', '45 saat = seminit'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'seminit', '89 saat = seminit'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minit', '90 saat = 2 minit'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minit', '44 minit = 44 minit'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'sejam', '45 minit = sejam'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'sejam', '89 minit = sejam'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 jam', '90 minit = 2 jam'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 jam', '5 jam = 5 jam'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 jam', '21 jam = 21 jam'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'sehari', '22 jam = sehari'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'sehari', '35 jam = sehari'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 hari', '36 jam = 2 hari'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'sehari', '1 hari = sehari'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 hari', '5 hari = 5 hari'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 hari', '25 hari = 25 hari'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'sebulan', '26 hari = sebulan'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'sebulan', '30 hari = sebulan'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'sebulan', '45 hari = sebulan'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 bulan', '46 hari = 2 bulan'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 bulan', '75 hari = 2 bulan'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 bulan', '76 hari = 3 bulan'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'sebulan', '1 bulan = sebulan'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 bulan', '5 bulan = 5 bulan'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'setahun', '345 hari = setahun'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 tahun', '548 hari = 2 tahun'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'setahun', '1 tahun = setahun'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 tahun', '5 tahun = 5 tahun'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'dalam beberapa saat', 'prefix'); assert.equal(moment(0).from(30000), 'beberapa saat yang lepas', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'beberapa saat yang lepas', 'waktu sekarang dari sekarang sepatutnya menunjukkan sebagai telah lepas'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'dalam beberapa saat', 'dalam beberapa saat'); assert.equal(moment().add({d: 5}).fromNow(), 'dalam 5 hari', 'dalam 5 hari'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Hari ini pukul 12.00', 'hari ini pada waktu yang sama'); assert.equal(moment(a).add({m: 25}).calendar(), 'Hari ini pukul 12.25', 'Sekarang tambah 25 minit'); assert.equal(moment(a).add({h: 1}).calendar(), 'Hari ini pukul 13.00', 'Sekarang tambah 1 jam'); assert.equal(moment(a).add({d: 1}).calendar(), 'Esok pukul 12.00', 'esok pada waktu yang sama'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Hari ini pukul 11.00', 'Sekarang tolak 1 jam'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Kelmarin pukul 12.00', 'kelmarin pada waktu yang sama'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [pukul] LT'), 'Hari ini + ' + i + ' hari waktu sekarang'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [pukul] LT'), 'Hari ini + ' + i + ' hari permulaan hari'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [pukul] LT'), 'Hari ini + ' + i + ' hari tamat hari'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [lepas] [pukul] LT'), 'Hari ini - ' + i + ' hari waktu sekarang'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [lepas] [pukul] LT'), 'Hari ini - ' + i + ' hari permulaan hari'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [lepas] [pukul] LT'), 'Hari ini - ' + i + ' hari tamat hari'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 minggu lepas'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'dalam 1 minggu'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 minggu lepas'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'dalam 2 minggu'); }); test('weeks year starting sunday format', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 sepatutnya minggu 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '2 02 2', 'Jan 7 2012 sepatutnya minggu 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 sepatutnya minggu 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '3 03 3', 'Jan 14 2012 sepatutnya minggu 3'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 sepatutnya minggu 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('ms'); test('parse', function (assert) { var i, tests = 'Januari Jan_Februari Feb_Mac Mac_April Apr_Mei Mei_Jun Jun_Julai Jul_Ogos Ogs_September Sep_Oktober Okt_November Nov_Disember Dis'.split('_'); function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' sepatutnya bulan ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Ahad, Februari 14 2010, 3:25:50 petang'], ['ddd, hA', 'Ahd, 3petang'], ['M Mo MM MMMM MMM', '2 2 02 Februari Feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 Ahad Ahd Ah'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '7 7 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'petang petang'], ['[hari] [ke] DDDo [tahun] ini', 'hari ke 45 tahun ini'], ['LTS', '15.25.50'], ['L', '14/02/2010'], ['LL', '14 Februari 2010'], ['LLL', '14 Februari 2010 pukul 15.25'], ['LLLL', 'Ahad, 14 Februari 2010 pukul 15.25'], ['l', '14/2/2010'], ['ll', '14 Feb 2010'], ['lll', '14 Feb 2010 pukul 15.25'], ['llll', 'Ahd, 14 Feb 2010 pukul 15.25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var i, expected = 'Januari Jan_Februari Feb_Mac Mac_April Apr_Mei Mei_Jun Jun_Julai Jul_Ogos Ogs_September Sep_Oktober Okt_November Nov_Disember Dis'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var i, expected = 'Ahad Ahd Ah_Isnin Isn Is_Selasa Sel Sl_Rabu Rab Rb_Khamis Kha Km_Jumaat Jum Jm_Sabtu Sab Sb'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'beberapa saat', '44 saat = beberapa saat'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'seminit', '45 saat = seminit'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'seminit', '89 saat = seminit'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minit', '90 saat = 2 minit'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minit', '44 minit = 44 minit'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'sejam', '45 minit = sejam'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'sejam', '89 minit = sejam'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 jam', '90 minit = 2 jam'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 jam', '5 jam = 5 jam'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 jam', '21 jam = 21 jam'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'sehari', '22 jam = sehari'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'sehari', '35 jam = sehari'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 hari', '36 jam = 2 hari'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'sehari', '1 hari = sehari'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 hari', '5 hari = 5 hari'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 hari', '25 hari = 25 hari'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'sebulan', '26 hari = sebulan'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'sebulan', '30 hari = sebulan'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'sebulan', '45 hari = sebulan'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 bulan', '46 hari = 2 bulan'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 bulan', '75 hari = 2 bulan'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 bulan', '76 hari = 3 bulan'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'sebulan', '1 bulan = sebulan'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 bulan', '5 bulan = 5 bulan'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'setahun', '345 hari = setahun'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 tahun', '548 hari = 2 tahun'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'setahun', '1 tahun = setahun'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 tahun', '5 tahun = 5 tahun'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'dalam beberapa saat', 'prefix'); assert.equal(moment(0).from(30000), 'beberapa saat yang lepas', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'beberapa saat yang lepas', 'waktu sekarang dari sekarang sepatutnya menunjukkan sebagai telah lepas'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'dalam beberapa saat', 'dalam beberapa saat'); assert.equal(moment().add({d: 5}).fromNow(), 'dalam 5 hari', 'dalam 5 hari'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Hari ini pukul 12.00', 'hari ini pada waktu yang sama'); assert.equal(moment(a).add({m: 25}).calendar(), 'Hari ini pukul 12.25', 'Sekarang tambah 25 minit'); assert.equal(moment(a).add({h: 1}).calendar(), 'Hari ini pukul 13.00', 'Sekarang tambah 1 jam'); assert.equal(moment(a).add({d: 1}).calendar(), 'Esok pukul 12.00', 'esok pada waktu yang sama'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Hari ini pukul 11.00', 'Sekarang tolak 1 jam'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Kelmarin pukul 12.00', 'kelmarin pada waktu yang sama'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [pukul] LT'), 'Hari ini + ' + i + ' hari waktu sekarang'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [pukul] LT'), 'Hari ini + ' + i + ' hari permulaan hari'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [pukul] LT'), 'Hari ini + ' + i + ' hari tamat hari'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [lepas] [pukul] LT'), 'Hari ini - ' + i + ' hari waktu sekarang'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [lepas] [pukul] LT'), 'Hari ini - ' + i + ' hari permulaan hari'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [lepas] [pukul] LT'), 'Hari ini - ' + i + ' hari tamat hari'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 minggu lepas'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'dalam 1 minggu'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 minggu lepas'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'dalam 2 minggu'); }); test('weeks year starting sunday format', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 sepatutnya minggu 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '2 02 2', 'Jan 7 2012 sepatutnya minggu 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 sepatutnya minggu 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '3 03 3', 'Jan 14 2012 sepatutnya minggu 3'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 sepatutnya minggu 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('my'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest (input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', ', , :: pm'], ['ddd, hA', ', PM'], ['M Mo MM MMMM MMM', ' '], ['YYYY YY', ' '], ['D Do DD', ' '], ['d do dddd ddd dd', ' '], ['DDD DDDo DDDD', ' '], ['w wo ww', ' '], ['h hh', ' '], ['H HH', ' '], ['m mm', ' '], ['s ss', ' '], ['a A', 'pm PM'], ['[] DDDo []', ' '], ['LTS', '::'], ['L', '//'], ['LL', ' '], ['LLL', ' :'], ['LLLL', ' :'], ['l', '//'], ['ll', ' '], ['lll', ' :'], ['llll', ' :'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 2]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 3]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 4]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 5]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 6]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 7]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 8]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 9]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 10]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 11]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 12]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 13]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 14]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 15]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 16]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 17]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 18]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 19]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 20]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 21]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 22]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 23]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 24]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 25]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 26]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 27]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 28]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 29]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 30]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 31]).format('DDDo'), '', ''); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({ s: 44 }), true), '.', ' . = .'); assert.equal(start.from(moment([2007, 1, 28]).add({ s: 45 }), true), '', ' . = '); assert.equal(start.from(moment([2007, 1, 28]).add({ s: 89 }), true), '', ' . = '); assert.equal(start.from(moment([2007, 1, 28]).add({ s: 90 }), true), ' ', ' . = '); assert.equal(start.from(moment([2007, 1, 28]).add({ m: 44 }), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ m: 45 }), true), '', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ m: 89 }), true), '', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ m: 90 }), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ h: 5 }), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ h: 21 }), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ h: 22 }), true), '', ' ='); assert.equal(start.from(moment([2007, 1, 28]).add({ h: 35 }), true), '', ' ='); assert.equal(start.from(moment([2007, 1, 28]).add({ h: 36 }), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 1 }), true), '', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 5 }), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 25 }), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 26 }), true), '', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 30 }), true), '', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 43 }), true), '', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 46 }), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 74 }), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 76 }), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ M: 1 }), true), '', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ M: 5 }), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 345 }), true), '', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ d: 548 }), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ y: 1 }), true), '', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({ y: 5 }), true), ' ', ' = '); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' . ', 'prefix'); assert.equal(moment(0).from(30000), ' . ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' . ', ' '); }); test('fromNow', function (assert) { assert.equal(moment().add({ s: 30 }).fromNow(), ' . ', ' . '); assert.equal(moment().add({ d: 5 }).fromNow(), ' ', ' '); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), '. : ', '. '); assert.equal(moment(a).add({m: 25}).calendar(), '. : ', ' '); assert.equal(moment(a).add({h: 1}).calendar(), '. : ', ' '); assert.equal(moment(a).add({d: 1}).calendar(), ' : ', ' '); assert.equal(moment(a).subtract({h: 1}).calendar(), '. : ', ' '); assert.equal(moment(a).subtract({d: 1}).calendar(), '. : ', '. '); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({ d: i }); assert.equal(m.calendar(), m.format('dddd LT []'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd LT []'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd LT []'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({ d: i }); assert.equal(m.calendar(), m.format('[] dddd LT []'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd LT []'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd LT []'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({ w: 1 }), weeksFromNow = moment().add({ w: 1 }); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), ' '); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), ' '); weeksAgo = moment().subtract({ w: 2 }); weeksFromNow = moment().add({ w: 2 }); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), ' '); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), ' '); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), ' ', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), ' ', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), ' ', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), ' ', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), ' ', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('nb'); test('parse', function (assert) { var tests = 'januar jan._februar feb._mars mars_april april_mai mai_juni juni_juli juli_august aug._september sep._oktober okt._november nov._desember des.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'sndag, februar 14. 2010, 3:25:50 pm'], ['ddd, hA', 's., 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 februar feb.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. sndag s. s'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[den] DDDo [dagen i ret]', 'den 45. dagen i ret'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14. februar 2010'], ['LLL', '14. februar 2010 kl. 15:25'], ['LLLL', 'sndag 14. februar 2010 kl. 15:25'], ['l', '14.2.2010'], ['ll', '14. feb. 2010'], ['lll', '14. feb. 2010 kl. 15:25'], ['llll', 's. 14. feb. 2010 kl. 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'januar jan._februar feb._mars mars_april april_mai mai_juni juni_juli juli_august aug._september sep._oktober okt._november nov._desember des.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'sndag s. s_mandag ma. ma_tirsdag ti. ti_onsdag on. on_torsdag to. to_fredag fr. fr_lrdag l. l'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'noen sekunder', '44 sekunder = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'ett minutt', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'ett minutt', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutter', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutter', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'en time', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'en time', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 timer', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 timer', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 timer', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'en dag', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'en dag', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dager', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'en dag', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dager', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dager', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'en mned', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'en mned', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'en mned', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mneder', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mneder', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mneder', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'en mned', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mneder', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'ett r', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 r', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'ett r', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 r', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'om noen sekunder', 'prefix'); assert.equal(moment(0).from(30000), 'noen sekunder siden', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'noen sekunder siden', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'om noen sekunder', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'om 5 dager', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'i dag kl. 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'i dag kl. 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'i dag kl. 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'i morgen kl. 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'i dag kl. 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'i gr kl. 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [kl.] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [kl.] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [kl.] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[forrige] dddd [kl.] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[forrige] dddd [kl.] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[forrige] dddd [kl.] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('ne'); test('parse', function (assert) { var tests = ' ._ ._ _ ._ _ _ ._ ._ ._ ._ ._ .'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, a h:mm:ss ', ', , :: '], ['ddd, a h ', '., '], ['M Mo MM MMMM MMM', ' .'], ['YYYY YY', ' '], ['D Do DD', ' '], ['d do dddd ddd dd', ' . .'], ['DDD DDDo DDDD', ' '], ['w wo ww', ' '], ['h hh', ' '], ['H HH', ' '], ['m mm', ' '], ['s ss', ' '], ['a A', ' '], ['LTS', ' :: '], ['L', '//'], ['LL', ' '], ['LLL', ' , : '], ['LLLL', ', , : '], ['l', '//'], ['ll', ' . '], ['lll', ' . , : '], ['llll', '., . , : '] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 2]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 3]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 4]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 5]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 6]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 7]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 8]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 9]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 10]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 11]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 12]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 13]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 14]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 15]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 16]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 17]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 18]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 19]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 20]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 21]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 22]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 23]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 24]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 25]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 26]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 27]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 28]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 29]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 30]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 31]).format('DDDo'), '', ''); }); test('format month', function (assert) { var expected = ' ._ ._ _ ._ _ _ ._ ._ ._ ._ ._ .'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' . ._ . ._ . ._ . ._ . ._ . ._ . .'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), ' ', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), ' ', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), ' ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), ' ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), ' ', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), ' ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), ' ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), ' ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), ' ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), ' ', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), ' ', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), ' ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), ' ', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), ' ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), ' ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), ' ', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), ' ', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), ' ', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), ' ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), ' ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), ' ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), ' ', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), ' ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), ' ', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), ' ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), ' ', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), ' ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', ' '); assert.equal(moment().add({d: 5}).fromNow(), ' ', ' '); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' : ', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' : ', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' : ', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' : ', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' : ', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' : ', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('meridiem', function (assert) { assert.equal(moment([2011, 2, 23, 2, 30]).format('a'), '', 'before dawn'); assert.equal(moment([2011, 2, 23, 9, 30]).format('a'), '', 'morning'); assert.equal(moment([2011, 2, 23, 14, 30]).format('a'), '', 'during day'); assert.equal(moment([2011, 2, 23, 17, 30]).format('a'), '', 'evening'); assert.equal(moment([2011, 2, 23, 19, 30]).format('a'), '', 'late evening'); assert.equal(moment([2011, 2, 23, 21, 20]).format('a'), '', 'night'); assert.equal(moment([2011, 2, 23, 2, 30]).format('A'), '', 'before dawn'); assert.equal(moment([2011, 2, 23, 9, 30]).format('A'), '', 'morning'); assert.equal(moment([2011, 2, 23, 14, 30]).format('A'), '', 'during day'); assert.equal(moment([2011, 2, 23, 17, 30]).format('A'), '', 'evening'); assert.equal(moment([2011, 2, 23, 19, 30]).format('A'), '', 'late evening'); assert.equal(moment([2011, 2, 23, 21, 20]).format('A'), '', 'night'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), ' ', 'Dec 26 2011 should be week 53'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), ' ', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), ' ', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), ' ', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), ' ', 'Jan 9 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('nl'); test('parse', function (assert) { var tests = 'januari jan._februari feb._maart mrt._april apr._mei mei._juni jun._juli jul._augustus aug._september sep._oktober okt._november nov._december dec.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, HH:mm:ss', 'zondag, februari 14de 2010, 15:25:50'], ['ddd, HH', 'zo., 15'], ['M Mo MM MMMM MMM', '2 2de 02 februari feb.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14de 14'], ['d do dddd ddd dd', '0 0de zondag zo. Zo'], ['DDD DDDo DDDD', '45 45ste 045'], ['w wo ww', '6 6de 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45ste day of the year'], ['LTS', '15:25:50'], ['L', '14-02-2010'], ['LL', '14 februari 2010'], ['LLL', '14 februari 2010 15:25'], ['LLLL', 'zondag 14 februari 2010 15:25'], ['l', '14-2-2010'], ['ll', '14 feb. 2010'], ['lll', '14 feb. 2010 15:25'], ['llll', 'zo. 14 feb. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1ste', '1ste'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2de', '2de'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3de', '3de'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4de', '4de'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5de', '5de'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6de', '6de'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7de', '7de'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8ste', '8ste'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9de', '9de'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10de', '10de'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11de', '11de'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12de', '12de'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13de', '13de'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14de', '14de'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15de', '15de'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16de', '16de'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17de', '17de'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18de', '18de'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19de', '19de'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20ste', '20ste'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21ste', '21ste'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22ste', '22ste'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23ste', '23ste'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24ste', '24ste'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25ste', '25ste'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26ste', '26ste'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27ste', '27ste'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28ste', '28ste'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29ste', '29ste'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30ste', '30ste'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31ste', '31ste'); }); test('format month', function (assert) { var expected = 'januari jan._februari feb._maart mrt._april apr._mei mei_juni jun._juli jul._augustus aug._september sep._oktober okt._november nov._december dec.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'zondag zo. Zo_maandag ma. Ma_dinsdag di. Di_woensdag wo. Wo_donderdag do. Do_vrijdag vr. Vr_zaterdag za. Za'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'een paar seconden', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'n minuut', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'n minuut', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minuten', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minuten', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'n uur', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'n uur', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 uur', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 uur', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 uur', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'n dag', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'n dag', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dagen', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'n dag', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dagen', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dagen', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'n maand', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'n maand', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'n maand', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 maanden', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 maanden', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 maanden', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'n maand', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 maanden', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'n jaar', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 jaar', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'n jaar', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 jaar', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'over een paar seconden', 'prefix'); assert.equal(moment(0).from(30000), 'een paar seconden geleden', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'een paar seconden geleden', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'over een paar seconden', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'over 5 dagen', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'vandaag om 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'vandaag om 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'vandaag om 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'morgen om 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'vandaag om 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'gisteren om 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [om] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [om] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [om] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[afgelopen] dddd [om] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[afgelopen] dddd [om] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[afgelopen] dddd [om] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('month abbreviation', function (assert) { assert.equal(moment([2012, 5, 23]).format('D-MMM-YYYY'), '23-jun-2012', 'format month abbreviation surrounded by dashes should not include a dot'); assert.equal(moment([2012, 5, 23]).format('D MMM YYYY'), '23 jun. 2012', 'format month abbreviation not surrounded by dashes should include a dot'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52ste', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1ste', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1ste', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2de', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2de', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('nn'); test('parse', function (assert) { var tests = 'januar jan_februar feb_mars mar_april apr_mai mai_juni jun_juli jul_august aug_september sep_oktober okt_november nov_desember des'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'sundag, februar 14. 2010, 3:25:50 pm'], ['ddd, hA', 'sun, 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 februar feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. sundag sun su'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14. februar 2010'], ['LLL', '14. februar 2010 kl. 15:25'], ['LLLL', 'sundag 14. februar 2010 kl. 15:25'], ['l', '14.2.2010'], ['ll', '14. feb 2010'], ['lll', '14. feb 2010 kl. 15:25'], ['llll', 'sun 14. feb 2010 kl. 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'januar jan_februar feb_mars mar_april apr_mai mai_juni jun_juli jul_august aug_september sep_oktober okt_november nov_desember des'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'sundag sun su_mndag mn m_tysdag tys ty_onsdag ons on_torsdag tor to_fredag fre fr_laurdag lau l'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'nokre sekund', '44 sekunder = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'eit minutt', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'eit minutt', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutt', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutt', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'ein time', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'ein time', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 timar', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 timar', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 timar', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'ein dag', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'ein dag', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dagar', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'ein dag', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dagar', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dagar', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'ein mnad', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'ein mnad', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'ein mnad', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mnader', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mnader', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mnader', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'ein mnad', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mnader', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'eit r', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 r', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'eit r', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 r', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'om nokre sekund', 'prefix'); assert.equal(moment(0).from(30000), 'nokre sekund sidan', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'nokre sekund sidan', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'om nokre sekund', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'om 5 dagar', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'I dag klokka 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'I dag klokka 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'I dag klokka 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'I morgon klokka 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'I dag klokka 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'I gr klokka 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [klokka] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [klokka] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [klokka] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[Fregande] dddd [klokka] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[Fregande] dddd [klokka] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[Fregande] dddd [klokka] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('pa-in'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, a h:mm:ss ', ', , :: '], ['ddd, a h ', ', '], ['M Mo MM MMMM MMM', ' '], ['YYYY YY', ' '], ['D Do DD', ' '], ['d do dddd ddd dd', ' '], ['DDD DDDo DDDD', ' '], ['w wo ww', ' '], ['h hh', ' '], ['H HH', ' '], ['m mm', ' '], ['s ss', ' '], ['a A', ' '], ['LTS', ' :: '], ['L', '//'], ['LL', ' '], ['LLL', ' , : '], ['LLLL', ', , : '], ['l', '//'], ['ll', ' '], ['lll', ' , : '], ['llll', ', , : '] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 2]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 3]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 4]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 5]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 6]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 7]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 8]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 9]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 10]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 11]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 12]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 13]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 14]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 15]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 16]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 17]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 18]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 19]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 20]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 21]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 22]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 23]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 24]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 25]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 26]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 27]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 28]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 29]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 30]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 31]).format('DDDo'), '', ''); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), ' ', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), ' ', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), ' ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), ' ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), ' ', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), ' ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), ' ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), ' ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), ' ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), ' ', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), ' ', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), ' ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), ' ', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), ' ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), ' ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), ' ', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), ' ', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), ' ', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), ' ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), ' ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), ' ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), ' ', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), ' ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), ' ', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), ' ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), ' ', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), ' ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', ' '); assert.equal(moment().add({d: 5}).fromNow(), ' ', ' '); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' : ', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' : ', 'Now plus 25 min'); assert.equal(moment(a).add({h: 3}).calendar(), ' : ', 'Now plus 3 hours'); assert.equal(moment(a).add({d: 1}).calendar(), ' : ', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' : ', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' : ', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('meridiem invariant', function (assert) { assert.equal(moment([2011, 2, 23, 2, 30]).format('a'), '', 'before dawn'); assert.equal(moment([2011, 2, 23, 9, 30]).format('a'), '', 'morning'); assert.equal(moment([2011, 2, 23, 14, 30]).format('a'), '', 'during day'); assert.equal(moment([2011, 2, 23, 17, 30]).format('a'), '', 'evening'); assert.equal(moment([2011, 2, 23, 19, 30]).format('a'), '', 'late evening'); assert.equal(moment([2011, 2, 23, 21, 20]).format('a'), '', 'night'); assert.equal(moment([2011, 2, 23, 2, 30]).format('A'), '', 'before dawn'); assert.equal(moment([2011, 2, 23, 9, 30]).format('A'), '', 'morning'); assert.equal(moment([2011, 2, 23, 14, 30]).format('A'), '', ' during day'); assert.equal(moment([2011, 2, 23, 17, 30]).format('A'), '', 'evening'); assert.equal(moment([2011, 2, 23, 19, 30]).format('A'), '', 'late evening'); assert.equal(moment([2011, 2, 23, 21, 20]).format('A'), '', 'night'); }); test('weeks year starting sunday', function (assert) { assert.equal(moment([2012, 0, 1]).week(), 1, 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).week(), 1, 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).week(), 2, 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).week(), 2, 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).week(), 3, 'Jan 15 2012 should be week 3'); }); test('weeks year starting monday', function (assert) { assert.equal(moment([2006, 11, 31]).week(), 1, 'Dec 31 2006 should be week 1'); assert.equal(moment([2007, 0, 1]).week(), 1, 'Jan 1 2007 should be week 1'); assert.equal(moment([2007, 0, 6]).week(), 1, 'Jan 6 2007 should be week 1'); assert.equal(moment([2007, 0, 7]).week(), 2, 'Jan 7 2007 should be week 2'); assert.equal(moment([2007, 0, 13]).week(), 2, 'Jan 13 2007 should be week 2'); assert.equal(moment([2007, 0, 14]).week(), 3, 'Jan 14 2007 should be week 3'); }); test('weeks year starting tuesday', function (assert) { assert.equal(moment([2007, 11, 29]).week(), 52, 'Dec 29 2007 should be week 52'); assert.equal(moment([2008, 0, 1]).week(), 1, 'Jan 1 2008 should be week 1'); assert.equal(moment([2008, 0, 5]).week(), 1, 'Jan 5 2008 should be week 1'); assert.equal(moment([2008, 0, 6]).week(), 2, 'Jan 6 2008 should be week 2'); assert.equal(moment([2008, 0, 12]).week(), 2, 'Jan 12 2008 should be week 2'); assert.equal(moment([2008, 0, 13]).week(), 3, 'Jan 13 2008 should be week 3'); }); test('weeks year starting wednesday', function (assert) { assert.equal(moment([2002, 11, 29]).week(), 1, 'Dec 29 2002 should be week 1'); assert.equal(moment([2003, 0, 1]).week(), 1, 'Jan 1 2003 should be week 1'); assert.equal(moment([2003, 0, 4]).week(), 1, 'Jan 4 2003 should be week 1'); assert.equal(moment([2003, 0, 5]).week(), 2, 'Jan 5 2003 should be week 2'); assert.equal(moment([2003, 0, 11]).week(), 2, 'Jan 11 2003 should be week 2'); assert.equal(moment([2003, 0, 12]).week(), 3, 'Jan 12 2003 should be week 3'); }); test('weeks year starting thursday', function (assert) { assert.equal(moment([2008, 11, 28]).week(), 1, 'Dec 28 2008 should be week 1'); assert.equal(moment([2009, 0, 1]).week(), 1, 'Jan 1 2009 should be week 1'); assert.equal(moment([2009, 0, 3]).week(), 1, 'Jan 3 2009 should be week 1'); assert.equal(moment([2009, 0, 4]).week(), 2, 'Jan 4 2009 should be week 2'); assert.equal(moment([2009, 0, 10]).week(), 2, 'Jan 10 2009 should be week 2'); assert.equal(moment([2009, 0, 11]).week(), 3, 'Jan 11 2009 should be week 3'); }); test('weeks year starting friday', function (assert) { assert.equal(moment([2009, 11, 27]).week(), 1, 'Dec 27 2009 should be week 1'); assert.equal(moment([2010, 0, 1]).week(), 1, 'Jan 1 2010 should be week 1'); assert.equal(moment([2010, 0, 2]).week(), 1, 'Jan 2 2010 should be week 1'); assert.equal(moment([2010, 0, 3]).week(), 2, 'Jan 3 2010 should be week 2'); assert.equal(moment([2010, 0, 9]).week(), 2, 'Jan 9 2010 should be week 2'); assert.equal(moment([2010, 0, 10]).week(), 3, 'Jan 10 2010 should be week 3'); }); test('weeks year starting saturday', function (assert) { assert.equal(moment([2010, 11, 26]).week(), 1, 'Dec 26 2010 should be week 1'); assert.equal(moment([2011, 0, 1]).week(), 1, 'Jan 1 2011 should be week 1'); assert.equal(moment([2011, 0, 2]).week(), 2, 'Jan 2 2011 should be week 2'); assert.equal(moment([2011, 0, 8]).week(), 2, 'Jan 8 2011 should be week 2'); assert.equal(moment([2011, 0, 9]).week(), 3, 'Jan 9 2011 should be week 3'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), ' ', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), ' ', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), ' ', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), ' ', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), ' ', 'Jan 15 2012 should be week 3'); }); test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('pl'); test('parse', function (assert) { var tests = 'stycze stycznia sty_luty lutego lut_marzec marca mar_kwiecie kwietnia kwi_maj maja maj_czerwiec czerwca cze_lipiec lipca lip_sierpie sierpnia sie_wrzesie wrzenia wrz_padziernik padziernika pa_listopad listopada lis_grudzie grudnia gru'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][2], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][2], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][2].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][2].toLocaleUpperCase(), 'MMMM', i); } }); test('parse strict', function (assert) { var tests = 'stycze stycznia sty_luty lutego lut_marzec marca mar_kwiecie kwietnia kwi_maj maja maj_czerwiec czerwca cze_lipiec lipca lip_sierpie sierpnia sie_wrzesie wrzenia wrz_padziernik padziernika pa_listopad listopada lis_grudzie grudnia gru'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm, true).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][2], 'MMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][2].toLocaleLowerCase(), 'MMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][2].toLocaleUpperCase(), 'MMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'niedziela, luty 14. 2010, 3:25:50 pm'], ['ddd, hA', 'nie, 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 luty lut'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. niedziela nie Nd'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14 lutego 2010'], ['LLL', '14 lutego 2010 15:25'], ['LLLL', 'niedziela, 14 lutego 2010 15:25'], ['l', '14.2.2010'], ['ll', '14 lut 2010'], ['lll', '14 lut 2010 15:25'], ['llll', 'nie, 14 lut 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'stycze sty_luty lut_marzec mar_kwiecie kwi_maj maj_czerwiec cze_lipiec lip_sierpie sie_wrzesie wrz_padziernik pa_listopad lis_grudzie gru'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'niedziela nie Nd_poniedziaek pon Pn_wtorek wt Wt_roda r r_czwartek czw Cz_pitek pt Pt_sobota sb So'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'kilka sekund', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'minuta', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'minuta', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minuty', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minuty', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'godzina', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'godzina', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 godziny', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 godzin', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 godzin', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '1 dzie', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '1 dzie', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dni', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '1 dzie', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dni', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dni', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'miesic', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'miesic', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'miesic', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 miesice', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 miesice', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 miesice', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'miesic', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 miesicy', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'rok', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 lata', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'rok', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 lat', '5 years = 5 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 112}), true), '112 lat', '112 years = 112 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 122}), true), '122 lata', '122 years = 122 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 213}), true), '213 lat', '213 years = 213 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 223}), true), '223 lata', '223 years = 223 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'za kilka sekund', 'prefix'); assert.equal(moment(0).from(30000), 'kilka sekund temu', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'kilka sekund temu', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'za kilka sekund', 'in a few seconds'); assert.equal(moment().add({h: 1}).fromNow(), 'za godzin', 'in an hour'); assert.equal(moment().add({d: 5}).fromNow(), 'za 5 dni', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Dzi o 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Dzi o 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Dzi o 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Jutro o 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Dzi o 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Wczoraj o 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('[W] dddd [o] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[W] dddd [o] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[W] dddd [o] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; function makeFormat(d) { switch (d.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 zeszy] dddd [o] LT'; } } for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('pt-br'); test('parse', function (assert) { var tests = 'janeiro jan_fevereiro fev_maro mar_abril abr_maio mai_junho jun_julho jul_agosto ago_setembro set_outubro out_novembro nov_dezembro dez'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Domingo, Fevereiro 14 2010, 3:25:50 pm'], ['ddd, hA', 'Dom, 3PM'], ['M Mo MM MMMM MMM', '2 2 02 Fevereiro Fev'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd', '0 0 Domingo Dom'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '8 8 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 de Fevereiro de 2010'], ['LLL', '14 de Fevereiro de 2010 s 15:25'], ['LLLL', 'Domingo, 14 de Fevereiro de 2010 s 15:25'], ['l', '14/2/2010'], ['ll', '14 de Fev de 2010'], ['lll', '14 de Fev de 2010 s 15:25'], ['llll', 'Dom, 14 de Fev de 2010 s 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = 'Janeiro Jan_Fevereiro Fev_Maro Mar_Abril Abr_Maio Mai_Junho Jun_Julho Jul_Agosto Ago_Setembro Set_Outubro Out_Novembro Nov_Dezembro Dez'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Domingo Dom_Segunda-feira Seg_Tera-feira Ter_Quarta-feira Qua_Quinta-feira Qui_Sexta-feira Sex_Sbado Sb'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'poucos segundos', '44 seconds = seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'um minuto', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'um minuto', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutos', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutos', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'uma hora', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'uma hora', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 horas', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 horas', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 horas', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'um dia', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'um dia', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dias', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'um dia', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dias', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dias', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'um ms', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'um ms', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'um ms', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 meses', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 meses', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 meses', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'um ms', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 meses', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'um ano', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 anos', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'um ano', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 anos', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'em poucos segundos', 'prefix'); assert.equal(moment(0).from(30000), 'poucos segundos atrs', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'em poucos segundos', 'in seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'em 5 dias', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Hoje s 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Hoje s 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Hoje s 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Amanh s 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Hoje s 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Ontem s 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [s] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [s] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [s] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format((m.day() === 0 || m.day() === 6) ? '[ltimo] dddd [s] LT' : '[ltima] dddd [s] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format((m.day() === 0 || m.day() === 6) ? '[ltimo] dddd [s] LT' : '[ltima] dddd [s] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format((m.day() === 0 || m.day() === 6) ? '[ltimo] dddd [s] LT' : '[ltima] dddd [s] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday format', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('pt'); test('parse', function (assert) { var tests = 'Janeiro Jan_Fevereiro Fev_Maro Mar_Abril Abr_Maio Mai_Junho Jun_Julho Jul_Agosto Ago_Setembro Set_Outubro Out_Novembro Nov_Dezembro Dez'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Domingo, Fevereiro 14 2010, 3:25:50 pm'], ['ddd, hA', 'Dom, 3PM'], ['M Mo MM MMMM MMM', '2 2 02 Fevereiro Fev'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd', '0 0 Domingo Dom'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '6 6 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 de Fevereiro de 2010'], ['LLL', '14 de Fevereiro de 2010 15:25'], ['LLLL', 'Domingo, 14 de Fevereiro de 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 de Fev de 2010'], ['lll', '14 de Fev de 2010 15:25'], ['llll', 'Dom, 14 de Fev de 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = 'Janeiro Jan_Fevereiro Fev_Maro Mar_Abril Abr_Maio Mai_Junho Jun_Julho Jul_Agosto Ago_Setembro Set_Outubro Out_Novembro Nov_Dezembro Dez'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Domingo Dom Dom_Segunda-Feira Seg 2_Tera-Feira Ter 3_Quarta-Feira Qua 4_Quinta-Feira Qui 5_Sexta-Feira Sex 6_Sbado Sb Sb'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'segundos', '44 seconds = seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'um minuto', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'um minuto', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minutos', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minutos', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'uma hora', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'uma hora', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 horas', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 horas', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 horas', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'um dia', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'um dia', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dias', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'um dia', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dias', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dias', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'um ms', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'um ms', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'um ms', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 meses', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 meses', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 meses', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'um ms', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 meses', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'um ano', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 anos', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'um ano', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 anos', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'em segundos', 'prefix'); assert.equal(moment(0).from(30000), 'h segundos', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'em segundos', 'in seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'em 5 dias', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Hoje s 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Hoje s 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Hoje s 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Amanh s 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Hoje s 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Ontem s 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [s] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [s] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [s] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format((m.day() === 0 || m.day() === 6) ? '[ltimo] dddd [s] LT' : '[ltima] dddd [s] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format((m.day() === 0 || m.day() === 6) ? '[ltimo] dddd [s] LT' : '[ltima] dddd [s] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format((m.day() === 0 || m.day() === 6) ? '[ltimo] dddd [s] LT' : '[ltima] dddd [s] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('ro'); test('parse', function (assert) { var tests = 'ianuarie ian._februarie febr._martie mart._aprilie apr._mai mai_iunie iun._iulie iul._august aug._septembrie sept._octombrie oct._noiembrie nov._decembrie dec.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss A', 'duminic, februarie 14 2010, 3:25:50 PM'], ['ddd, hA', 'Dum, 3PM'], ['M Mo MM MMMM MMM', '2 2 02 februarie febr.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 duminic Dum Du'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '7 7 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[a] DDDo[a zi a anului]', 'a 45a zi a anului'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14 februarie 2010'], ['LLL', '14 februarie 2010 15:25'], ['LLLL', 'duminic, 14 februarie 2010 15:25'], ['l', '14.2.2010'], ['ll', '14 febr. 2010'], ['lll', '14 febr. 2010 15:25'], ['llll', 'Dum, 14 febr. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = 'ianuarie ian._februarie febr._martie mart._aprilie apr._mai mai_iunie iun._iulie iul._august aug._septembrie sept._octombrie oct._noiembrie nov._decembrie dec.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'duminic Dum Du_luni Lun Lu_mari Mar Ma_miercuri Mie Mi_joi Joi Jo_vineri Vin Vi_smbt Sm S'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'cteva secunde', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'un minut', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'un minut', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minute', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 de minute', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'o or', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'o or', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ore', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ore', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 de ore', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'o zi', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'o zi', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 zile', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'o zi', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 zile', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 de zile', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'o lun', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'o lun', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'o lun', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 luni', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 luni', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 luni', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'o lun', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 luni', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'un an', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ani', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'un an', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ani', '5 years = 5 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 19}), true), '19 ani', '19 years = 19 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 20}), true), '20 de ani', '20 years = 20 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 100}), true), '100 de ani', '100 years = 100 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 101}), true), '101 ani', '101 years = 101 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 119}), true), '119 ani', '119 years = 119 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 120}), true), '120 de ani', '120 years = 120 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 219}), true), '219 ani', '219 years = 219 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 220}), true), '220 de ani', '220 years = 220 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'peste cteva secunde', 'prefix'); assert.equal(moment(0).from(30000), 'cteva secunde n urm', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'cteva secunde n urm', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'peste cteva secunde', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'peste 5 zile', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'azi la 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'azi la 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'azi la 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'mine la 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'azi la 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'ieri la 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [la] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [la] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [la] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[fosta] dddd [la] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[fosta] dddd [la] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[fosta] dddd [la] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('ru'); test('parse', function (assert) { var tests = ' ._ ._ _ ._ _ _ _ ._ ._ ._ ._ .'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } function equalTestStrict(input, mmm, monthIndex) { assert.equal(moment(input, mmm, true).month(), monthIndex, input + ' ' + mmm + ' should be strict month ' + (monthIndex + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); equalTestStrict(tests[i][1], 'MMM', i); equalTestStrict(tests[i][0], 'MMMM', i); equalTestStrict(tests[i][1].toLocaleLowerCase(), 'MMM', i); equalTestStrict(tests[i][1].toLocaleUpperCase(), 'MMM', i); equalTestStrict(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTestStrict(tests[i][0].toLocaleUpperCase(), 'MMMM', i); } }); test('parse exceptional case', function (assert) { assert.equal(moment('11 1989', ['DD MMMM YYYY']).format('DD-MM-YYYY'), '11-05-1989'); }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, HH:mm:ss', ', 14- 2010, 15:25:50'], ['ddd, h A', ', 3 '], ['M Mo MM MMMM MMM', '2 2- 02 .'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14- 14'], ['d do dddd ddd dd', '0 0- '], ['DDD DDDo DDDD', '45 45- 045'], ['w wo ww', '7 7- 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', ' '], ['DDDo [ ]', '45- '], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14 2010 .'], ['LLL', '14 2010 ., 15:25'], ['LLLL', ', 14 2010 ., 15:25'], ['l', '14.2.2010'], ['ll', '14 . 2010 .'], ['lll', '14 . 2010 ., 15:25'], ['llll', ', 14 . 2010 ., 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format meridiem', function (assert) { assert.equal(moment([2012, 11, 28, 0, 0]).format('A'), '', 'night'); assert.equal(moment([2012, 11, 28, 3, 59]).format('A'), '', 'night'); assert.equal(moment([2012, 11, 28, 4, 0]).format('A'), '', 'morning'); assert.equal(moment([2012, 11, 28, 11, 59]).format('A'), '', 'morning'); assert.equal(moment([2012, 11, 28, 12, 0]).format('A'), '', 'afternoon'); assert.equal(moment([2012, 11, 28, 16, 59]).format('A'), '', 'afternoon'); assert.equal(moment([2012, 11, 28, 17, 0]).format('A'), '', 'evening'); assert.equal(moment([2012, 11, 28, 23, 59]).format('A'), '', 'evening'); }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1-', '1-'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2-', '2-'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3-', '3-'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4-', '4-'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5-', '5-'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6-', '6-'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7-', '7-'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8-', '8-'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9-', '9-'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10-', '10-'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11-', '11-'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12-', '12-'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13-', '13-'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14-', '14-'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15-', '15-'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16-', '16-'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17-', '17-'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18-', '18-'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19-', '19-'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20-', '20-'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21-', '21-'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22-', '22-'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23-', '23-'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24-', '24-'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25-', '25-'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26-', '26-'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27-', '27-'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28-', '28-'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29-', '29-'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30-', '30-'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31-', '31-'); }); test('format month', function (assert) { var expected = ' ._ ._ _ ._ _ _ _ ._ ._ ._ ._ .'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format month case', function (assert) { var months = { 'nominative': '___________'.split('_'), 'accusative': '___________'.split('_') }, i; for (i = 0; i < 12; i++) { assert.equal(moment([2011, i, 1]).format('D MMMM'), '1 ' + months.accusative[i], '1 ' + months.accusative[i]); assert.equal(moment([2011, i, 1]).format('MMMM'), months.nominative[i], '1 ' + months.nominative[i]); } }); test('format month short case', function (assert) { var monthsShort = { 'nominative': '._.__.____._._._._.'.split('_'), 'accusative': '._._._.____._._._._.'.split('_') }, i; for (i = 0; i < 12; i++) { assert.equal(moment([2011, i, 1]).format('D MMM'), '1 ' + monthsShort.accusative[i], '1 ' + monthsShort.accusative[i]); assert.equal(moment([2011, i, 1]).format('MMM'), monthsShort.nominative[i], '1 ' + monthsShort.nominative[i]); } }); test('format month case with escaped symbols', function (assert) { var months = { 'nominative': '___________'.split('_'), 'accusative': '___________'.split('_') }, i; for (i = 0; i < 12; i++) { assert.equal(moment([2013, i, 1]).format('D[] MMMM'), '1 ' + months.accusative[i], '1 ' + months.accusative[i]); assert.equal(moment([2013, i, 1]).format('[<i>]D[</i>] [<b>]MMMM[</b>]'), '<i>1</i> <b>' + months.accusative[i] + '</b>', '1 <b>' + months.accusative[i] + '</b>'); assert.equal(moment([2013, i, 1]).format('D[- ] MMMM'), '1- ' + months.accusative[i], '1- ' + months.accusative[i]); assert.equal(moment([2013, i, 1]).format('D, MMMM'), '1, ' + months.nominative[i], '1, ' + months.nominative[i]); } }); test('format month short case with escaped symbols', function (assert) { var monthsShort = { 'nominative': '._.__.____._._._._.'.split('_'), 'accusative': '._._._.____._._._._.'.split('_') }, i; for (i = 0; i < 12; i++) { assert.equal(moment([2013, i, 1]).format('D[] MMM'), '1 ' + monthsShort.accusative[i], '1 ' + monthsShort.accusative[i]); assert.equal(moment([2013, i, 1]).format('[<i>]D[</i>] [<b>]MMM[</b>]'), '<i>1</i> <b>' + monthsShort.accusative[i] + '</b>', '1 <b>' + monthsShort.accusative[i] + '</b>'); assert.equal(moment([2013, i, 1]).format('D[- ] MMM'), '1- ' + monthsShort.accusative[i], '1- ' + monthsShort.accusative[i]); assert.equal(moment([2013, i, 1]).format('D, MMM'), '1, ' + monthsShort.nominative[i], '1, ' + monthsShort.nominative[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 31}), true), '31 ', '31 minutes = 31 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 11}), true), '11 ', '11 days = 11 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 21}), true), '21 ', '21 days = 21 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' 5 ', 'in 5 days'); assert.equal(moment().add({m: 31}).fromNow(), ' 31 ', 'in 31 minutes = in 31 minutes'); assert.equal(moment().subtract({m: 31}).fromNow(), '31 ', '31 minutes ago = 31 minutes ago'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m, now; function makeFormatNext(d) { switch (d.day()) { case 0: return '[ ] dddd [] LT'; case 1: case 2: case 4: return '[ ] dddd [] LT'; case 3: case 5: case 6: return '[ ] dddd [] LT'; } } function makeFormatThis(d) { if (d.day() === 2) { return '[] dddd [] LT'; } else { return '[] dddd [] LT'; } } now = moment().startOf('week'); for (i = 2; i < 7; i++) { m = moment(now).add({d: i}); assert.equal(m.calendar(now), m.format(makeFormatThis(m)), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(now), m.format(makeFormatThis(m)), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(now), m.format(makeFormatThis(m)), 'Today + ' + i + ' days end of day'); } now = moment().endOf('week'); for (i = 2; i < 7; i++) { m = moment(now).add({d: i}); assert.equal(m.calendar(now), m.format(makeFormatNext(m)), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(now), m.format(makeFormatNext(m)), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(now), m.format(makeFormatNext(m)), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m, now; function makeFormatLast(d) { switch (d.day()) { case 0: return '[ ] dddd [] LT'; case 1: case 2: case 4: return '[ ] dddd [] LT'; case 3: case 5: case 6: return '[ ] dddd [] LT'; } } function makeFormatThis(d) { if (d.day() === 2) { return '[] dddd [] LT'; } else { return '[] dddd [] LT'; } } now = moment().startOf('week'); for (i = 2; i < 7; i++) { m = moment(now).subtract({d: i}); assert.equal(m.calendar(now), m.format(makeFormatLast(m)), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(now), m.format(makeFormatLast(m)), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(now), m.format(makeFormatLast(m)), 'Today - ' + i + ' days end of day'); } now = moment().endOf('week'); for (i = 2; i < 7; i++) { m = moment(now).subtract({d: i}); assert.equal(m.calendar(now), m.format(makeFormatThis(m)), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(now), m.format(makeFormatThis(m)), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(now), m.format(makeFormatThis(m)), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1-', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1-', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2-', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2-', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('se'); test('parse', function (assert) { var i, tests = 'oajagemnnu oj_guovvamnnu guov_njukamnnu njuk_cuoomnnu cuo_miessemnnu mies_geassemnnu geas_suoidnemnnu suoi_borgemnnu borg_akamnnu ak_golggotmnnu golg_skbmamnnu skb_juovlamnnu juov'.split('_'); function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'sotnabeaivi, guovvamnnu 14. 2010, 3:25:50 pm'], ['ddd, hA', 'sotn, 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 guovvamnnu guov'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. sotnabeaivi sotn s'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[jagi] DDDo [beaivi]', 'jagi 45. beaivi'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', 'guovvamnnu 14. b. 2010'], ['LLL', 'guovvamnnu 14. b. 2010 ti. 15:25'], ['LLLL', 'sotnabeaivi, guovvamnnu 14. b. 2010 ti. 15:25'], ['l', '14.2.2010'], ['ll', 'guov 14. b. 2010'], ['lll', 'guov 14. b. 2010 ti. 15:25'], ['llll', 'sotn, guov 14. b. 2010 ti. 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var i, expected = 'oajagemnnu oj_guovvamnnu guov_njukamnnu njuk_cuoomnnu cuo_miessemnnu mies_geassemnnu geas_suoidnemnnu suoi_borgemnnu borg_akamnnu ak_golggotmnnu golg_skbmamnnu skb_juovlamnnu juov'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var i, expected = 'sotnabeaivi sotn s_vuossrga vuos v_maebrga ma m_gaskavahkku gask g_duorastat duor d_bearjadat bear b_lvvardat lv L'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'moadde sekunddat', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'okta minuhta', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'okta minuhta', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minuhtat', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minuhtat', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'okta diimmu', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'okta diimmu', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 diimmut', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 diimmut', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 diimmut', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'okta beaivi', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'okta beaivi', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 beaivvit', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'okta beaivi', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 beaivvit', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 beaivvit', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'okta mnnu', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'okta mnnu', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'okta mnnu', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mnut', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mnut', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mnut', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'okta mnnu', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mnut', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'okta jahki', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 jagit', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'okta jahki', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 jagit', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'moadde sekunddat geaes', 'prefix'); assert.equal(moment(0).from(30000), 'mait moadde sekunddat', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'mait moadde sekunddat', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'moadde sekunddat geaes', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), '5 beaivvit geaes', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'otne ti 12:00', 'Today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'otne ti 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'otne ti 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'ihttin ti 12:00', 'Tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'otne ti 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'ikte ti 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [ti] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [ti] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [ti] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[ovddit] dddd [ti] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[ovddit] dddd [ti] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[ovddit] dddd [ti] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('si'); /*jshint -W100*/ test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['YYYY MMMM Do dddd, a h:mm:ss', '2010 14 , .. 3:25:50'], ['YYYY MMMM Do dddd, a h:mm:ss', '2010 14 , .. 3:25:50'], ['ddd, A h', ', 3'], ['M Mo MM MMMM MMM', '2 2 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45 045'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', '.. '], ['[] DDDo []', ' 45 '], ['LTS', '.. 3:25:50'], ['LT', '.. 3:25'], ['L', '2010/02/14'], ['LL', '2010 14'], ['LLL', '2010 14, .. 3:25'], ['LLLL', '2010 14 , .. 3:25:50'], ['l', '2010/2/14'], ['ll', '2010 14'], ['lll', '2010 14, .. 3:25'], ['llll', '2010 14 , .. 3:25:50'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1 ', '1 '); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2 ', '2 '); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3 ', '3 '); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4 ', '4 '); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5 ', '5 '); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6 ', '6 '); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7 ', '7 '); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8 ', '8 '); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9 ', '9 '); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10 ', '10 '); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11 ', '11 '); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12 ', '12 '); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13 ', '13 '); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14 ', '14 '); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15 ', '15 '); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16 ', '16 '); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17 ', '17 '); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18 ', '18 '); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19 ', '19 '); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20 ', '20 '); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21 ', '21 '); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22 ', '22 '); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23 ', '23 '); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24 ', '24 '); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25 ', '25 '); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26 ', '26 '); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27 ', '27 '); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28 ', '28 '); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29 ', '29 '); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30 ', '30 '); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31 ', '31 '); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), ' 2', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), ' 44', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), ' 2', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), ' 5', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), ' 21', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), ' 2', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), ' 5', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), ' 25', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), ' 2', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), ' 2', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), ' 3', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), ' 5', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), ' 2', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), ' 5', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' 5', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' .. 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' .. 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' .. 1:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' .. 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' .. 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' .. 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd LT[]'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd LT[]'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd LT[]'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[] dddd LT[]'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd LT[]'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd LT[]'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('sk'); test('parse', function (assert) { var tests = 'janur jan._februr feb._marec mar._aprl apr._mj mj_jn jn._jl jl._august aug._september sep._oktber okt._november nov._december dec.'.split('_'), i; function equalTest(input, mmm, monthIndex) { assert.equal(moment(input, mmm).month(), monthIndex, input + ' should be month ' + (monthIndex + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss', 'nedea, februr 14. 2010, 3:25:50'], ['ddd, h', 'ne, 3'], ['M Mo MM MMMM MMM', '2 2. 02 februr feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. nedea ne ne'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['DDDo [de v roku]', '45. de v roku'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14. februr 2010'], ['LLL', '14. februr 2010 15:25'], ['LLLL', 'nedea 14. februr 2010 15:25'], ['l', '14.2.2010'], ['ll', '14. feb 2010'], ['lll', '14. feb 2010 15:25'], ['llll', 'ne 14. feb 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'janur jan_februr feb_marec mar_aprl apr_mj mj_jn jn_jl jl_august aug_september sep_oktber okt_november nov_december dec'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'nedea ne ne_pondelok po po_utorok ut ut_streda st st_tvrtok t t_piatok pi pi_sobota so so'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'pr seknd', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'minta', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'minta', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minty', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 mint', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'hodina', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'hodina', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 hodiny', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 hodn', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 hodn', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'de', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'de', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dni', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'de', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dn', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dn', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'mesiac', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'mesiac', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'mesiac', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mesiace', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mesiace', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mesiace', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'mesiac', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mesiacov', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'rok', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 roky', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'rok', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 rokov', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'za pr seknd', 'prefix'); assert.equal(moment(0).from(30000), 'pred pr sekundami', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'pred pr sekundami', 'now from now should display as in the past'); }); test('fromNow (future)', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'za pr seknd', 'in a few seconds'); assert.equal(moment().add({m: 1}).fromNow(), 'za mintu', 'in a minute'); assert.equal(moment().add({m: 3}).fromNow(), 'za 3 minty', 'in 3 minutes'); assert.equal(moment().add({m: 10}).fromNow(), 'za 10 mint', 'in 10 minutes'); assert.equal(moment().add({h: 1}).fromNow(), 'za hodinu', 'in an hour'); assert.equal(moment().add({h: 3}).fromNow(), 'za 3 hodiny', 'in 3 hours'); assert.equal(moment().add({h: 10}).fromNow(), 'za 10 hodn', 'in 10 hours'); assert.equal(moment().add({d: 1}).fromNow(), 'za de', 'in a day'); assert.equal(moment().add({d: 3}).fromNow(), 'za 3 dni', 'in 3 days'); assert.equal(moment().add({d: 10}).fromNow(), 'za 10 dn', 'in 10 days'); assert.equal(moment().add({M: 1}).fromNow(), 'za mesiac', 'in a month'); assert.equal(moment().add({M: 3}).fromNow(), 'za 3 mesiace', 'in 3 months'); assert.equal(moment().add({M: 10}).fromNow(), 'za 10 mesiacov', 'in 10 months'); assert.equal(moment().add({y: 1}).fromNow(), 'za rok', 'in a year'); assert.equal(moment().add({y: 3}).fromNow(), 'za 3 roky', 'in 3 years'); assert.equal(moment().add({y: 10}).fromNow(), 'za 10 rokov', 'in 10 years'); }); test('fromNow (past)', function (assert) { assert.equal(moment().subtract({s: 30}).fromNow(), 'pred pr sekundami', 'a few seconds ago'); assert.equal(moment().subtract({m: 1}).fromNow(), 'pred mintou', 'a minute ago'); assert.equal(moment().subtract({m: 3}).fromNow(), 'pred 3 mintami', '3 minutes ago'); assert.equal(moment().subtract({m: 10}).fromNow(), 'pred 10 mintami', '10 minutes ago'); assert.equal(moment().subtract({h: 1}).fromNow(), 'pred hodinou', 'an hour ago'); assert.equal(moment().subtract({h: 3}).fromNow(), 'pred 3 hodinami', '3 hours ago'); assert.equal(moment().subtract({h: 10}).fromNow(), 'pred 10 hodinami', '10 hours ago'); assert.equal(moment().subtract({d: 1}).fromNow(), 'pred dom', 'a day ago'); assert.equal(moment().subtract({d: 3}).fromNow(), 'pred 3 dami', '3 days ago'); assert.equal(moment().subtract({d: 10}).fromNow(), 'pred 10 dami', '10 days ago'); assert.equal(moment().subtract({M: 1}).fromNow(), 'pred mesiacom', 'a month ago'); assert.equal(moment().subtract({M: 3}).fromNow(), 'pred 3 mesiacmi', '3 months ago'); assert.equal(moment().subtract({M: 10}).fromNow(), 'pred 10 mesiacmi', '10 months ago'); assert.equal(moment().subtract({y: 1}).fromNow(), 'pred rokom', 'a year ago'); assert.equal(moment().subtract({y: 3}).fromNow(), 'pred 3 rokmi', '3 years ago'); assert.equal(moment().subtract({y: 10}).fromNow(), 'pred 10 rokmi', '10 years ago'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'dnes o 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'dnes o 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'dnes o 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'zajtra o 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'dnes o 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'vera o 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m, nextDay; for (i = 2; i < 7; i++) { m = moment().add({d: i}); nextDay = ''; switch (m.day()) { case 0: nextDay = 'v nedeu'; break; case 1: nextDay = 'v pondelok'; break; case 2: nextDay = 'v utorok'; break; case 3: nextDay = 'v stredu'; break; case 4: nextDay = 'vo tvrtok'; break; case 5: nextDay = 'v piatok'; break; case 6: nextDay = 'v sobotu'; break; } assert.equal(m.calendar(), m.format('[' + nextDay + '] [o] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[' + nextDay + '] [o] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[' + nextDay + '] [o] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m, lastDay; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); lastDay = ''; switch (m.day()) { case 0: lastDay = 'minul nedeu'; break; case 1: lastDay = 'minul pondelok'; break; case 2: lastDay = 'minul utorok'; break; case 3: lastDay = 'minul stredu'; break; case 4: lastDay = 'minul tvrtok'; break; case 5: lastDay = 'minul piatok'; break; case 6: lastDay = 'minul sobotu'; break; } assert.equal(m.calendar(), m.format('[' + lastDay + '] [o] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[' + lastDay + '] [o] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[' + lastDay + '] [o] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('humanize duration', function (assert) { assert.equal(moment.duration(1, 'minutes').humanize(), 'minta', 'a minute (future)'); assert.equal(moment.duration(1, 'minutes').humanize(true), 'za mintu', 'in a minute'); assert.equal(moment.duration(-1, 'minutes').humanize(), 'minta', 'a minute (past)'); assert.equal(moment.duration(-1, 'minutes').humanize(true), 'pred mintou', 'a minute ago'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('sl'); test('parse', function (assert) { var tests = 'januar jan._februar feb._marec mar._april apr._maj maj_junij jun._julij jul._avgust avg._september sep._oktober okt._november nov._december dec.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, h:mm:ss a', 'nedelja, 14. februar 2010, 3:25:50 pm'], ['ddd, hA', 'ned., 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 februar feb.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. nedelja ned. ne'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '7 7. 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['LTS', '15:25:50'], ['L', '14. 02. 2010'], ['LL', '14. februar 2010'], ['LLL', '14. februar 2010 15:25'], ['LLLL', 'nedelja, 14. februar 2010 15:25'], ['l', '14. 2. 2010'], ['ll', '14. feb. 2010'], ['lll', '14. feb. 2010 15:25'], ['llll', 'ned., 14. feb. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'januar jan._februar feb._marec mar._april apr._maj maj._junij jun._julij jul._avgust avg._september sep._oktober okt._november nov._december dec.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'nedelja ned. ne_ponedeljek pon. po_torek tor. to_sreda sre. sr_etrtek et. e_petek pet. pe_sobota sob. so'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'nekaj sekund', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'ena minuta', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'ena minuta', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minuti', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minut', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'ena ura', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'ena ura', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 uri', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ur', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ur', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'en dan', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'en dan', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dni', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'en dan', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dni', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dni', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'en mesec', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'en mesec', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'en mesec', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 meseca', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 meseca', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mesece', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'en mesec', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mesecev', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'eno leto', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 leti', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'eno leto', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 let', '5 years = 5 years'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 1}), true), 'ena minuta', 'a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 2}), true), '2 minuti', '2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 3}), true), '3 minute', '3 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 4}), true), '4 minute', '4 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 5}), true), '5 minut', '5 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 1}), true), 'ena ura', 'an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 2}), true), '2 uri', '2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 3}), true), '3 ure', '3 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 4}), true), '4 ure', '4 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ur', '5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'en dan', 'a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 2}), true), '2 dni', '2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 3}), true), '3 dni', '3 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 4}), true), '4 dni', '4 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dni', '5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'en mesec', 'a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 2}), true), '2 meseca', '2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 3}), true), '3 mesece', '3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 4}), true), '4 mesece', '4 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mesecev', '5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'eno leto', 'a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 2}), true), '2 leti', '2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 3}), true), '3 leta', '3 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 4}), true), '4 leta', '4 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 let', '5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'ez nekaj sekund', 'prefix'); assert.equal(moment(0).from(30000), 'pred nekaj sekundami', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'pred nekaj sekundami', 'now from now should display as in the past'); }); test('fromNow (future)', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'ez nekaj sekund', 'in a few seconds'); assert.equal(moment().add({m: 1}).fromNow(), 'ez eno minuto', 'in a minute'); assert.equal(moment().add({m: 2}).fromNow(), 'ez 2 minuti', 'in 2 minutes'); assert.equal(moment().add({m: 3}).fromNow(), 'ez 3 minute', 'in 3 minutes'); assert.equal(moment().add({m: 4}).fromNow(), 'ez 4 minute', 'in 4 minutes'); assert.equal(moment().add({m: 5}).fromNow(), 'ez 5 minut', 'in 5 minutes'); assert.equal(moment().add({h: 1}).fromNow(), 'ez eno uro', 'in an hour'); assert.equal(moment().add({h: 2}).fromNow(), 'ez 2 uri', 'in 2 hours'); assert.equal(moment().add({h: 3}).fromNow(), 'ez 3 ure', 'in 3 hours'); assert.equal(moment().add({h: 4}).fromNow(), 'ez 4 ure', 'in 4 hours'); assert.equal(moment().add({h: 5}).fromNow(), 'ez 5 ur', 'in 5 hours'); assert.equal(moment().add({d: 1}).fromNow(), 'ez en dan', 'in a day'); assert.equal(moment().add({d: 2}).fromNow(), 'ez 2 dni', 'in 2 days'); assert.equal(moment().add({d: 3}).fromNow(), 'ez 3 dni', 'in 3 days'); assert.equal(moment().add({d: 4}).fromNow(), 'ez 4 dni', 'in 4 days'); assert.equal(moment().add({d: 5}).fromNow(), 'ez 5 dni', 'in 5 days'); assert.equal(moment().add({M: 1}).fromNow(), 'ez en mesec', 'in a month'); assert.equal(moment().add({M: 2}).fromNow(), 'ez 2 meseca', 'in 2 months'); assert.equal(moment().add({M: 3}).fromNow(), 'ez 3 mesece', 'in 3 months'); assert.equal(moment().add({M: 4}).fromNow(), 'ez 4 mesece', 'in 4 months'); assert.equal(moment().add({M: 5}).fromNow(), 'ez 5 mesecev', 'in 5 months'); assert.equal(moment().add({y: 1}).fromNow(), 'ez eno leto', 'in a year'); assert.equal(moment().add({y: 2}).fromNow(), 'ez 2 leti', 'in 2 years'); assert.equal(moment().add({y: 3}).fromNow(), 'ez 3 leta', 'in 3 years'); assert.equal(moment().add({y: 4}).fromNow(), 'ez 4 leta', 'in 4 years'); assert.equal(moment().add({y: 5}).fromNow(), 'ez 5 let', 'in 5 years'); assert.equal(moment().subtract({s: 30}).fromNow(), 'pred nekaj sekundami', 'a few seconds ago'); assert.equal(moment().subtract({m: 1}).fromNow(), 'pred eno minuto', 'a minute ago'); assert.equal(moment().subtract({m: 2}).fromNow(), 'pred 2 minutama', '2 minutes ago'); assert.equal(moment().subtract({m: 3}).fromNow(), 'pred 3 minutami', '3 minutes ago'); assert.equal(moment().subtract({m: 4}).fromNow(), 'pred 4 minutami', '4 minutes ago'); assert.equal(moment().subtract({m: 5}).fromNow(), 'pred 5 minutami', '5 minutes ago'); assert.equal(moment().subtract({h: 1}).fromNow(), 'pred eno uro', 'an hour ago'); assert.equal(moment().subtract({h: 2}).fromNow(), 'pred 2 urama', '2 hours ago'); assert.equal(moment().subtract({h: 3}).fromNow(), 'pred 3 urami', '3 hours ago'); assert.equal(moment().subtract({h: 4}).fromNow(), 'pred 4 urami', '4 hours ago'); assert.equal(moment().subtract({h: 5}).fromNow(), 'pred 5 urami', '5 hours ago'); assert.equal(moment().subtract({d: 1}).fromNow(), 'pred enim dnem', 'a day ago'); assert.equal(moment().subtract({d: 2}).fromNow(), 'pred 2 dnevoma', '2 days ago'); assert.equal(moment().subtract({d: 3}).fromNow(), 'pred 3 dnevi', '3 days ago'); assert.equal(moment().subtract({d: 4}).fromNow(), 'pred 4 dnevi', '4 days ago'); assert.equal(moment().subtract({d: 5}).fromNow(), 'pred 5 dnevi', '5 days ago'); assert.equal(moment().subtract({M: 1}).fromNow(), 'pred enim mesecem', 'a month ago'); assert.equal(moment().subtract({M: 2}).fromNow(), 'pred 2 mesecema', '2 months ago'); assert.equal(moment().subtract({M: 3}).fromNow(), 'pred 3 meseci', '3 months ago'); assert.equal(moment().subtract({M: 4}).fromNow(), 'pred 4 meseci', '4 months ago'); assert.equal(moment().subtract({M: 5}).fromNow(), 'pred 5 meseci', '5 months ago'); assert.equal(moment().subtract({y: 1}).fromNow(), 'pred enim letom', 'a year ago'); assert.equal(moment().subtract({y: 2}).fromNow(), 'pred 2 letoma', '2 years ago'); assert.equal(moment().subtract({y: 3}).fromNow(), 'pred 3 leti', '3 years ago'); assert.equal(moment().subtract({y: 4}).fromNow(), 'pred 4 leti', '4 years ago'); assert.equal(moment().subtract({y: 5}).fromNow(), 'pred 5 leti', '5 years ago'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'danes ob 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'danes ob 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'danes ob 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'jutri ob 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'danes ob 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'veraj ob 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; function makeFormat(d) { switch (d.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'; } } for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; function makeFormat(d) { switch (d.day()) { case 0: return '[prejnjo] [nedeljo] [ob] LT'; case 3: return '[prejnjo] [sredo] [ob] LT'; case 6: return '[prejnjo] [soboto] [ob] LT'; case 1: case 2: case 4: case 5: return '[prejnji] dddd [ob] LT'; } } for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1.', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1.', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2.', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2.', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3.', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('sq'); test('parse', function (assert) { var i, tests = 'Janar Jan_Shkurt Shk_Mars Mar_Prill Pri_Maj Maj_Qershor Qer_Korrik Kor_Gusht Gus_Shtator Sht_Tetor Tet_Nntor Nn_Dhjetor Dhj'.split('_'); function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, HH:mm:ss', 'E Diel, Shkurt 14. 2010, 15:25:50'], ['ddd, HH', 'Die, 15'], ['M Mo MM MMMM MMM', '2 2. 02 Shkurt Shk'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. E Diel Die D'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'MD MD'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 Shkurt 2010'], ['LLL', '14 Shkurt 2010 15:25'], ['LLLL', 'E Diel, 14 Shkurt 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 Shk 2010'], ['lll', '14 Shk 2010 15:25'], ['llll', 'Die, 14 Shk 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('meridiem', function (assert) { assert.equal(moment([2011, 2, 23, 0, 0]).format('A'), 'PD', 'before dawn'); assert.equal(moment([2011, 2, 23, 12, 0]).format('A'), 'MD', 'noon'); }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var i, expected = 'Janar Jan_Shkurt Shk_Mars Mar_Prill Pri_Maj Maj_Qershor Qer_Korrik Kor_Gusht Gus_Shtator Sht_Tetor Tet_Nntor Nn_Dhjetor Dhj'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var i, expected = 'E Diel Die D_E Hn Hn H_E Mart Mar Ma_E Mrkur Mr M_E Enjte Enj E_E Premte Pre P_E Shtun Sht Sh'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'disa sekonda', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'nj minut', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'nj minut', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minuta', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minuta', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'nj or', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'nj or', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 or', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 or', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 or', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'nj dit', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'nj dit', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dit', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'nj dit', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dit', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dit', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'nj muaj', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'nj muaj', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'nj muaj', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 muaj', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 muaj', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 muaj', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'nj muaj', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 muaj', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'nj vit', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 vite', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'nj vit', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 vite', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'n disa sekonda', 'prefix'); assert.equal(moment(0).from(30000), 'disa sekonda m par', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'disa sekonda m par', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'n disa sekonda', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'n 5 dit', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Sot n 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Sot n 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Sot n 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Nesr n 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Sot n 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Dje n 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [n] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [n] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [n] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [e kaluar n] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [e kaluar n] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [e kaluar n] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('sr-cyrl'); test('parse', function (assert) { var tests = ' ._ ._ ._ ._ _ _ _ ._ ._ ._ ._ .'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, h:mm:ss a', ', 14. 2010, 3:25:50 pm'], ['ddd, hA', '., 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 .'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. . '], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '7 7. 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['LTS', '15:25:50'], ['L', '14. 02. 2010'], ['LL', '14. 2010'], ['LLL', '14. 2010 15:25'], ['LLLL', ', 14. 2010 15:25'], ['l', '14. 2. 2010'], ['ll', '14. . 2010'], ['lll', '14. . 2010 15:25'], ['llll', '., 14. . 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = ' ._ ._ ._ ._ _ _ _ ._ ._ ._ ._ .'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' . _ . _ . _ . _ . _ . _ . '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), ' ', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), ' ', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), ' ', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), ' ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'prefix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' 5 ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; function makeFormat(d) { switch (d.day()) { case 0: return '[] [] [] LT'; case 3: return '[] [] [] LT'; case 6: return '[] [] [] LT'; case 1: case 2: case 4: case 5: return '[] dddd [] LT'; } } for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; function makeFormat(d) { var lastWeekDay = [ '[] [] [] LT', '[] [] [] LT', '[] [] [] LT', '[] [] [] LT', '[] [] [] LT', '[] [] [] LT', '[] [] [] LT' ]; return lastWeekDay[d.day()]; } for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1.', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1.', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2.', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2.', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3.', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('sr'); test('parse', function (assert) { var tests = 'januar jan._februar feb._mart mar._april apr._maj maj_jun jun_jul jul_avgust avg._septembar sep._oktobar okt._novembar nov._decembar dec.'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, h:mm:ss a', 'nedelja, 14. februar 2010, 3:25:50 pm'], ['ddd, hA', 'ned., 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 februar feb.'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. nedelja ned. ne'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '7 7. 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['LTS', '15:25:50'], ['L', '14. 02. 2010'], ['LL', '14. februar 2010'], ['LLL', '14. februar 2010 15:25'], ['LLLL', 'nedelja, 14. februar 2010 15:25'], ['l', '14. 2. 2010'], ['ll', '14. feb. 2010'], ['lll', '14. feb. 2010 15:25'], ['llll', 'ned., 14. feb. 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'januar jan._februar feb._mart mar._april apr._maj maj_jun jun_jul jul_avgust avg._septembar sep._oktobar okt._novembar nov._decembar dec.'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'nedelja ned. ne_ponedeljak pon. po_utorak uto. ut_sreda sre. sr_etvrtak et. e_petak pet. pe_subota sub. su'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'nekoliko sekundi', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'jedan minut', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'jedan minut', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minute', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minuta', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'jedan sat', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'jedan sat', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 sata', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 sati', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 sati', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'dan', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'dan', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dana', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'dan', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dana', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dana', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'mesec', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'mesec', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'mesec', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 meseca', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 meseca', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 meseca', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'mesec', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 meseci', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'godinu', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 godine', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'godinu', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 godina', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'za nekoliko sekundi', 'prefix'); assert.equal(moment(0).from(30000), 'pre nekoliko sekundi', 'prefix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'pre nekoliko sekundi', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'za nekoliko sekundi', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'za 5 dana', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'danas u 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'danas u 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'danas u 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'sutra u 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'danas u 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'jue u 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; function makeFormat(d) { switch (d.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'; } } for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; function makeFormat(d) { var lastWeekDay = [ '[prole] [nedelje] [u] LT', '[prolog] [ponedeljka] [u] LT', '[prolog] [utorka] [u] LT', '[prole] [srede] [u] LT', '[prolog] [etvrtka] [u] LT', '[prolog] [petka] [u] LT', '[prole] [subote] [u] LT' ]; return lastWeekDay[d.day()]; } for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1.', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1.', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2.', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2.', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3.', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('ss'); test('parse', function (assert) { var tests = "Bhimbidvwane Bhi_Indlovana Ina_Indlov'lenkhulu Inu_Mabasa Mab_Inkhwekhweti Ink_Inhlaba Inh_Kholwane Kho_Ingci Igc_Inyoni Iny_Imphala Imp_Lweti lwe_Ingongoni Igo".split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('parse meridiem', function (assert) { var i, b = moment(), meridiemTests = [ // h a patterns, expected hours, isValid ['10 ekuseni', 10, true], ['11 emini', 11, true], ['3 entsambama', 15, true], ['4 entsambama', 16, true], ['6 entsambama', 18, true], ['7 ebusuku', 19, true], ['12 ebusuku', 0, true], ['10 am', 10, false], ['10 pm', 10, false] ], parsed; // test that a formatted moment including meridiem string can be parsed back to the same moment assert.ok(b.isSame(moment(b.format('h:mm:ss a'), 'h:mm:ss a', 'ss', true), 'seconds'), b.format('h:mm:ss a') + ' should be equal to ' + moment(b.format('h:mm:ss a'), 'h:mm:ss a', 'ss', true).format('h:mm:ss a')); // test that a formatted moment having a meridiem string can be parsed with strict flag assert.ok(moment(b.format('h:mm:ss a'), 'h:mm:ss a', 'ss', true).isValid(), b.format('h:mm:ss a') + ' should be parsed as valid'); for (i = 0; i < meridiemTests.length; i++) { parsed = moment(meridiemTests[i][0], 'h a', 'ss', true); assert.equal(parsed.isValid(), meridiemTests[i][2], 'validity for ' + meridiemTests[i][0]); if (parsed.isValid()) { assert.equal(parsed.hours(), meridiemTests[i][1], 'hours for ' + meridiemTests[i][0]); } } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Lisontfo, Indlovana 14 2010, 3:25:50 entsambama'], ['ddd, h A', 'Lis, 3 entsambama'], ['M Mo MM MMMM MMM', '2 2 02 Indlovana Ina'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 Lisontfo Lis Li'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '6 6 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'entsambama entsambama'], ['[Lilanga] DDDo [lilanga lelinyaka]', 'Lilanga 45 lilanga lelinyaka'], ['LTS', '3:25:50 entsambama'], ['L', '14/02/2010'], ['LL', '14 Indlovana 2010'], ['LLL', '14 Indlovana 2010 3:25 entsambama'], ['LLLL', 'Lisontfo, 14 Indlovana 2010 3:25 entsambama'], ['l', '14/2/2010'], ['ll', '14 Ina 2010'], ['lll', '14 Ina 2010 3:25 entsambama'], ['llll', 'Lis, 14 Ina 2010 3:25 entsambama'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = "Bhimbidvwane Bhi_Indlovana Ina_Indlov'lenkhulu Inu_Mabasa Mab_Inkhwekhweti Ink_Inhlaba Inh_Kholwane Kho_Ingci Igc_Inyoni Iny_Imphala Imp_Lweti Lwe_Ingongoni Igo".split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Lisontfo Lis Li_Umsombuluko Umb Us_Lesibili Lsb Lb_Lesitsatfu Les Lt_Lesine Lsi Ls_Lesihlanu Lsh Lh_Umgcibelo Umg Ug'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'emizuzwana lomcane', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'umzuzu', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'umzuzu', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 emizuzu', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 emizuzu', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'lihora', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'lihora', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 emahora', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 emahora', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 emahora', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'lilanga', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'lilanga', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 emalanga', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'lilanga', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 emalanga', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 emalanga', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'inyanga', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'inyanga', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'inyanga', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 tinyanga', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 tinyanga', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 tinyanga', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'inyanga', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 tinyanga', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'umnyaka', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 iminyaka', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'umnyaka', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 iminyaka', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'nga emizuzwana lomcane', 'prefix'); assert.equal(moment(0).from(30000), 'wenteka nga emizuzwana lomcane', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'wenteka nga emizuzwana lomcane', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'nga emizuzwana lomcane', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'nga 5 emalanga', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Namuhla nga 12:00 emini', 'Today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Namuhla nga 12:25 emini', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Namuhla nga 1:00 emini', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Kusasa nga 12:00 emini', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Namuhla nga 11:00 emini', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Itolo nga 12:00 emini', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [nga] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [nga] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [nga] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [leliphelile] [nga] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [leliphelile] [nga] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [leliphelile] [nga] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1', 'Jan 4 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('sv'); test('parse', function (assert) { var tests = 'januari jan_februari feb_mars mar_april apr_maj maj_juni jun_juli jul_augusti aug_september sep_oktober okt_november nov_december dec'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'sndag, februari 14e 2010, 3:25:50 pm'], ['ddd, hA', 'sn, 3PM'], ['M Mo MM MMMM MMM', '2 2a 02 februari feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14e 14'], ['d do dddd ddd dd', '0 0e sndag sn s'], ['DDD DDDo DDDD', '45 45e 045'], ['w wo ww', '6 6e 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45e day of the year'], ['LTS', '15:25:50'], ['L', '2010-02-14'], ['LL', '14 februari 2010'], ['LLL', '14 februari 2010 kl. 15:25'], ['LLLL', 'sndag 14 februari 2010 kl. 15:25'], ['l', '2010-2-14'], ['ll', '14 feb 2010'], ['lll', '14 feb 2010 15:25'], ['llll', 'sn 14 feb 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1a', '1a'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2a', '2a'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3e', '3e'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4e', '4e'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5e', '5e'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6e', '6e'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7e', '7e'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8e', '8e'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9e', '9e'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10e', '10e'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11e', '11e'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12e', '12e'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13e', '13e'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14e', '14e'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15e', '15e'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16e', '16e'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17e', '17e'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18e', '18e'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19e', '19e'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20e', '20e'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21a', '21a'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22a', '22a'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23e', '23e'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24e', '24e'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25e', '25e'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26e', '26e'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27e', '27e'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28e', '28e'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29e', '29e'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30e', '30e'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31a', '31a'); }); test('format month', function (assert) { var expected = 'januari jan_februari feb_mars mar_april apr_maj maj_juni jun_juli jul_augusti aug_september sep_oktober okt_november nov_december dec'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'sndag sn s_mndag mn m_tisdag tis ti_onsdag ons on_torsdag tor to_fredag fre fr_lrdag lr l'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'ngra sekunder', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'en minut', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'en minut', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minuter', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minuter', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'en timme', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'en timme', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 timmar', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 timmar', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 timmar', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'en dag', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'en dag', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 dagar', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'en dag', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 dagar', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 dagar', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'en mnad', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'en mnad', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'en mnad', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mnader', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mnader', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mnader', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'en mnad', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mnader', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'ett r', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 r', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'ett r', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 r', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'om ngra sekunder', 'prefix'); assert.equal(moment(0).from(30000), 'fr ngra sekunder sedan', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'fr ngra sekunder sedan', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'om ngra sekunder', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'om 5 dagar', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Idag 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Idag 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Idag 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Imorgon 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Idag 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Igr 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('[P] dddd LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[P] dddd LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[P] dddd LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[I] dddd[s] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[I] dddd[s] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[I] dddd[s] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52a', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1a', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1a', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2a', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2a', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('sw'); test('parse', function (assert) { var tests = 'Januari Jan_Februari Feb_Machi Mac_Aprili Apr_Mei Mei_Juni Jun_Julai Jul_Agosti Ago_Septemba Sep_Oktoba Okt_Novemba Nov_Desemba Des'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Jumapili, Februari 14 2010, 3:25:50 pm'], ['ddd, hA', 'Jpl, 3PM'], ['M Mo MM MMMM MMM', '2 2 02 Februari Feb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 Jumapili Jpl J2'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '7 7 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[siku] DDDo [ya mwaka]', 'siku 45 ya mwaka'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14 Februari 2010'], ['LLL', '14 Februari 2010 15:25'], ['LLLL', 'Jumapili, 14 Februari 2010 15:25'], ['l', '14.2.2010'], ['ll', '14 Feb 2010'], ['lll', '14 Feb 2010 15:25'], ['llll', 'Jpl, 14 Feb 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = 'Januari Jan_Februari Feb_Machi Mac_Aprili Apr_Mei Mei_Juni Jun_Julai Jul_Agosti Ago_Septemba Sep_Oktoba Okt_Novemba Nov_Desemba Des'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Jumapili Jpl J2_Jumatatu Jtat J3_Jumanne Jnne J4_Jumatano Jtan J5_Alhamisi Alh Al_Ijumaa Ijm Ij_Jumamosi Jmos J1'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'hivi punde', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'dakika moja', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'dakika moja', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), 'dakika 2', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), 'dakika 44', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'saa limoja', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'saa limoja', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), 'masaa 2', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), 'masaa 5', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), 'masaa 21', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'siku moja', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'siku moja', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), 'masiku 2', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'siku moja', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), 'masiku 5', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), 'masiku 25', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'mwezi mmoja', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'mwezi mmoja', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'mwezi mmoja', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), 'miezi 2', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), 'miezi 2', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), 'miezi 3', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'mwezi mmoja', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), 'miezi 5', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'mwaka mmoja', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), 'miaka 2', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'mwaka mmoja', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), 'miaka 5', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'hivi punde baadaye', 'prefix'); assert.equal(moment(0).from(30000), 'tokea hivi punde', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'tokea hivi punde', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'hivi punde baadaye', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'masiku 5 baadaye', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'leo saa 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'leo saa 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'leo saa 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'kesho saa 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'leo saa 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'jana 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('[wiki ijayo] dddd [saat] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[wiki ijayo] dddd [saat] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[wiki ijayo] dddd [saat] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[wiki iliyopita] dddd [saat] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[wiki iliyopita] dddd [saat] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[wiki iliyopita] dddd [saat] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday format', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('ta'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', ', , :: '], ['ddd, hA', ', '], ['M Mo MM MMMM MMM', ' '], ['YYYY YY', ' '], ['D Do DD', ' '], ['d do dddd ddd dd', ' '], ['DDD DDDo DDDD', ' '], ['w wo ww', ' '], ['h hh', ' '], ['H HH', ' '], ['m mm', ' '], ['s ss', ' '], ['a A', ' '], ['[] DDDo []', ' '], ['LTS', '::'], ['L', '//'], ['LL', ' '], ['LLL', ' , :'], ['LLLL', ', , :'], ['l', '//'], ['ll', ' '], ['lll', ' , :'], ['llll', ', , :'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 2]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 3]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 4]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 5]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 6]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 7]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 8]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 9]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 10]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 11]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 12]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 13]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 14]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 15]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 16]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 17]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 18]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 19]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 20]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 21]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 22]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 23]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 24]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 25]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 26]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 27]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 28]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 29]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 30]).format('DDDo'), '', ''); assert.equal(moment([2011, 0, 31]).format('DDDo'), '', ''); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 = '); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), ' ', '45 = '); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), ' ', '89 = '); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), ' ', '90 = '); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), ' ', '44 = 44 '); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), ' ', '45 = '); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), ' ', '89 = '); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), ' ', '90 = '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), ' ', '5 = 5 '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), ' ', '5 = '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), ' ', '6 = days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), ' ', '5 = 5 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), ' ', '5 = 5 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), ' ', '6 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), ' ', '0 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), ' ', '45 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), ' ', '46 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), ' ', '75 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), ' ', '76 = '); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), ' ', '5 = 5 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), ' ', '45 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), ' ', '548 = '); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), ' ', '5 = 5 '); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', ' '); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', ' '); assert.equal(moment().add({d: 5}).fromNow(), ' ', '5 '); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' :', ' 12:00'); assert.equal(moment(a).add({m: 25}).calendar(), ' :', ' 12:25'); assert.equal(moment(a).add({h: 1}).calendar(), ' :', ' 13:00'); assert.equal(moment(a).add({d: 1}).calendar(), ' :', ' 12:00'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' :', ' 11:00'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' :', ' 12:00'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd, LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd, LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd, LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[ ] dddd, LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[ ] dddd, LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[ ] dddd, LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('meridiem', function (assert) { assert.equal(moment([2011, 2, 23, 0, 30]).format('a'), ' ', '(after) midnight'); assert.equal(moment([2011, 2, 23, 2, 30]).format('a'), ' ', 'before dawn'); assert.equal(moment([2011, 2, 23, 9, 30]).format('a'), ' ', 'morning'); assert.equal(moment([2011, 2, 23, 14, 30]).format('a'), ' ', 'during day'); assert.equal(moment([2011, 2, 23, 17, 30]).format('a'), ' ', 'evening'); assert.equal(moment([2011, 2, 23, 19, 30]).format('a'), ' ', 'late evening'); assert.equal(moment([2011, 2, 23, 23, 30]).format('a'), ' ', '(before) midnight'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('te'); test('parse', function (assert) { var tests = ' ._ ._ _ ._ _ _ _ ._ ._ ._ ._ .'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, a h:mm:ss', ', 14 2010, 3:25:50'], ['ddd, a h ', ', 3 '], ['M Mo MM MMMM MMM', '2 2 02 .'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '8 8 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', ' '], ['LTS', ' 3:25:50'], ['L', '14/02/2010'], ['LL', '14 2010'], ['LLL', '14 2010, 3:25'], ['LLLL', ', 14 2010, 3:25'], ['l', '14/2/2010'], ['ll', '14 . 2010'], ['lll', '14 . 2010, 3:25'], ['llll', ', 14 . 2010, 3:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = ' ._ ._ _ ._ _ _ _ ._ ._ ._ ._ .'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), ' ', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), ' ', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), ' ', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), ' ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), ' ', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), ' ', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), ' ', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), ' ', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), ' ', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), ' ', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), ' ', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), ' ', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), ' ', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', ' '); assert.equal(moment().add({d: 5}).fromNow(), '5 ', '5 '); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 3}).calendar(), ' 3:00', 'Now plus 3 hours'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd[,] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd[,] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('meridiem', function (assert) { assert.equal(moment([2011, 2, 23, 2, 30]).format('a'), '', 'before dawn'); assert.equal(moment([2011, 2, 23, 9, 30]).format('a'), '', 'morning'); assert.equal(moment([2011, 2, 23, 14, 30]).format('a'), '', 'during day'); assert.equal(moment([2011, 2, 23, 17, 30]).format('a'), '', 'evening'); assert.equal(moment([2011, 2, 23, 19, 30]).format('a'), '', 'late evening'); assert.equal(moment([2011, 2, 23, 21, 20]).format('a'), '', 'night'); assert.equal(moment([2011, 2, 23, 2, 30]).format('A'), '', 'before dawn'); assert.equal(moment([2011, 2, 23, 9, 30]).format('A'), '', 'morning'); assert.equal(moment([2011, 2, 23, 14, 30]).format('A'), '', ' during day'); assert.equal(moment([2011, 2, 23, 17, 30]).format('A'), '', 'evening'); assert.equal(moment([2011, 2, 23, 19, 30]).format('A'), '', 'late evening'); assert.equal(moment([2011, 2, 23, 21, 20]).format('A'), '', 'night'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('th'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, h:mm:ss a', ', 14 2010, 3:25:50 '], ['ddd, h A', ', 3 '], ['M Mo MM MMMM MMM', '2 2 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 .'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '8 8 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', ' '], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LTS', '15 25 50 '], ['L', '2010/02/14'], ['LL', '14 2010'], ['LLL', '14 2010 15 25 '], ['LLLL', ' 14 2010 15 25 '], ['l', '2010/2/14'], ['ll', '14 2010'], ['lll', '14 2010 15 25 '], ['llll', ' 14 2010 15 25 '] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' ._ ._ ._ ._ ._ ._ .'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), '', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '1 ', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '1 ', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '1 ', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '1 ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '1 ', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '1 ', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '1 ', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '1 ', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '1 ', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '1 ', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '1 ', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '1 ', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '1 ', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), '', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), '', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' 5 ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12 0 ', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12 25 ', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13 0 ', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12 0 ', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11 0 ', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12 0 ', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd[ ] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd[ ] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd[ ] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[]dddd[ ] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[]dddd[ ] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[]dddd[ ] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday format', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1', 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2', 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('tl-ph'); test('parse', function (assert) { var tests = 'Enero Ene_Pebrero Peb_Marso Mar_Abril Abr_Mayo May_Hunyo Hun_Hulyo Hul_Agosto Ago_Setyembre Set_Oktubre Okt_Nobyembre Nob_Disyembre Dis'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Linggo, Pebrero 14 2010, 3:25:50 pm'], ['ddd, hA', 'Lin, 3PM'], ['M Mo MM MMMM MMM', '2 2 02 Pebrero Peb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 Linggo Lin Li'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '6 6 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LTS', '15:25:50'], ['L', '02/14/2010'], ['LL', 'Pebrero 14, 2010'], ['LLL', 'Pebrero 14, 2010 15:25'], ['LLLL', 'Linggo, Pebrero 14, 2010 15:25'], ['l', '2/14/2010'], ['ll', 'Peb 14, 2010'], ['lll', 'Peb 14, 2010 15:25'], ['llll', 'Lin, Peb 14, 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = 'Enero Ene_Pebrero Peb_Marso Mar_Abril Abr_Mayo May_Hunyo Hun_Hulyo Hul_Agosto Ago_Setyembre Set_Oktubre Okt_Nobyembre Nob_Disyembre Dis'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Linggo Lin Li_Lunes Lun Lu_Martes Mar Ma_Miyerkules Miy Mi_Huwebes Huw Hu_Biyernes Biy Bi_Sabado Sab Sab'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'ilang segundo', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'isang minuto', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'isang minuto', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minuto', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minuto', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'isang oras', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'isang oras', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 oras', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 oras', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 oras', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'isang araw', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'isang araw', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 araw', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'isang araw', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 araw', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 araw', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'isang buwan', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'isang buwan', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'isang buwan', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 buwan', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 buwan', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 buwan', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'isang buwan', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 buwan', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'isang taon', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 taon', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'isang taon', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 taon', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'sa loob ng ilang segundo', 'prefix'); assert.equal(moment(0).from(30000), 'ilang segundo ang nakalipas', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'sa loob ng ilang segundo', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'sa loob ng 5 araw', 'in 5 days'); }); test('same day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Ngayon sa 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Ngayon sa 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Ngayon sa 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Bukas sa 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Ngayon sa 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Kahapon sa 12:00', 'yesterday at the same time'); }); test('same next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [sa] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [sa] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [sa] LT'), 'Today + ' + i + ' days end of day'); } }); test('same last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [huling linggo] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [huling linggo] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [huling linggo] LT'), 'Today - ' + i + ' days end of day'); } }); test('same all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('tlh'); //Current parsing method doesn't allow parsing correctly months 10, 11 and 12. /* * test('parse', function (assert) { var tests = 'tera jar wa.jar wa_tera jar cha.jar cha_tera jar wej.jar wej_tera jar loS.jar loS_tera jar vagh.jar vagh_tera jar jav.jar jav_tera jar Soch.jar Soch_tera jar chorgh.jar chorgh_tera jar Hut.jar Hut_tera jar wamaH.jar wamaH_tera jar wamaH wa.jar wamaH wa_tera jar wamaH cha.jar wamaH cha'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split('.'); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); */ test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'lojmItjaj, tera jar cha 14. 2010, 3:25:50 pm'], ['ddd, hA', 'lojmItjaj, 3PM'], ['M Mo MM MMMM MMM', '2 2. 02 tera jar cha jar cha'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. lojmItjaj lojmItjaj lojmItjaj'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[DIS jaj] DDDo', 'DIS jaj 45.'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14 tera jar cha 2010'], ['LLL', '14 tera jar cha 2010 15:25'], ['LLLL', 'lojmItjaj, 14 tera jar cha 2010 15:25'], ['l', '14.2.2010'], ['ll', '14 jar cha 2010'], ['lll', '14 jar cha 2010 15:25'], ['llll', 'lojmItjaj, 14 jar cha 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'tera jar wa jar wa_tera jar cha jar cha_tera jar wej jar wej_tera jar loS jar loS_tera jar vagh jar vagh_tera jar jav jar jav_tera jar Soch jar Soch_tera jar chorgh jar chorgh_tera jar Hut jar Hut_tera jar wamaH jar wamaH_tera jar wamaH wa jar wamaH wa_tera jar wamaH cha jar wamaH cha'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'lojmItjaj lojmItjaj lojmItjaj_DaSjaj DaSjaj DaSjaj_povjaj povjaj povjaj_ghItlhjaj ghItlhjaj ghItlhjaj_loghjaj loghjaj loghjaj_buqjaj buqjaj buqjaj_ghInjaj ghInjaj ghInjaj'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'puS lup', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'wa tup', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'wa tup', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), 'cha tup', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), 'loSmaH loS tup', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'wa rep', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'wa rep', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), 'cha rep', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), 'vagh rep', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), 'chamaH wa rep', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'wa jaj', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'wa jaj', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), 'cha jaj', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'wa jaj', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), 'vagh jaj', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), 'chamaH vagh jaj', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'wa jar', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'wa jar', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'wa jar', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), 'cha jar', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), 'cha jar', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), 'wej jar', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'wa jar', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), 'vagh jar', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'wa DIS', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), 'cha DIS', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'wa DIS', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), 'vagh DIS', '5 years = 5 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 112}), true), 'wavatlh wamaH cha DIS', '112 years = 112 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 122}), true), 'wavatlh chamaH cha DIS', '122 years = 122 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 213}), true), 'chavatlh wamaH wej DIS', '213 years = 213 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 223}), true), 'chavatlh chamaH wej DIS', '223 years = 223 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'puS lup pIq', 'suffix'); assert.equal(moment(0).from(30000), 'puS lup ret', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'puS lup ret', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'puS lup pIq', 'in a few seconds'); assert.equal(moment().add({h: 1}).fromNow(), 'wa rep pIq', 'in an hour'); assert.equal(moment().add({d: 5}).fromNow(), 'vagh leS', 'in 5 days'); assert.equal(moment().add({M: 2}).fromNow(), 'cha waQ', 'in 2 months'); assert.equal(moment().add({y: 1}).fromNow(), 'wa nem', 'in a year'); assert.equal(moment().add({s: -30}).fromNow(), 'puS lup ret', 'a few seconds ago'); assert.equal(moment().add({h: -1}).fromNow(), 'wa rep ret', 'an hour ago'); assert.equal(moment().add({d: -5}).fromNow(), 'vagh Hu', '5 days ago'); assert.equal(moment().add({M: -2}).fromNow(), 'cha wen', '2 months ago'); assert.equal(moment().add({y: -1}).fromNow(), 'wa ben', 'a year ago'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'DaHjaj 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'DaHjaj 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'DaHjaj 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'waleS 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'DaHjaj 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'waHu 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('LLL'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('LLL'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('LLL'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('LLL'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('LLL'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('LLL'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('tr'); test('parse', function (assert) { var tests = 'Ocak Oca_ubat ub_Mart Mar_Nisan Nis_Mays May_Haziran Haz_Temmuz Tem_Austos Au_Eyll Eyl_Ekim Eki_Kasm Kas_Aralk Ara'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Pazar, ubat 14\'nc 2010, 3:25:50 pm'], ['ddd, hA', 'Paz, 3PM'], ['M Mo MM MMMM MMM', '2 2\'nci 02 ubat ub'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14\'nc 14'], ['d do dddd ddd dd', '0 0\'nc Pazar Paz Pz'], ['DDD DDDo DDDD', '45 45\'inci 045'], ['w wo ww', '7 7\'nci 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[yln] DDDo [gn]', 'yln 45\'inci gn'], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14 ubat 2010'], ['LLL', '14 ubat 2010 15:25'], ['LLLL', 'Pazar, 14 ubat 2010 15:25'], ['l', '14.2.2010'], ['ll', '14 ub 2010'], ['lll', '14 ub 2010 15:25'], ['llll', 'Paz, 14 ub 2010 15:25'] ], DDDo = [ [359, '360\'nc'], [199, '200\'nc'], [149, '150\'nci'] ], dt = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), DDDoDt, i; for (i = 0; i < a.length; i++) { assert.equal(dt.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } for (i = 0; i < DDDo.length; i++) { DDDoDt = moment([2010]); assert.equal(DDDoDt.add(DDDo[i][0], 'days').format('DDDo'), DDDo[i][1], DDDo[i][0] + ' ---> ' + DDDo[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1\'inci', '1st'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2\'nci', '2nd'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3\'nc', '3rd'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4\'nc', '4th'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5\'inci', '5th'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6\'nc', '6th'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7\'nci', '7th'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8\'inci', '8th'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9\'uncu', '9th'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10\'uncu', '10th'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11\'inci', '11th'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12\'nci', '12th'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13\'nc', '13th'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14\'nc', '14th'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15\'inci', '15th'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16\'nc', '16th'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17\'nci', '17th'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18\'inci', '18th'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19\'uncu', '19th'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20\'nci', '20th'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21\'inci', '21th'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22\'nci', '22th'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23\'nc', '23th'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24\'nc', '24th'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25\'inci', '25th'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26\'nc', '26th'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27\'nci', '27th'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28\'inci', '28th'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29\'uncu', '29th'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30\'uncu', '30th'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31\'inci', '31st'); }); test('format month', function (assert) { var expected = 'Ocak Oca_ubat ub_Mart Mar_Nisan Nis_Mays May_Haziran Haz_Temmuz Tem_Austos Au_Eyll Eyl_Ekim Eki_Kasm Kas_Aralk Ara'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Pazar Paz Pz_Pazartesi Pts Pt_Sal Sal Sa_aramba ar a_Perembe Per Pe_Cuma Cum Cu_Cumartesi Cts Ct'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'birka saniye', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'bir dakika', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'bir dakika', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 dakika', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 dakika', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'bir saat', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'bir saat', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 saat', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 saat', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 saat', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'bir gn', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'bir gn', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 gn', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'bir gn', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 gn', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 gn', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'bir ay', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'bir ay', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'bir ay', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ay', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ay', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ay', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'bir ay', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ay', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'bir yl', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 yl', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'bir yl', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 yl', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'birka saniye sonra', 'prefix'); assert.equal(moment(0).from(30000), 'birka saniye nce', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'birka saniye nce', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'birka saniye sonra', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), '5 gn sonra', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'bugn saat 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'bugn saat 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'bugn saat 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'yarn saat 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'bugn saat 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'dn 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('[haftaya] dddd [saat] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[haftaya] dddd [saat] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[haftaya] dddd [saat] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[geen hafta] dddd [saat] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[geen hafta] dddd [saat] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[geen hafta] dddd [saat] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1\'inci', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1\'inci', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2\'nci', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2\'nci', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3\'nc', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('tzl'); test('parse', function (assert) { var tests = 'Januar Jan_Fevraglh Fev_Mar Mar_Avru Avr_Mai Mai_Gn Gn_Julia Jul_Guscht Gus_Setemvar Set_Listopts Lis_Noemvar Noe_Zecemvar Zec'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h.mm.ss a', 'Sladi, Fevraglh 14. 2010, 3.25.50 d\'o'], ['ddd, hA', 'Sl, 3D\'O'], ['M Mo MM MMMM MMM', '2 2. 02 Fevraglh Fev'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14. 14'], ['d do dddd ddd dd', '0 0. Sladi Sl S'], ['DDD DDDo DDDD', '45 45. 045'], ['w wo ww', '6 6. 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'd\'o D\'O'], ['[the] DDDo [day of the year]', 'the 45. day of the year'], ['LTS', '15.25.50'], ['L', '14.02.2010'], ['LL', '14. Fevraglh dallas 2010'], ['LLL', '14. Fevraglh dallas 2010 15.25'], ['LLLL', 'Sladi, li 14. Fevraglh dallas 2010 15.25'], ['l', '14.2.2010'], ['ll', '14. Fev dallas 2010'], ['lll', '14. Fev dallas 2010 15.25'], ['llll', 'Sl, li 14. Fev dallas 2010 15.25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1.', '1.'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2.', '2.'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3.', '3.'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4.', '4.'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5.', '5.'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6.', '6.'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7.', '7.'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8.', '8.'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9.', '9.'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10.', '10.'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11.', '11.'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12.', '12.'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13.', '13.'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14.', '14.'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15.', '15.'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16.', '16.'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17.', '17.'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18.', '18.'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19.', '19.'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20.', '20.'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21.', '21.'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22.', '22.'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23.', '23.'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24.', '24.'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25.', '25.'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26.', '26.'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27.', '27.'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28.', '28.'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29.', '29.'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30.', '30.'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31.', '31.'); }); test('format month', function (assert) { var expected = 'Januar Jan_Fevraglh Fev_Mar Mar_Avru Avr_Mai Mai_Gn Gn_Julia Jul_Guscht Gus_Setemvar Set_Listopts Lis_Noemvar Noe_Zecemvar Zec'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'Sladi Sl S_Lnei Ln L_Maitzi Mai Ma_Mrcuri Mr M_Xhadi Xh Xh_Vineri Vi Vi_Sturi St S'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'viensas secunds', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '\'n mut', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '\'n mut', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 muts', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 muts', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '\'n ora', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '\'n ora', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 oras', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 oras', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 oras', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '\'n ziua', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '\'n ziua', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ziuas', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '\'n ziua', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ziuas', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ziuas', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '\'n mes', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '\'n mes', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '\'n mes', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 mesen', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 mesen', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 mesen', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '\'n mes', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 mesen', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '\'n ar', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ars', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '\'n ar', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ars', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'osprei viensas secunds', 'prefix'); assert.equal(moment(0).from(30000), 'ja\'iensas secunds', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'ja\'iensas secunds', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'osprei viensas secunds', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'osprei 5 ziuas', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'oxhi 12.00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'oxhi 12.25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'oxhi 13.00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'dem 12.00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'oxhi 11.00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'ieiri 12.00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[sr el] dddd [lasteu ] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[sr el] dddd [lasteu ] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[sr el] dddd [lasteu ] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); // Monday is the first day of the week. // The week that contains Jan 4th is the first week of the year. test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52.', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1.', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1.', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2.', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2.', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('tzm-latn'); test('parse', function (assert) { var tests = 'innayr innayr_brayr brayr_mars mars_ibrir ibrir_mayyw mayyw_ywnyw ywnyw_ywlywz ywlywz_wt wt_wtanbir wtanbir_ktwbr ktwbr_nwwanbir nwwanbir_dwjnbir dwjnbir'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'asamas, brayr 14 2010, 3:25:50 pm'], ['ddd, hA', 'asamas, 3PM'], ['M Mo MM MMMM MMM', '2 2 02 brayr brayr'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 asamas asamas asamas'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '8 8 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 brayr 2010'], ['LLL', '14 brayr 2010 15:25'], ['LLLL', 'asamas 14 brayr 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 brayr 2010'], ['lll', '14 brayr 2010 15:25'], ['llll', 'asamas 14 brayr 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = 'innayr innayr_brayr brayr_mars mars_ibrir ibrir_mayyw mayyw_ywnyw ywnyw_ywlywz ywlywz_wt wt_wtanbir wtanbir_ktwbr ktwbr_nwwanbir nwwanbir_dwjnbir dwjnbir'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'asamas asamas asamas_aynas aynas aynas_asinas asinas asinas_akras akras akras_akwas akwas akwas_asimwas asimwas asimwas_asiyas asiyas asiyas'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'imik', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'minu', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'minu', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 minu', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 minu', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'saa', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'saa', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 tassain', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 tassain', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 tassain', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'ass', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'ass', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ossan', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'ass', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ossan', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ossan', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'ayowr', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'ayowr', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'ayowr', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 iyyirn', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 iyyirn', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 iyyirn', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'ayowr', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 iyyirn', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'asgas', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 isgasn', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'asgas', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 isgasn', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'dadkh s yan imik', 'prefix'); assert.equal(moment(0).from(30000), 'yan imik', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'yan imik', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'dadkh s yan imik', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), 'dadkh s yan 5 ossan', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'asdkh g 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'asdkh g 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'asdkh g 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'aska g 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'asdkh g 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'assant g 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [g] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [g] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [g] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [g] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [g] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [g] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 31]).format('w ww wo'), '1 01 1', 'Dec 31 2011 should be week 1'); assert.equal(moment([2012, 0, 6]).format('w ww wo'), '1 01 1', 'Jan 6 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '2 02 2', 'Jan 7 2012 should be week 2'); assert.equal(moment([2012, 0, 13]).format('w ww wo'), '2 02 2', 'Jan 13 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '3 03 3', 'Jan 14 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('tzm'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', ', 14 2010, 3:25:50 pm'], ['ddd, hA', ', 3PM'], ['M Mo MM MMMM MMM', '2 2 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '8 8 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45 day of the year'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 2010'], ['LLL', '14 2010 15:25'], ['LLLL', ' 14 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 2010'], ['lll', '14 2010 15:25'], ['llll', ' 14 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), '', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 o', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 o', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 o', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'o', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'o', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'o', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'o', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' 5 o', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 31]).format('w ww wo'), '1 01 1', 'Dec 31 2011 should be week 1'); assert.equal(moment([2012, 0, 6]).format('w ww wo'), '1 01 1', 'Jan 6 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '2 02 2', 'Jan 7 2012 should be week 2'); assert.equal(moment([2012, 0, 13]).format('w ww wo'), '2 02 2', 'Jan 13 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '3 03 3', 'Jan 14 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('uk'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do MMMM YYYY, HH:mm:ss', ', 14- 2010, 15:25:50'], ['ddd, h A', ', 3 '], ['M Mo MM MMMM MMM', '2 2- 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14- 14'], ['d do dddd ddd dd', '0 0- '], ['DDD DDDo DDDD', '45 45- 045'], ['w wo ww', '7 7- 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', ' '], ['DDDo [ ]', '45- '], ['LTS', '15:25:50'], ['L', '14.02.2010'], ['LL', '14 2010 .'], ['LLL', '14 2010 ., 15:25'], ['LLLL', ', 14 2010 ., 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format meridiem', function (assert) { assert.equal(moment([2012, 11, 28, 0, 0]).format('A'), '', 'night'); assert.equal(moment([2012, 11, 28, 3, 59]).format('A'), '', 'night'); assert.equal(moment([2012, 11, 28, 4, 0]).format('A'), '', 'morning'); assert.equal(moment([2012, 11, 28, 11, 59]).format('A'), '', 'morning'); assert.equal(moment([2012, 11, 28, 12, 0]).format('A'), '', 'afternoon'); assert.equal(moment([2012, 11, 28, 16, 59]).format('A'), '', 'afternoon'); assert.equal(moment([2012, 11, 28, 17, 0]).format('A'), '', 'evening'); assert.equal(moment([2012, 11, 28, 23, 59]).format('A'), '', 'evening'); }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1-', '1-'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2-', '2-'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3-', '3-'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4-', '4-'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5-', '5-'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6-', '6-'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7-', '7-'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8-', '8-'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9-', '9-'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10-', '10-'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11-', '11-'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12-', '12-'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13-', '13-'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14-', '14-'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15-', '15-'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16-', '16-'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17-', '17-'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18-', '18-'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19-', '19-'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20-', '20-'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21-', '21-'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22-', '22-'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23-', '23-'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24-', '24-'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25-', '25-'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26-', '26-'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27-', '27-'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28-', '28-'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29-', '29-'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30-', '30-'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31-', '31-'); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format month case', function (assert) { var months = { 'nominative': '___________'.split('_'), 'accusative': '___________'.split('_') }, i; for (i = 0; i < 12; i++) { assert.equal(moment([2011, i, 1]).format('D MMMM'), '1 ' + months.accusative[i], '1 ' + months.accusative[i]); assert.equal(moment([2011, i, 1]).format('MMMM'), months.nominative[i], '1 ' + months.nominative[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ', '44 seconds = seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 11}), true), '11 ', '11 days = 11 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 21}), true), '21 ', '21 days = 21 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' 5 ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 2}).calendar(), ' 10:00', 'Now minus 2 hours'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00', 'yesterday at the same time'); // A special case for Ukrainian since 11 hours have different preposition assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00', 'same day at 11 o\'clock'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('[] dddd [' + (m.hours() === 11 ? '' : '') + '] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd [] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd [] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; function makeFormat(d) { switch (d.day()) { case 0: case 3: case 5: case 6: return '[] dddd [' + (d.hours() === 11 ? '' : '') + '] LT'; case 1: case 2: case 4: return '[] dddd [' + (d.hours() === 11 ? '' : '') + '] LT'; } } for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format(makeFormat(m)), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2011, 11, 26]).format('w ww wo'), '1 01 1-', 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1-', 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2-', 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2-', 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3-', 'Jan 9 2012 should be week 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('uz'); test('parse', function (assert) { var tests = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, Do-MMMM YYYY, h:mm:ss', ', 14- 2010, 3:25:50'], ['ddd, h:mm', ', 3:25'], ['M Mo MM MMMM MMM', '2 2 02 '], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '7 7 07'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[] DDDo-[]', ' 45-'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 2010'], ['LLL', '14 2010 15:25'], ['LLLL', '14 2010, 15:25'], ['l', '14/2/2010'], ['ll', '14 2010'], ['lll', '14 2010 15:25'], ['llll', '14 2010, 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var expected = ' _ _ _ _ _ _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), '', '44 = '); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), ' ', '45 = '); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), ' ', '89 = '); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 = 44 '); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), ' ', '45 = '); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), ' ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 = 5 '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 = 21 '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), ' ', '22 = '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), ' ', '35 = '); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), ' ', '1 = 1 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 = 5 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 = 25 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), ' ', '26 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), ' ', '30 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), ' ', '45 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 = 3 '); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), ' ', ' = '); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 = 5 '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), ' ', '345 = '); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 = 2 '); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), ' ', '1 = '); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 = 5 '); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), ' ', 'prefix'); assert.equal(moment(0).from(30000), ' ', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), ' ', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), ' 5 ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), ' 12:00 ', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), ' 12:25 ', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), ' 13:00 ', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), ' 12:00 ', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), ' 11:00 ', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), ' 12:00 ', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [ ] LT []'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [ ] LT []'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [ ] LT []'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[] dddd [ ] LT []'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[] dddd [ ] LT []'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[] dddd [ ] LT []'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '2 02 2', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '3 03 3', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('vi'); test('parse', function (assert) { var i, tests = 'thng 1,Th01_thng 2,Th02_thng 3,Th03_thng 4,Th04_thng 5,Th05_thng 6,Th06_thng 7,Th07_thng 8,Th08_thng 9,Th09_thng 10,Th10_thng 11,Th11_thng 12,Th12'.split('_'); function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + i); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(','); equalTest(tests[i][0], '[thng] M', i); equalTest(tests[i][1], '[Th]M', i); equalTest(tests[i][0], '[thng] MM', i); equalTest(tests[i][1], '[Th]MM', i); equalTest(tests[i][0].toLocaleLowerCase(), '[THNG] M', i); equalTest(tests[i][1].toLocaleLowerCase(), '[TH]M', i); equalTest(tests[i][0].toLocaleUpperCase(), '[THNG] MM', i); equalTest(tests[i][1].toLocaleUpperCase(), '[TH]MM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'ch nht, thng 2 14 2010, 3:25:50 ch'], ['ddd, hA', 'CN, 3CH'], ['M Mo MM MMMM MMM', '2 2 02 thng 2 Th02'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 ch nht CN CN'], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '6 6 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'ch CH'], ['[ngy th] DDDo [ca nm]', 'ngy th 45 ca nm'], ['LTS', '15:25:50'], ['L', '14/02/2010'], ['LL', '14 thng 2 nm 2010'], ['LLL', '14 thng 2 nm 2010 15:25'], ['LLLL', 'ch nht, 14 thng 2 nm 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 Th02 2010'], ['lll', '14 Th02 2010 15:25'], ['llll', 'CN, 14 Th02 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31'); }); test('format month', function (assert) { var i, expected = 'thng 1,Th01_thng 2,Th02_thng 3,Th03_thng 4,Th04_thng 5,Th05_thng 6,Th06_thng 7,Th07_thng 8,Th08_thng 9,Th09_thng 10,Th10_thng 11,Th11_thng 12,Th12'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM,MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var i, expected = 'ch nht CN CN_th hai T2 T2_th ba T3 T3_th t T4 T4_th nm T5 T5_th su T6 T6_th by T7 T7'.split('_'); for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'vi giy', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'mt pht', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'mt pht', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 pht', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 pht', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'mt gi', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'mt gi', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 gi', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 gi', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 gi', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'mt ngy', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'mt ngy', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ngy', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'mt ngy', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ngy', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ngy', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'mt thng', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'mt thng', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'mt thng', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 thng', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 thng', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 thng', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'mt thng', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 thng', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'mt nm', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 nm', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'mt nm', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 nm', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), 'vi giy ti', 'prefix'); assert.equal(moment(0).from(30000), 'vi giy trc', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), 'vi giy trc', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), 'vi giy ti', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), '5 ngy ti', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Hm nay lc 12:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Hm nay lc 12:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Hm nay lc 13:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Ngy mai lc 12:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Hm nay lc 11:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Hm qua lc 12:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [tun ti lc] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [tun ti lc] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [tun ti lc] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('dddd [tun ri lc] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [tun ri lc] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [tun ri lc] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('x-pseudo'); test('parse', function (assert) { var tests = 'J~~r J~_F~br~r ~Fb_~Mrc~h ~Mr_p~rl ~pr_~M ~M_~J~ ~J_Jl~ ~Jl_~gst~ ~g_Sp~tmb~r ~Sp_~ctb~r ~ct_~vm~br ~v_~Dc~mbr ~Dc'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'S~d~, F~br~r 14th 2010, 3:25:50 pm'], ['ddd, hA', 'S~, 3PM'], ['M Mo MM MMMM MMM', '2 2nd 02 F~br~r ~Fb'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14th 14'], ['d do dddd ddd dd', '0 0th S~d~ S~ S~'], ['DDD DDDo DDDD', '45 45th 045'], ['w wo ww', '6 6th 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45th day of the year'], ['LT', '15:25'], ['L', '14/02/2010'], ['LL', '14 F~br~r 2010'], ['LLL', '14 F~br~r 2010 15:25'], ['LLLL', 'S~d~, 14 F~br~r 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 ~Fb 2010'], ['lll', '14 ~Fb 2010 15:25'], ['llll', 'S~, 14 ~Fb 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format ordinal', function (assert) { assert.equal(moment([2011, 0, 1]).format('DDDo'), '1st', '1st'); assert.equal(moment([2011, 0, 2]).format('DDDo'), '2nd', '2nd'); assert.equal(moment([2011, 0, 3]).format('DDDo'), '3rd', '3rd'); assert.equal(moment([2011, 0, 4]).format('DDDo'), '4th', '4th'); assert.equal(moment([2011, 0, 5]).format('DDDo'), '5th', '5th'); assert.equal(moment([2011, 0, 6]).format('DDDo'), '6th', '6th'); assert.equal(moment([2011, 0, 7]).format('DDDo'), '7th', '7th'); assert.equal(moment([2011, 0, 8]).format('DDDo'), '8th', '8th'); assert.equal(moment([2011, 0, 9]).format('DDDo'), '9th', '9th'); assert.equal(moment([2011, 0, 10]).format('DDDo'), '10th', '10th'); assert.equal(moment([2011, 0, 11]).format('DDDo'), '11th', '11th'); assert.equal(moment([2011, 0, 12]).format('DDDo'), '12th', '12th'); assert.equal(moment([2011, 0, 13]).format('DDDo'), '13th', '13th'); assert.equal(moment([2011, 0, 14]).format('DDDo'), '14th', '14th'); assert.equal(moment([2011, 0, 15]).format('DDDo'), '15th', '15th'); assert.equal(moment([2011, 0, 16]).format('DDDo'), '16th', '16th'); assert.equal(moment([2011, 0, 17]).format('DDDo'), '17th', '17th'); assert.equal(moment([2011, 0, 18]).format('DDDo'), '18th', '18th'); assert.equal(moment([2011, 0, 19]).format('DDDo'), '19th', '19th'); assert.equal(moment([2011, 0, 20]).format('DDDo'), '20th', '20th'); assert.equal(moment([2011, 0, 21]).format('DDDo'), '21st', '21st'); assert.equal(moment([2011, 0, 22]).format('DDDo'), '22nd', '22nd'); assert.equal(moment([2011, 0, 23]).format('DDDo'), '23rd', '23rd'); assert.equal(moment([2011, 0, 24]).format('DDDo'), '24th', '24th'); assert.equal(moment([2011, 0, 25]).format('DDDo'), '25th', '25th'); assert.equal(moment([2011, 0, 26]).format('DDDo'), '26th', '26th'); assert.equal(moment([2011, 0, 27]).format('DDDo'), '27th', '27th'); assert.equal(moment([2011, 0, 28]).format('DDDo'), '28th', '28th'); assert.equal(moment([2011, 0, 29]).format('DDDo'), '29th', '29th'); assert.equal(moment([2011, 0, 30]).format('DDDo'), '30th', '30th'); assert.equal(moment([2011, 0, 31]).format('DDDo'), '31st', '31st'); }); test('format month', function (assert) { var expected = 'J~~r J~_F~br~r ~Fb_~Mrc~h ~Mr_p~rl ~pr_~M ~M_~J~ ~J_Jl~ ~Jl_~gst~ ~g_Sp~tmb~r ~Sp_~ctb~r ~ct_~vm~br ~v_~Dc~mbr ~Dc'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = 'S~d~ S~ S~_M~d~ ~M M~_T~sd~ ~T T_Wd~sd~ ~Wd ~W_T~hrs~d ~Th T~h_~Frd~ ~Fr Fr~_S~tr~d ~St S'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), ' ~fw ~sc~ds', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), ' ~m~t', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), ' ~m~t', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 m~~ts', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 m~~ts', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '~ h~r', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '~ h~r', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 h~rs', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 h~rs', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 h~rs', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), ' ~d', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), ' ~d', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 d~s', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), ' ~d', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 d~s', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 d~s', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), ' ~m~th', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), ' ~m~th', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), ' ~m~th', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 m~t~hs', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 m~t~hs', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 m~t~hs', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), ' ~m~th', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 m~t~hs', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), ' ~r', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ~rs', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), ' ~r', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ~rs', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), '~ ~fw ~sc~ds', 'prefix'); assert.equal(moment(0).from(30000), ' ~fw ~sc~ds ~g', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), ' ~fw ~sc~ds ~g', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), '~ ~fw ~sc~ds', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), '~ 5 d~s', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(2).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'T~d~ t 02:00', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'T~d~ t 02:25', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'T~d~ t 03:00', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'T~m~rr~w t 02:00', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'T~d~ t 01:00', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), '~st~rd~ t 02:00', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('dddd [t] LT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('dddd [t] LT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('dddd [t] LT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[L~st] dddd [t] LT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[L~st] dddd [t] LT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[L~st] dddd [t] LT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52nd', 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).format('w ww wo'), '1 01 1st', 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '1 01 1st', 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).format('w ww wo'), '2 02 2nd', 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '2 02 2nd', 'Jan 15 2012 should be week 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('zh-cn'); test('parse', function (assert) { var tests = ' 1_ 2_ 3_ 4_ 5_ 6_ 7_ 8_ 9_ 10_ 11_ 12'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, a h:mm:ss', ', 14 2010, 3:25:50'], ['ddd, Ah', ', 3'], ['M Mo MM MMMM MMM', '2 2 02 2'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '6 6 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', ' '], ['[] DDDo', ' 45'], ['LTS', '32550'], ['L', '2010-02-14'], ['LL', '2010214'], ['LLL', '2010214325'], ['LLLL', '2010214325'], ['l', '2010-02-14'], ['ll', '2010214'], ['lll', '2010214325'], ['llll', '2010214325'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format month', function (assert) { var expected = ' 1_ 2_ 3_ 4_ 5_ 6_ 7_ 8_ 9_ 10_ 11_ 12'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), '', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '1 ', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '1 ', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 ', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 ', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '1 ', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '1 ', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 ', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 ', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 ', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '1 ', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '1 ', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 ', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '1 ', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 ', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 ', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '1 ', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '1 ', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '1 ', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 ', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 ', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 ', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '1 ', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 ', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '1 ', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 ', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '1 ', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 ', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), '', 'prefix'); assert.equal(moment(0).from(30000), '', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), '', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), '', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), '5 ', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), '12', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), '1225', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), '1', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), '12', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), '11', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), '12', 'yesterday at the same time'); }); test('calendar current week', function (assert) { var i, m, today = moment().startOf('day'); for (i = 0; i < 7; i++) { m = moment().startOf('week').add({d: i}); if (Math.abs(m.diff(today, 'days')) <= 1) { continue; // skip today, yesterday, tomorrow } assert.equal(m.calendar(), m.format('[]ddd12'), 'Monday + ' + i + ' days current time'); } }); test('calendar next week', function (assert) { var i, m, today = moment().startOf('day'); for (i = 7; i < 14; i++) { m = moment().startOf('week').add({d: i}); if (Math.abs(m.diff(today, 'days')) >= 7) { continue; } if (Math.abs(m.diff(today, 'days')) <= 1) { continue; // skip today, yesterday, tomorrow } assert.equal(m.calendar(), m.format('[]ddd12'), 'Today + ' + i + ' days beginning of day'); } assert.equal(42, 42, 'at least one assert'); }); test('calendar last week', function (assert) { var i, m, today = moment().startOf('day'); for (i = 1; i < 8; i++) { m = moment().startOf('week').subtract({d: i}); if ((Math.abs(m.diff(today, 'days')) >= 7) || (Math.abs(m.diff(today, 'days')) <= 1)) { continue; } assert.equal(m.calendar(), m.format('[]ddd12'), 'Monday - ' + i + ' days next week'); } assert.equal(42, 42, 'at least one assert'); }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('LL'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('LL'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('LL'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('LL'), 'in 2 weeks'); }); test('meridiem', function (assert) { assert.equal(moment([2011, 2, 23, 0, 0]).format('A'), '', 'before dawn'); assert.equal(moment([2011, 2, 23, 6, 0]).format('A'), '', 'morning'); assert.equal(moment([2011, 2, 23, 9, 0]).format('A'), '', 'before noon'); assert.equal(moment([2011, 2, 23, 12, 0]).format('A'), '', 'noon'); assert.equal(moment([2011, 2, 23, 13, 0]).format('A'), '', 'afternoon'); assert.equal(moment([2011, 2, 23, 18, 0]).format('A'), '', 'night'); }); test('weeks year starting sunday format', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '52 52 52', 'Jan 1 2012 52'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1', 'Jan 7 2012 1'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2', 'Jan 14 2012 2'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } localeModule('zh-tw'); test('parse', function (assert) { var tests = ' 1_ 2_ 3_ 4_ 5_ 6_ 7_ 8_ 9_ 10_ 11_ 12'.split('_'), i; function equalTest(input, mmm, i) { assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); test('format', function (assert) { var a = [ ['dddd, MMMM Do YYYY, a h:mm:ss', ', 14 2010, 3:25:50'], ['ddd, Ah', ', 3'], ['M Mo MM MMMM MMM', '2 2 02 2'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14 14'], ['d do dddd ddd dd', '0 0 '], ['DDD DDDo DDDD', '45 45 045'], ['w wo ww', '8 8 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', ' '], ['[] DDDo', ' 45'], ['LTS', '32550'], ['L', '2010214'], ['LL', '2010214'], ['LLL', '2010214325'], ['LLLL', '2010214325'], ['l', '2010214'], ['ll', '2010214'], ['lll', '2010214325'], ['llll', '2010214325'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assert.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('format month', function (assert) { var expected = ' 1_ 2_ 3_ 4_ 5_ 6_ 7_ 8_ 9_ 10_ 11_ 12'.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); test('format week', function (assert) { var expected = ' _ _ _ _ _ _ '.split('_'), i; for (i = 0; i < expected.length; i++) { assert.equal(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); test('from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), '', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), '1', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89}), true), '1', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45}), true), '1', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89}), true), '1', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22}), true), '1', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35}), true), '1', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1}), true), '1', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), '1', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), '1', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), '1', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), '1', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), '1', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), '1', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5', '5 years = 5 years'); }); test('suffix', function (assert) { assert.equal(moment(30000).from(0), '', 'prefix'); assert.equal(moment(0).from(30000), '', 'suffix'); }); test('now from now', function (assert) { assert.equal(moment().fromNow(), '', 'now from now should display as in the past'); }); test('fromNow', function (assert) { assert.equal(moment().add({s: 30}).fromNow(), '', 'in a few seconds'); assert.equal(moment().add({d: 5}).fromNow(), '5', 'in 5 days'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), '1200', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), '1225', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), '100', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), '1200', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), '1100', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), '1200', 'yesterday at the same time'); }); test('calendar next week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assert.equal(m.calendar(), m.format('[]ddddLT'), 'Today + ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[]ddddLT'), 'Today + ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[]ddddLT'), 'Today + ' + i + ' days end of day'); } }); test('calendar last week', function (assert) { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assert.equal(m.calendar(), m.format('[]ddddLT'), 'Today - ' + i + ' days current time'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assert.equal(m.calendar(), m.format('[]ddddLT'), 'Today - ' + i + ' days beginning of day'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assert.equal(m.calendar(), m.format('[]ddddLT'), 'Today - ' + i + ' days end of day'); } }); test('calendar all else', function (assert) { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '1 week ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 1 week'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assert.equal(weeksAgo.calendar(), weeksAgo.format('L'), '2 weeks ago'); assert.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), 'in 2 weeks'); }); test('meridiem', function (assert) { assert.equal(moment([2011, 2, 23, 0, 0]).format('a'), '', 'morning'); assert.equal(moment([2011, 2, 23, 9, 0]).format('a'), '', 'before noon'); assert.equal(moment([2011, 2, 23, 12, 0]).format('a'), '', 'noon'); assert.equal(moment([2011, 2, 23, 13, 0]).format('a'), '', 'after noon'); assert.equal(moment([2011, 2, 23, 18, 0]).format('a'), '', 'night'); assert.equal(moment([2011, 2, 23, 0, 0]).format('A'), '', 'morning'); assert.equal(moment([2011, 2, 23, 9, 0]).format('A'), '', 'before noon'); assert.equal(moment([2011, 2, 23, 12, 0]).format('A'), '', 'noon'); assert.equal(moment([2011, 2, 23, 13, 0]).format('A'), '', 'afternoon'); assert.equal(moment([2011, 2, 23, 18, 0]).format('A'), '', 'night'); }); test('weeks year starting sunday format', function (assert) { assert.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1', 'Jan 1 2012 1'); assert.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1', 'Jan 7 2012 1'); assert.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2', 'Jan 8 2012 2'); assert.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2', 'Jan 14 2012 2'); assert.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3', 'Jan 15 2012 3'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('add and subtract'); test('add short reverse args', function (assert) { var a = moment(), b, c, d; a.year(2011); a.month(9); a.date(12); a.hours(6); a.minutes(7); a.seconds(8); a.milliseconds(500); assert.equal(a.add({ms: 50}).milliseconds(), 550, 'Add milliseconds'); assert.equal(a.add({s: 1}).seconds(), 9, 'Add seconds'); assert.equal(a.add({m: 1}).minutes(), 8, 'Add minutes'); assert.equal(a.add({h: 1}).hours(), 7, 'Add hours'); assert.equal(a.add({d: 1}).date(), 13, 'Add date'); assert.equal(a.add({w: 1}).date(), 20, 'Add week'); assert.equal(a.add({M: 1}).month(), 10, 'Add month'); assert.equal(a.add({y: 1}).year(), 2012, 'Add year'); assert.equal(a.add({Q: 1}).month(), 1, 'Add quarter'); b = moment([2010, 0, 31]).add({M: 1}); c = moment([2010, 1, 28]).subtract({M: 1}); d = moment([2010, 1, 28]).subtract({Q: 1}); assert.equal(b.month(), 1, 'add month, jan 31st to feb 28th'); assert.equal(b.date(), 28, 'add month, jan 31st to feb 28th'); assert.equal(c.month(), 0, 'subtract month, feb 28th to jan 28th'); assert.equal(c.date(), 28, 'subtract month, feb 28th to jan 28th'); assert.equal(d.month(), 10, 'subtract quarter, feb 28th 2010 to nov 28th 2009'); assert.equal(d.date(), 28, 'subtract quarter, feb 28th 2010 to nov 28th 2009'); assert.equal(d.year(), 2009, 'subtract quarter, feb 28th 2010 to nov 28th 2009'); }); test('add long reverse args', function (assert) { var a = moment(); a.year(2011); a.month(9); a.date(12); a.hours(6); a.minutes(7); a.seconds(8); a.milliseconds(500); assert.equal(a.add({milliseconds: 50}).milliseconds(), 550, 'Add milliseconds'); assert.equal(a.add({seconds: 1}).seconds(), 9, 'Add seconds'); assert.equal(a.add({minutes: 1}).minutes(), 8, 'Add minutes'); assert.equal(a.add({hours: 1}).hours(), 7, 'Add hours'); assert.equal(a.add({days: 1}).date(), 13, 'Add date'); assert.equal(a.add({weeks: 1}).date(), 20, 'Add week'); assert.equal(a.add({months: 1}).month(), 10, 'Add month'); assert.equal(a.add({years: 1}).year(), 2012, 'Add year'); assert.equal(a.add({quarters: 1}).month(), 1, 'Add quarter'); }); test('add long singular reverse args', function (assert) { var a = moment(); a.year(2011); a.month(9); a.date(12); a.hours(6); a.minutes(7); a.seconds(8); a.milliseconds(500); assert.equal(a.add({millisecond: 50}).milliseconds(), 550, 'Add milliseconds'); assert.equal(a.add({second: 1}).seconds(), 9, 'Add seconds'); assert.equal(a.add({minute: 1}).minutes(), 8, 'Add minutes'); assert.equal(a.add({hour: 1}).hours(), 7, 'Add hours'); assert.equal(a.add({day: 1}).date(), 13, 'Add date'); assert.equal(a.add({week: 1}).date(), 20, 'Add week'); assert.equal(a.add({month: 1}).month(), 10, 'Add month'); assert.equal(a.add({year: 1}).year(), 2012, 'Add year'); assert.equal(a.add({quarter: 1}).month(), 1, 'Add quarter'); }); test('add string long reverse args', function (assert) { var a = moment(), b; test.expectedDeprecations('moment().add(period, number)'); a.year(2011); a.month(9); a.date(12); a.hours(6); a.minutes(7); a.seconds(8); a.milliseconds(500); b = a.clone(); assert.equal(a.add('millisecond', 50).milliseconds(), 550, 'Add milliseconds'); assert.equal(a.add('second', 1).seconds(), 9, 'Add seconds'); assert.equal(a.add('minute', 1).minutes(), 8, 'Add minutes'); assert.equal(a.add('hour', 1).hours(), 7, 'Add hours'); assert.equal(a.add('day', 1).date(), 13, 'Add date'); assert.equal(a.add('week', 1).date(), 20, 'Add week'); assert.equal(a.add('month', 1).month(), 10, 'Add month'); assert.equal(a.add('year', 1).year(), 2012, 'Add year'); assert.equal(b.add('day', '01').date(), 13, 'Add date'); assert.equal(a.add('quarter', 1).month(), 1, 'Add quarter'); }); test('add string long singular reverse args', function (assert) { var a = moment(), b; test.expectedDeprecations('moment().add(period, number)'); a.year(2011); a.month(9); a.date(12); a.hours(6); a.minutes(7); a.seconds(8); a.milliseconds(500); b = a.clone(); assert.equal(a.add('milliseconds', 50).milliseconds(), 550, 'Add milliseconds'); assert.equal(a.add('seconds', 1).seconds(), 9, 'Add seconds'); assert.equal(a.add('minutes', 1).minutes(), 8, 'Add minutes'); assert.equal(a.add('hours', 1).hours(), 7, 'Add hours'); assert.equal(a.add('days', 1).date(), 13, 'Add date'); assert.equal(a.add('weeks', 1).date(), 20, 'Add week'); assert.equal(a.add('months', 1).month(), 10, 'Add month'); assert.equal(a.add('years', 1).year(), 2012, 'Add year'); assert.equal(b.add('days', '01').date(), 13, 'Add date'); assert.equal(a.add('quarters', 1).month(), 1, 'Add quarter'); }); test('add string short reverse args', function (assert) { var a = moment(); test.expectedDeprecations('moment().add(period, number)'); a.year(2011); a.month(9); a.date(12); a.hours(6); a.minutes(7); a.seconds(8); a.milliseconds(500); assert.equal(a.add('ms', 50).milliseconds(), 550, 'Add milliseconds'); assert.equal(a.add('s', 1).seconds(), 9, 'Add seconds'); assert.equal(a.add('m', 1).minutes(), 8, 'Add minutes'); assert.equal(a.add('h', 1).hours(), 7, 'Add hours'); assert.equal(a.add('d', 1).date(), 13, 'Add date'); assert.equal(a.add('w', 1).date(), 20, 'Add week'); assert.equal(a.add('M', 1).month(), 10, 'Add month'); assert.equal(a.add('y', 1).year(), 2012, 'Add year'); assert.equal(a.add('Q', 1).month(), 1, 'Add quarter'); }); test('add string long', function (assert) { var a = moment(); a.year(2011); a.month(9); a.date(12); a.hours(6); a.minutes(7); a.seconds(8); a.milliseconds(500); assert.equal(a.add(50, 'millisecond').milliseconds(), 550, 'Add milliseconds'); assert.equal(a.add(1, 'second').seconds(), 9, 'Add seconds'); assert.equal(a.add(1, 'minute').minutes(), 8, 'Add minutes'); assert.equal(a.add(1, 'hour').hours(), 7, 'Add hours'); assert.equal(a.add(1, 'day').date(), 13, 'Add date'); assert.equal(a.add(1, 'week').date(), 20, 'Add week'); assert.equal(a.add(1, 'month').month(), 10, 'Add month'); assert.equal(a.add(1, 'year').year(), 2012, 'Add year'); assert.equal(a.add(1, 'quarter').month(), 1, 'Add quarter'); }); test('add string long singular', function (assert) { var a = moment(); a.year(2011); a.month(9); a.date(12); a.hours(6); a.minutes(7); a.seconds(8); a.milliseconds(500); assert.equal(a.add(50, 'milliseconds').milliseconds(), 550, 'Add milliseconds'); assert.equal(a.add(1, 'seconds').seconds(), 9, 'Add seconds'); assert.equal(a.add(1, 'minutes').minutes(), 8, 'Add minutes'); assert.equal(a.add(1, 'hours').hours(), 7, 'Add hours'); assert.equal(a.add(1, 'days').date(), 13, 'Add date'); assert.equal(a.add(1, 'weeks').date(), 20, 'Add week'); assert.equal(a.add(1, 'months').month(), 10, 'Add month'); assert.equal(a.add(1, 'years').year(), 2012, 'Add year'); assert.equal(a.add(1, 'quarters').month(), 1, 'Add quarter'); }); test('add string short', function (assert) { var a = moment(); a.year(2011); a.month(9); a.date(12); a.hours(6); a.minutes(7); a.seconds(8); a.milliseconds(500); assert.equal(a.add(50, 'ms').milliseconds(), 550, 'Add milliseconds'); assert.equal(a.add(1, 's').seconds(), 9, 'Add seconds'); assert.equal(a.add(1, 'm').minutes(), 8, 'Add minutes'); assert.equal(a.add(1, 'h').hours(), 7, 'Add hours'); assert.equal(a.add(1, 'd').date(), 13, 'Add date'); assert.equal(a.add(1, 'w').date(), 20, 'Add week'); assert.equal(a.add(1, 'M').month(), 10, 'Add month'); assert.equal(a.add(1, 'y').year(), 2012, 'Add year'); assert.equal(a.add(1, 'Q').month(), 1, 'Add quarter'); }); test('add strings string short reversed', function (assert) { var a = moment(); test.expectedDeprecations('moment().add(period, number)'); a.year(2011); a.month(9); a.date(12); a.hours(6); a.minutes(7); a.seconds(8); a.milliseconds(500); assert.equal(a.add('ms', '50').milliseconds(), 550, 'Add milliseconds'); assert.equal(a.add('s', '1').seconds(), 9, 'Add seconds'); assert.equal(a.add('m', '1').minutes(), 8, 'Add minutes'); assert.equal(a.add('h', '1').hours(), 7, 'Add hours'); assert.equal(a.add('d', '1').date(), 13, 'Add date'); assert.equal(a.add('w', '1').date(), 20, 'Add week'); assert.equal(a.add('M', '1').month(), 10, 'Add month'); assert.equal(a.add('y', '1').year(), 2012, 'Add year'); assert.equal(a.add('Q', '1').month(), 1, 'Add quarter'); }); test('subtract strings string short reversed', function (assert) { var a = moment(); test.expectedDeprecations('moment().subtract(period, number)'); a.year(2011); a.month(9); a.date(12); a.hours(6); a.minutes(7); a.seconds(8); a.milliseconds(500); assert.equal(a.subtract('ms', '50').milliseconds(), 450, 'Subtract milliseconds'); assert.equal(a.subtract('s', '1').seconds(), 7, 'Subtract seconds'); assert.equal(a.subtract('m', '1').minutes(), 6, 'Subtract minutes'); assert.equal(a.subtract('h', '1').hours(), 5, 'Subtract hours'); assert.equal(a.subtract('d', '1').date(), 11, 'Subtract date'); assert.equal(a.subtract('w', '1').date(), 4, 'Subtract week'); assert.equal(a.subtract('M', '1').month(), 8, 'Subtract month'); assert.equal(a.subtract('y', '1').year(), 2010, 'Subtract year'); assert.equal(a.subtract('Q', '1').month(), 5, 'Subtract quarter'); }); test('add strings string short', function (assert) { var a = moment(); a.year(2011); a.month(9); a.date(12); a.hours(6); a.minutes(7); a.seconds(8); a.milliseconds(500); assert.equal(a.add('50', 'ms').milliseconds(), 550, 'Add milliseconds'); assert.equal(a.add('1', 's').seconds(), 9, 'Add seconds'); assert.equal(a.add('1', 'm').minutes(), 8, 'Add minutes'); assert.equal(a.add('1', 'h').hours(), 7, 'Add hours'); assert.equal(a.add('1', 'd').date(), 13, 'Add date'); assert.equal(a.add('1', 'w').date(), 20, 'Add week'); assert.equal(a.add('1', 'M').month(), 10, 'Add month'); assert.equal(a.add('1', 'y').year(), 2012, 'Add year'); assert.equal(a.add('1', 'Q').month(), 1, 'Add quarter'); }); test('subtract strings string short', function (assert) { var a = moment(); a.year(2011); a.month(9); a.date(12); a.hours(6); a.minutes(7); a.seconds(8); a.milliseconds(500); assert.equal(a.subtract('50', 'ms').milliseconds(), 450, 'Subtract milliseconds'); assert.equal(a.subtract('1', 's').seconds(), 7, 'Subtract seconds'); assert.equal(a.subtract('1', 'm').minutes(), 6, 'Subtract minutes'); assert.equal(a.subtract('1', 'h').hours(), 5, 'Subtract hours'); assert.equal(a.subtract('1', 'd').date(), 11, 'Subtract date'); assert.equal(a.subtract('1', 'w').date(), 4, 'Subtract week'); assert.equal(a.subtract('1', 'M').month(), 8, 'Subtract month'); assert.equal(a.subtract('1', 'y').year(), 2010, 'Subtract year'); assert.equal(a.subtract('1', 'Q').month(), 5, 'Subtract quarter'); }); test('add across DST', function (assert) { // Detect Safari bug and bail. Hours on 13th March 2011 are shifted // with 1 ahead. if (new Date(2011, 2, 13, 5, 0, 0).getHours() !== 5) { expect(0); return; } var a = moment(new Date(2011, 2, 12, 5, 0, 0)), b = moment(new Date(2011, 2, 12, 5, 0, 0)), c = moment(new Date(2011, 2, 12, 5, 0, 0)), d = moment(new Date(2011, 2, 12, 5, 0, 0)), e = moment(new Date(2011, 2, 12, 5, 0, 0)); a.add(1, 'days'); b.add(24, 'hours'); c.add(1, 'months'); e.add(1, 'quarter'); assert.equal(a.hours(), 5, 'adding days over DST difference should result in the same hour'); if (b.isDST() && !d.isDST()) { assert.equal(b.hours(), 6, 'adding hours over DST difference should result in a different hour'); } else if (!b.isDST() && d.isDST()) { assert.equal(b.hours(), 4, 'adding hours over DST difference should result in a different hour'); } else { assert.equal(b.hours(), 5, 'adding hours over DST difference should result in a same hour if the timezone does not have daylight savings time'); } assert.equal(c.hours(), 5, 'adding months over DST difference should result in the same hour'); assert.equal(e.hours(), 5, 'adding quarters over DST difference should result in the same hour'); }); test('add decimal values of days and months', function (assert) { assert.equal(moment([2016,3,3]).add(1.5, 'days').date(), 5, 'adding 1.5 days is rounded to adding 2 day'); assert.equal(moment([2016,3,3]).add(-1.5, 'days').date(), 1, 'adding -1.5 days is rounded to adding -2 day'); assert.equal(moment([2016,3,1]).add(-1.5, 'days').date(), 30, 'adding -1.5 days on first of month wraps around'); assert.equal(moment([2016,3,3]).add(1.5, 'months').month(), 5, 'adding 1.5 months adds 2 months'); assert.equal(moment([2016,3,3]).add(-1.5, 'months').month(), 1, 'adding -1.5 months adds -2 months'); assert.equal(moment([2016,0,3]).add(-1.5, 'months').month(), 10, 'adding -1.5 months at start of year wraps back'); assert.equal(moment([2016,3,3]).subtract(1.5, 'days').date(),1, 'subtract 1.5 days is rounded to subtract 2 day'); assert.equal(moment([2016,3,2]).subtract(1.5, 'days').date(), 31, 'subtract 1.5 days subtracts 2 days'); assert.equal(moment([2016,1,1]).subtract(1.1, 'days').date(), 31, 'subtract 1.1 days wraps to previous month'); assert.equal(moment([2016,3,3]).subtract(-1.5, 'days').date(), 5, 'subtract -1.5 days is rounded to subtract -2 day'); assert.equal(moment([2016,3,30]).subtract(-1.5, 'days').date(), 2, 'subtract -1.5 days on last of month wraps around'); assert.equal(moment([2016,3,3]).subtract(1.5, 'months').month(), 1, 'subtract 1.5 months subtract 2 months'); assert.equal(moment([2016,3,3]).subtract(-1.5, 'months').month(), 5, 'subtract -1.5 months subtract -2 month'); assert.equal(moment([2016,11,31]).subtract(-1.5, 'months').month(),1, 'subtract -1.5 months at end of year wraps back'); assert.equal(moment([2016, 0,1]).add(1.5, 'years').format('YYYY-MM-DD'), '2017-07-01', 'add 1.5 years adds 1 year six months'); assert.equal(moment([2016, 0,1]).add(1.6, 'years').format('YYYY-MM-DD'), '2017-08-01', 'add 1.6 years becomes 1.6*12 = 19.2, round, 19 months'); assert.equal(moment([2016,0,1]).add(1.1, 'quarters').format('YYYY-MM-DD'), '2016-04-01', 'add 1.1 quarters 1.1*3=3.3, round, 3 months'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } // These tests are for locale independent features // locale dependent tests would be in locale test folder module('calendar'); test('passing a function', function (assert) { var a = moment().hours(13).minutes(0).seconds(0); assert.equal(moment(a).calendar(null, { 'sameDay': function () { return 'h:mmA'; } }), '1:00PM', 'should equate'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('create'); test('array', function (assert) { assert.ok(moment([2010]).toDate() instanceof Date, '[2010]'); assert.ok(moment([2010, 1]).toDate() instanceof Date, '[2010, 1]'); assert.ok(moment([2010, 1, 12]).toDate() instanceof Date, '[2010, 1, 12]'); assert.ok(moment([2010, 1, 12, 1]).toDate() instanceof Date, '[2010, 1, 12, 1]'); assert.ok(moment([2010, 1, 12, 1, 1]).toDate() instanceof Date, '[2010, 1, 12, 1, 1]'); assert.ok(moment([2010, 1, 12, 1, 1, 1]).toDate() instanceof Date, '[2010, 1, 12, 1, 1, 1]'); assert.ok(moment([2010, 1, 12, 1, 1, 1, 1]).toDate() instanceof Date, '[2010, 1, 12, 1, 1, 1, 1]'); assert.equal(+moment(new Date(2010, 1, 14, 15, 25, 50, 125)), +moment([2010, 1, 14, 15, 25, 50, 125]), 'constructing with array === constructing with new Date()'); }); test('array with invalid arguments', function (assert) { assert.ok(!moment([2010, null, null]).isValid(), '[2010, null, null]'); assert.ok(!moment([1945, null, null]).isValid(), '[1945, null, null] (pre-1970)'); }); test('array copying', function (assert) { var importantArray = [2009, 11]; moment(importantArray); assert.deepEqual(importantArray, [2009, 11], 'initializer should not mutate the original array'); }); test('object', function (assert) { var fmt = 'YYYY-MM-DD HH:mm:ss.SSS', tests = [ [{year: 2010}, '2010-01-01 00:00:00.000'], [{year: 2010, month: 1}, '2010-02-01 00:00:00.000'], [{year: 2010, month: 1, day: 12}, '2010-02-12 00:00:00.000'], [{year: 2010, month: 1, date: 12}, '2010-02-12 00:00:00.000'], [{year: 2010, month: 1, day: 12, hours: 1}, '2010-02-12 01:00:00.000'], [{year: 2010, month: 1, date: 12, hours: 1}, '2010-02-12 01:00:00.000'], [{year: 2010, month: 1, day: 12, hours: 1, minutes: 1}, '2010-02-12 01:01:00.000'], [{year: 2010, month: 1, date: 12, hours: 1, minutes: 1}, '2010-02-12 01:01:00.000'], [{year: 2010, month: 1, day: 12, hours: 1, minutes: 1, seconds: 1}, '2010-02-12 01:01:01.000'], [{year: 2010, month: 1, day: 12, hours: 1, minutes: 1, seconds: 1, milliseconds: 1}, '2010-02-12 01:01:01.001'], [{years: 2010, months: 1, days: 14, hours: 15, minutes: 25, seconds: 50, milliseconds: 125}, '2010-02-14 15:25:50.125'], [{year: 2010, month: 1, day: 14, hour: 15, minute: 25, second: 50, millisecond: 125}, '2010-02-14 15:25:50.125'], [{y: 2010, M: 1, d: 14, h: 15, m: 25, s: 50, ms: 125}, '2010-02-14 15:25:50.125'] ], i; for (i = 0; i < tests.length; ++i) { assert.equal(moment(tests[i][0]).format(fmt), tests[i][1]); } }); test('multi format array copying', function (assert) { var importantArray = ['MM/DD/YYYY', 'YYYY-MM-DD', 'MM-DD-YYYY']; moment('1999-02-13', importantArray); assert.deepEqual(importantArray, ['MM/DD/YYYY', 'YYYY-MM-DD', 'MM-DD-YYYY'], 'initializer should not mutate the original array'); }); test('number', function (assert) { assert.ok(moment(1000).toDate() instanceof Date, '1000'); assert.equal(moment(1000).valueOf(), 1000, 'asserting valueOf'); assert.equal(moment.utc(1000).valueOf(), 1000, 'asserting valueOf'); }); test('unix', function (assert) { assert.equal(moment.unix(1).valueOf(), 1000, '1 unix timestamp == 1000 Date.valueOf'); assert.equal(moment(1000).unix(), 1, '1000 Date.valueOf == 1 unix timestamp'); assert.equal(moment.unix(1000).valueOf(), 1000000, '1000 unix timestamp == 1000000 Date.valueOf'); assert.equal(moment(1500).unix(), 1, '1500 Date.valueOf == 1 unix timestamp'); assert.equal(moment(1900).unix(), 1, '1900 Date.valueOf == 1 unix timestamp'); assert.equal(moment(2100).unix(), 2, '2100 Date.valueOf == 2 unix timestamp'); assert.equal(moment(1333129333524).unix(), 1333129333, '1333129333524 Date.valueOf == 1333129333 unix timestamp'); assert.equal(moment(1333129333524000).unix(), 1333129333524, '1333129333524000 Date.valueOf == 1333129333524 unix timestamp'); }); test('date', function (assert) { assert.ok(moment(new Date()).toDate() instanceof Date, 'new Date()'); }); test('date mutation', function (assert) { var a = new Date(); assert.ok(moment(a).toDate() !== a, 'the date moment uses should not be the date passed in'); }); test('moment', function (assert) { assert.ok(moment(moment()).toDate() instanceof Date, 'moment(moment())'); assert.ok(moment(moment(moment())).toDate() instanceof Date, 'moment(moment(moment()))'); }); test('cloning moment should only copy own properties', function (assert) { assert.ok(!moment().clone().hasOwnProperty('month'), 'Should not clone prototype methods'); }); test('cloning moment works with weird clones', function (assert) { var extend = function (a, b) { var i; for (i in b) { a[i] = b[i]; } return a; }, now = moment(), nowu = moment.utc(); assert.equal(+extend({}, now).clone(), +now, 'cloning extend-ed now is now'); assert.equal(+extend({}, nowu).clone(), +nowu, 'cloning extend-ed utc now is utc now'); }); test('cloning respects moment.momentProperties', function (assert) { var m = moment(); assert.equal(m.clone()._special, undefined, 'cloning ignores extra properties'); m._special = 'bacon'; moment.momentProperties.push('_special'); assert.equal(m.clone()._special, 'bacon', 'cloning respects momentProperties'); moment.momentProperties.pop(); }); test('undefined', function (assert) { assert.ok(moment().toDate() instanceof Date, 'undefined'); }); test('iso with bad input', function (assert) { assert.ok(!moment('a', moment.ISO_8601).isValid(), 'iso parsing with invalid string'); assert.ok(!moment('a', moment.ISO_8601, true).isValid(), 'iso parsing with invalid string, strict'); }); test('iso format 24hrs', function (assert) { assert.equal(moment('2014-01-01T24:00:00.000').format('YYYY-MM-DD[T]HH:mm:ss.SSS'), '2014-01-02T00:00:00.000', 'iso format with 24:00 localtime'); assert.equal(moment.utc('2014-01-01T24:00:00.000').format('YYYY-MM-DD[T]HH:mm:ss.SSS'), '2014-01-02T00:00:00.000', 'iso format with 24:00 utc'); }); test('string without format - json', function (assert) { assert.equal(moment('Date(1325132654000)').valueOf(), 1325132654000, 'Date(1325132654000)'); assert.equal(moment('Date(-1325132654000)').valueOf(), -1325132654000, 'Date(-1325132654000)'); assert.equal(moment('/Date(1325132654000)/').valueOf(), 1325132654000, '/Date(1325132654000)/'); assert.equal(moment('/Date(1325132654000+0700)/').valueOf(), 1325132654000, '/Date(1325132654000+0700)/'); assert.equal(moment('/Date(1325132654000-0700)/').valueOf(), 1325132654000, '/Date(1325132654000-0700)/'); }); test('string with format dropped am/pm bug', function (assert) { moment.locale('en'); assert.equal(moment('05/1/2012 12:25:00', 'MM/DD/YYYY h:m:s a').format('MM/DD/YYYY'), '05/01/2012', 'should not break if am/pm is left off from the parsing tokens'); assert.equal(moment('05/1/2012 12:25:00 am', 'MM/DD/YYYY h:m:s a').format('MM/DD/YYYY'), '05/01/2012', 'should not break if am/pm is left off from the parsing tokens'); assert.equal(moment('05/1/2012 12:25:00 pm', 'MM/DD/YYYY h:m:s a').format('MM/DD/YYYY'), '05/01/2012', 'should not break if am/pm is left off from the parsing tokens'); assert.ok(moment('05/1/2012 12:25:00', 'MM/DD/YYYY h:m:s a').isValid()); assert.ok(moment('05/1/2012 12:25:00 am', 'MM/DD/YYYY h:m:s a').isValid()); assert.ok(moment('05/1/2012 12:25:00 pm', 'MM/DD/YYYY h:m:s a').isValid()); }); test('empty string with formats', function (assert) { assert.equal(moment('', 'MM').format('YYYY-MM-DD HH:mm:ss'), 'Invalid date'); assert.equal(moment(' ', 'MM').format('YYYY-MM-DD HH:mm:ss'), 'Invalid date'); assert.equal(moment(' ', 'DD').format('YYYY-MM-DD HH:mm:ss'), 'Invalid date'); assert.equal(moment(' ', ['MM', 'DD']).format('YYYY-MM-DD HH:mm:ss'), 'Invalid date'); assert.ok(!moment('', 'MM').isValid()); assert.ok(!moment(' ', 'MM').isValid()); assert.ok(!moment(' ', 'DD').isValid()); assert.ok(!moment(' ', ['MM', 'DD']).isValid()); }); test('defaulting to current date', function (assert) { var now = moment(); assert.equal(moment('12:13:14', 'hh:mm:ss').format('YYYY-MM-DD hh:mm:ss'), now.clone().hour(12).minute(13).second(14).format('YYYY-MM-DD hh:mm:ss'), 'given only time default to current date'); assert.equal(moment('05', 'DD').format('YYYY-MM-DD'), now.clone().date(5).format('YYYY-MM-DD'), 'given day of month default to current month, year'); assert.equal(moment('05', 'MM').format('YYYY-MM-DD'), now.clone().month(4).date(1).format('YYYY-MM-DD'), 'given month default to current year'); assert.equal(moment('1996', 'YYYY').format('YYYY-MM-DD'), now.clone().year(1996).month(0).date(1).format('YYYY-MM-DD'), 'given year do not default'); }); test('matching am/pm', function (assert) { assert.equal(moment('2012-09-03T03:00PM', 'YYYY-MM-DDThh:mmA').format('YYYY-MM-DDThh:mmA'), '2012-09-03T03:00PM', 'am/pm should parse correctly for PM'); assert.equal(moment('2012-09-03T03:00P.M.', 'YYYY-MM-DDThh:mmA').format('YYYY-MM-DDThh:mmA'), '2012-09-03T03:00PM', 'am/pm should parse correctly for P.M.'); assert.equal(moment('2012-09-03T03:00P', 'YYYY-MM-DDThh:mmA').format('YYYY-MM-DDThh:mmA'), '2012-09-03T03:00PM', 'am/pm should parse correctly for P'); assert.equal(moment('2012-09-03T03:00pm', 'YYYY-MM-DDThh:mmA').format('YYYY-MM-DDThh:mmA'), '2012-09-03T03:00PM', 'am/pm should parse correctly for pm'); assert.equal(moment('2012-09-03T03:00p.m.', 'YYYY-MM-DDThh:mmA').format('YYYY-MM-DDThh:mmA'), '2012-09-03T03:00PM', 'am/pm should parse correctly for p.m.'); assert.equal(moment('2012-09-03T03:00p', 'YYYY-MM-DDThh:mmA').format('YYYY-MM-DDThh:mmA'), '2012-09-03T03:00PM', 'am/pm should parse correctly for p'); assert.equal(moment('2012-09-03T03:00AM', 'YYYY-MM-DDThh:mmA').format('YYYY-MM-DDThh:mmA'), '2012-09-03T03:00AM', 'am/pm should parse correctly for AM'); assert.equal(moment('2012-09-03T03:00A.M.', 'YYYY-MM-DDThh:mmA').format('YYYY-MM-DDThh:mmA'), '2012-09-03T03:00AM', 'am/pm should parse correctly for A.M.'); assert.equal(moment('2012-09-03T03:00A', 'YYYY-MM-DDThh:mmA').format('YYYY-MM-DDThh:mmA'), '2012-09-03T03:00AM', 'am/pm should parse correctly for A'); assert.equal(moment('2012-09-03T03:00am', 'YYYY-MM-DDThh:mmA').format('YYYY-MM-DDThh:mmA'), '2012-09-03T03:00AM', 'am/pm should parse correctly for am'); assert.equal(moment('2012-09-03T03:00a.m.', 'YYYY-MM-DDThh:mmA').format('YYYY-MM-DDThh:mmA'), '2012-09-03T03:00AM', 'am/pm should parse correctly for a.m.'); assert.equal(moment('2012-09-03T03:00a', 'YYYY-MM-DDThh:mmA').format('YYYY-MM-DDThh:mmA'), '2012-09-03T03:00AM', 'am/pm should parse correctly for a'); assert.equal(moment('5:00p.m.March 4 2012', 'h:mmAMMMM D YYYY').format('YYYY-MM-DDThh:mmA'), '2012-03-04T05:00PM', 'am/pm should parse correctly before month names'); }); test('string with format', function (assert) { moment.locale('en'); var a = [ ['YYYY-Q', '2014-4'], ['MM-DD-YYYY', '12-02-1999'], ['DD-MM-YYYY', '12-02-1999'], ['DD/MM/YYYY', '12/02/1999'], ['DD_MM_YYYY', '12_02_1999'], ['DD:MM:YYYY', '12:02:1999'], ['D-M-YY', '2-2-99'], ['YY', '99'], ['DDD-YYYY', '300-1999'], ['DD-MM-YYYY h:m:s', '12-02-1999 2:45:10'], ['DD-MM-YYYY h:m:s a', '12-02-1999 2:45:10 am'], ['DD-MM-YYYY h:m:s a', '12-02-1999 2:45:10 pm'], ['h:mm a', '12:00 pm'], ['h:mm a', '12:30 pm'], ['h:mm a', '12:00 am'], ['h:mm a', '12:30 am'], ['HH:mm', '12:00'], ['YYYY-MM-DDTHH:mm:ss', '2011-11-11T11:11:11'], ['MM-DD-YYYY [M]', '12-02-1999 M'], ['ddd MMM DD HH:mm:ss YYYY', 'Tue Apr 07 22:52:51 2009'], ['HH:mm:ss', '12:00:00'], ['HH:mm:ss', '12:30:00'], ['HH:mm:ss', '00:00:00'], ['HH:mm:ss S', '00:30:00 1'], ['HH:mm:ss SS', '00:30:00 12'], ['HH:mm:ss SSS', '00:30:00 123'], ['HH:mm:ss S', '00:30:00 7'], ['HH:mm:ss SS', '00:30:00 78'], ['HH:mm:ss SSS', '00:30:00 789'], ['X', '1234567890'], ['x', '1234567890123'], ['LT', '12:30 AM'], ['LTS', '12:30:29 AM'], ['L', '09/02/1999'], ['l', '9/2/1999'], ['LL', 'September 2, 1999'], ['ll', 'Sep 2, 1999'], ['LLL', 'September 2, 1999 12:30 AM'], ['lll', 'Sep 2, 1999 12:30 AM'], ['LLLL', 'Thursday, September 2, 1999 12:30 AM'], ['llll', 'Thu, Sep 2, 1999 12:30 AM'] ], m, i; for (i = 0; i < a.length; i++) { m = moment(a[i][1], a[i][0]); assert.ok(m.isValid()); assert.equal(m.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('2 digit year with YYYY format', function (assert) { assert.equal(moment('9/2/99', 'D/M/YYYY').format('DD/MM/YYYY'), '09/02/1999', 'D/M/YYYY ---> 9/2/99'); assert.equal(moment('9/2/1999', 'D/M/YYYY').format('DD/MM/YYYY'), '09/02/1999', 'D/M/YYYY ---> 9/2/1999'); assert.equal(moment('9/2/68', 'D/M/YYYY').format('DD/MM/YYYY'), '09/02/2068', 'D/M/YYYY ---> 9/2/68'); assert.equal(moment('9/2/69', 'D/M/YYYY').format('DD/MM/YYYY'), '09/02/1969', 'D/M/YYYY ---> 9/2/69'); }); test('unix timestamp format', function (assert) { var formats = ['X', 'X.S', 'X.SS', 'X.SSS'], i, format; for (i = 0; i < formats.length; i++) { format = formats[i]; assert.equal(moment('1234567890', format).valueOf(), 1234567890 * 1000, format + ' matches timestamp without milliseconds'); assert.equal(moment('1234567890.1', format).valueOf(), 1234567890 * 1000 + 100, format + ' matches timestamp with deciseconds'); assert.equal(moment('1234567890.12', format).valueOf(), 1234567890 * 1000 + 120, format + ' matches timestamp with centiseconds'); assert.equal(moment('1234567890.123', format).valueOf(), 1234567890 * 1000 + 123, format + ' matches timestamp with milliseconds'); } }); test('unix offset milliseconds', function (assert) { assert.equal(moment('1234567890123', 'x').valueOf(), 1234567890123, 'x matches unix offset in milliseconds'); }); test('milliseconds format', function (assert) { assert.equal(moment('1', 'S').get('ms'), 100, 'deciseconds'); // assert.equal(moment('10', 'S', true).isValid(), false, 'deciseconds with two digits'); // assert.equal(moment('1', 'SS', true).isValid(), false, 'centiseconds with one digits'); assert.equal(moment('12', 'SS').get('ms'), 120, 'centiseconds'); // assert.equal(moment('123', 'SS', true).isValid(), false, 'centiseconds with three digits'); assert.equal(moment('123', 'SSS').get('ms'), 123, 'milliseconds'); assert.equal(moment('1234', 'SSSS').get('ms'), 123, 'milliseconds with SSSS'); assert.equal(moment('123456789101112', 'SSSS').get('ms'), 123, 'milliseconds with SSSS'); }); test('string with format no separators', function (assert) { moment.locale('en'); var a = [ ['MMDDYYYY', '12021999'], ['DDMMYYYY', '12021999'], ['YYYYMMDD', '19991202'], ['DDMMMYYYY', '10Sep2001'] ], i; for (i = 0; i < a.length; i++) { assert.equal(moment(a[i][1], a[i][0]).format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); test('string with format (timezone)', function (assert) { assert.equal(moment('5 -0700', 'H ZZ').toDate().getUTCHours(), 12, 'parse hours \'5 -0700\' ---> \'H ZZ\''); assert.equal(moment('5 -07:00', 'H Z').toDate().getUTCHours(), 12, 'parse hours \'5 -07:00\' ---> \'H Z\''); assert.equal(moment('5 -0730', 'H ZZ').toDate().getUTCMinutes(), 30, 'parse hours \'5 -0730\' ---> \'H ZZ\''); assert.equal(moment('5 -07:30', 'H Z').toDate().getUTCMinutes(), 30, 'parse hours \'5 -07:0\' ---> \'H Z\''); assert.equal(moment('5 +0100', 'H ZZ').toDate().getUTCHours(), 4, 'parse hours \'5 +0100\' ---> \'H ZZ\''); assert.equal(moment('5 +01:00', 'H Z').toDate().getUTCHours(), 4, 'parse hours \'5 +01:00\' ---> \'H Z\''); assert.equal(moment('5 +0130', 'H ZZ').toDate().getUTCMinutes(), 30, 'parse hours \'5 +0130\' ---> \'H ZZ\''); assert.equal(moment('5 +01:30', 'H Z').toDate().getUTCMinutes(), 30, 'parse hours \'5 +01:30\' ---> \'H Z\''); }); test('string with format (timezone offset)', function (assert) { var a, b, c, d, e, f; a = new Date(Date.UTC(2011, 0, 1, 1)); b = moment('2011 1 1 0 -01:00', 'YYYY MM DD HH Z'); assert.equal(a.getHours(), b.hours(), 'date created with utc == parsed string with timezone offset'); assert.equal(+a, +b, 'date created with utc == parsed string with timezone offset'); c = moment('2011 2 1 10 -05:00', 'YYYY MM DD HH Z'); d = moment('2011 2 1 8 -07:00', 'YYYY MM DD HH Z'); assert.equal(c.hours(), d.hours(), '10 am central time == 8 am pacific time'); e = moment.utc('Fri, 20 Jul 2012 17:15:00', 'ddd, DD MMM YYYY HH:mm:ss'); f = moment.utc('Fri, 20 Jul 2012 10:15:00 -0700', 'ddd, DD MMM YYYY HH:mm:ss ZZ'); assert.equal(e.hours(), f.hours(), 'parse timezone offset in utc'); }); test('string with timezone around start of year', function (assert) { assert.equal(moment('2000-01-01T00:00:00.000+01:00').toISOString(), '1999-12-31T23:00:00.000Z', '+1:00 around 2000'); assert.equal(moment('2000-01-01T00:00:00.000-01:00').toISOString(), '2000-01-01T01:00:00.000Z', '-1:00 around 2000'); assert.equal(moment('1970-01-01T00:00:00.000+01:00').toISOString(), '1969-12-31T23:00:00.000Z', '+1:00 around 1970'); assert.equal(moment('1970-01-01T00:00:00.000-01:00').toISOString(), '1970-01-01T01:00:00.000Z', '-1:00 around 1970'); assert.equal(moment('1200-01-01T00:00:00.000+01:00').toISOString(), '1199-12-31T23:00:00.000Z', '+1:00 around 1200'); assert.equal(moment('1200-01-01T00:00:00.000-01:00').toISOString(), '1200-01-01T01:00:00.000Z', '-1:00 around 1200'); }); test('string with array of formats', function (assert) { assert.equal(moment('11-02-1999', ['MM-DD-YYYY', 'DD-MM-YYYY']).format('MM DD YYYY'), '11 02 1999', 'switching month and day'); assert.equal(moment('02-11-1999', ['MM/DD/YYYY', 'YYYY MM DD', 'MM-DD-YYYY']).format('MM DD YYYY'), '02 11 1999', 'year last'); assert.equal(moment('1999-02-11', ['MM/DD/YYYY', 'YYYY MM DD', 'MM-DD-YYYY']).format('MM DD YYYY'), '02 11 1999', 'year first'); assert.equal(moment('02-11-1999', ['MM/DD/YYYY', 'YYYY MM DD']).format('MM DD YYYY'), '02 11 1999', 'year last'); assert.equal(moment('1999-02-11', ['MM/DD/YYYY', 'YYYY MM DD']).format('MM DD YYYY'), '02 11 1999', 'year first'); assert.equal(moment('02-11-1999', ['YYYY MM DD', 'MM/DD/YYYY']).format('MM DD YYYY'), '02 11 1999', 'year last'); assert.equal(moment('1999-02-11', ['YYYY MM DD', 'MM/DD/YYYY']).format('MM DD YYYY'), '02 11 1999', 'year first'); assert.equal(moment('13-11-1999', ['MM/DD/YYYY', 'DD/MM/YYYY']).format('MM DD YYYY'), '11 13 1999', 'second must be month'); assert.equal(moment('11-13-1999', ['MM/DD/YYYY', 'DD/MM/YYYY']).format('MM DD YYYY'), '11 13 1999', 'first must be month'); assert.equal(moment('01-02-2000', ['MM/DD/YYYY', 'DD/MM/YYYY']).format('MM DD YYYY'), '01 02 2000', 'either can be a month, month first format'); assert.equal(moment('02-01-2000', ['DD/MM/YYYY', 'MM/DD/YYYY']).format('MM DD YYYY'), '01 02 2000', 'either can be a month, day first format'); assert.equal(moment('11-02-10', ['MM/DD/YY', 'YY MM DD', 'DD-MM-YY']).format('MM DD YYYY'), '02 11 2010', 'all unparsed substrings have influence on format penalty'); assert.equal(moment('11-02-10', ['MM-DD-YY HH:mm', 'YY MM DD']).format('MM DD YYYY'), '02 10 2011', 'prefer formats without extra tokens'); assert.equal(moment('11-02-10 junk', ['MM-DD-YY', 'YY.MM.DD junk']).format('MM DD YYYY'), '02 10 2011', 'prefer formats that dont result in extra characters'); assert.equal(moment('11-22-10', ['YY-MM-DD', 'YY-DD-MM']).format('MM DD YYYY'), '10 22 2011', 'prefer valid results'); assert.equal(moment('gibberish', ['YY-MM-DD', 'YY-DD-MM']).format('MM DD YYYY'), 'Invalid date', 'doest throw for invalid strings'); assert.equal(moment('gibberish', []).format('MM DD YYYY'), 'Invalid date', 'doest throw for an empty array'); //path_to_url assert.equal(moment( 'System Administrator and Database Assistant (7/1/2011), System Administrator and Database Assistant (7/1/2011), Database Coordinator (7/1/2011), Vice President (7/1/2011), System Administrator and Database Assistant (5/31/2012), Database Coordinator (7/1/2012), System Administrator and Database Assistant (7/1/2013)', ['MM/DD/YYYY', 'MM-DD-YYYY', 'YYYY-MM-DD', 'YYYY-MM-DDTHH:mm:ssZ']) .format('YYYY-MM-DD'), '2011-07-01', 'Works for long strings'); assert.equal(moment('11-02-10', ['MM.DD.YY', 'DD-MM-YY']).format('MM DD YYYY'), '02 11 2010', 'escape RegExp special characters on comparing'); assert.equal(moment('13-10-98', ['DD MM YY', 'DD MM YYYY'])._f, 'DD MM YY', 'use two digit year'); assert.equal(moment('13-10-1998', ['DD MM YY', 'DD MM YYYY'])._f, 'DD MM YYYY', 'use four digit year'); assert.equal(moment('01', ['MM', 'DD'])._f, 'MM', 'Should use first valid format'); }); test('string with array of formats + ISO', function (assert) { assert.equal(moment('1994', [moment.ISO_8601, 'MM', 'HH:mm', 'YYYY']).year(), 1994, 'iso: assert parse YYYY'); assert.equal(moment('17:15', [moment.ISO_8601, 'MM', 'HH:mm', 'YYYY']).hour(), 17, 'iso: assert parse HH:mm (1)'); assert.equal(moment('17:15', [moment.ISO_8601, 'MM', 'HH:mm', 'YYYY']).minutes(), 15, 'iso: assert parse HH:mm (2)'); assert.equal(moment('06', [moment.ISO_8601, 'MM', 'HH:mm', 'YYYY']).month(), 6 - 1, 'iso: assert parse MM'); assert.equal(moment('2012-06-01', [moment.ISO_8601, 'MM', 'HH:mm', 'YYYY']).parsingFlags().iso, true, 'iso: assert parse iso'); assert.equal(moment('2014-05-05', [moment.ISO_8601, 'YYYY-MM-DD']).parsingFlags().iso, true, 'iso: edge case array precedence iso'); assert.equal(moment('2014-05-05', ['YYYY-MM-DD', moment.ISO_8601]).parsingFlags().iso, false, 'iso: edge case array precedence not iso'); }); test('string with format - years', function (assert) { assert.equal(moment('67', 'YY').format('YYYY'), '2067', '67 > 2067'); assert.equal(moment('68', 'YY').format('YYYY'), '2068', '68 > 2068'); assert.equal(moment('69', 'YY').format('YYYY'), '1969', '69 > 1969'); assert.equal(moment('70', 'YY').format('YYYY'), '1970', '70 > 1970'); }); test('implicit cloning', function (assert) { var momentA = moment([2011, 10, 10]), momentB = moment(momentA); momentA.month(5); assert.equal(momentB.month(), 10, 'Calling moment() on a moment will create a clone'); assert.equal(momentA.month(), 5, 'Calling moment() on a moment will create a clone'); }); test('explicit cloning', function (assert) { var momentA = moment([2011, 10, 10]), momentB = momentA.clone(); momentA.month(5); assert.equal(momentB.month(), 10, 'Calling moment() on a moment will create a clone'); assert.equal(momentA.month(), 5, 'Calling moment() on a moment will create a clone'); }); test('cloning carrying over utc mode', function (assert) { assert.equal(moment().local().clone()._isUTC, false, 'An explicit cloned local moment should have _isUTC == false'); assert.equal(moment().utc().clone()._isUTC, true, 'An cloned utc moment should have _isUTC == true'); assert.equal(moment().clone()._isUTC, false, 'An explicit cloned local moment should have _isUTC == false'); assert.equal(moment.utc().clone()._isUTC, true, 'An explicit cloned utc moment should have _isUTC == true'); assert.equal(moment(moment().local())._isUTC, false, 'An implicit cloned local moment should have _isUTC == false'); assert.equal(moment(moment().utc())._isUTC, true, 'An implicit cloned utc moment should have _isUTC == true'); assert.equal(moment(moment())._isUTC, false, 'An implicit cloned local moment should have _isUTC == false'); assert.equal(moment(moment.utc())._isUTC, true, 'An implicit cloned utc moment should have _isUTC == true'); }); test('parsing iso', function (assert) { var offset = moment([2011, 9, 8]).utcOffset(), pad = function (input) { if (input < 10) { return '0' + input; } return '' + input; }, hourOffset = (offset > 0 ? Math.floor(offset / 60) : Math.ceil(offset / 60)), minOffset = offset - (hourOffset * 60), tz = (offset >= 0) ? '+' + pad(hourOffset) + ':' + pad(minOffset) : '-' + pad(-hourOffset) + ':' + pad(-minOffset), tz2 = tz.replace(':', ''), tz3 = tz2.slice(0, 3), //Tz3 removes minutes digit so will break the tests when parsed if they all use the same minutes digit minutesForTz3 = pad((4 + minOffset) % 60), minute = pad(4 + minOffset), formats = [ ['2011-10-08', '2011-10-08T00:00:00.000' + tz], ['2011-10-08T18', '2011-10-08T18:00:00.000' + tz], ['2011-10-08T18:04', '2011-10-08T18:04:00.000' + tz], ['2011-10-08T18:04:20', '2011-10-08T18:04:20.000' + tz], ['2011-10-08T18:04' + tz, '2011-10-08T18:04:00.000' + tz], ['2011-10-08T18:04:20' + tz, '2011-10-08T18:04:20.000' + tz], ['2011-10-08T18:04' + tz2, '2011-10-08T18:04:00.000' + tz], ['2011-10-08T18:04:20' + tz2, '2011-10-08T18:04:20.000' + tz], ['2011-10-08T18:04' + tz3, '2011-10-08T18:' + minutesForTz3 + ':00.000' + tz], ['2011-10-08T18:04:20' + tz3, '2011-10-08T18:' + minutesForTz3 + ':20.000' + tz], ['2011-10-08T18:04:20.1' + tz2, '2011-10-08T18:04:20.100' + tz], ['2011-10-08T18:04:20.11' + tz2, '2011-10-08T18:04:20.110' + tz], ['2011-10-08T18:04:20.111' + tz2, '2011-10-08T18:04:20.111' + tz], ['2011-10-08 18', '2011-10-08T18:00:00.000' + tz], ['2011-10-08 18:04', '2011-10-08T18:04:00.000' + tz], ['2011-10-08 18:04:20', '2011-10-08T18:04:20.000' + tz], ['2011-10-08 18:04' + tz, '2011-10-08T18:04:00.000' + tz], ['2011-10-08 18:04:20' + tz, '2011-10-08T18:04:20.000' + tz], ['2011-10-08 18:04' + tz2, '2011-10-08T18:04:00.000' + tz], ['2011-10-08 18:04:20' + tz2, '2011-10-08T18:04:20.000' + tz], ['2011-10-08 18:04' + tz3, '2011-10-08T18:' + minutesForTz3 + ':00.000' + tz], ['2011-10-08 18:04:20' + tz3, '2011-10-08T18:' + minutesForTz3 + ':20.000' + tz], ['2011-10-08 18:04:20.1' + tz2, '2011-10-08T18:04:20.100' + tz], ['2011-10-08 18:04:20.11' + tz2, '2011-10-08T18:04:20.110' + tz], ['2011-10-08 18:04:20.111' + tz2, '2011-10-08T18:04:20.111' + tz], ['2011-W40', '2011-10-03T00:00:00.000' + tz], ['2011-W40-6', '2011-10-08T00:00:00.000' + tz], ['2011-W40-6T18', '2011-10-08T18:00:00.000' + tz], ['2011-W40-6T18:04', '2011-10-08T18:04:00.000' + tz], ['2011-W40-6T18:04:20', '2011-10-08T18:04:20.000' + tz], ['2011-W40-6T18:04' + tz, '2011-10-08T18:04:00.000' + tz], ['2011-W40-6T18:04:20' + tz, '2011-10-08T18:04:20.000' + tz], ['2011-W40-6T18:04' + tz2, '2011-10-08T18:04:00.000' + tz], ['2011-W40-6T18:04:20' + tz2, '2011-10-08T18:04:20.000' + tz], ['2011-W40-6T18:04' + tz3, '2011-10-08T18:' + minutesForTz3 + ':00.000' + tz], ['2011-W40-6T18:04:20' + tz3, '2011-10-08T18:' + minutesForTz3 + ':20.000' + tz], ['2011-W40-6T18:04:20.1' + tz2, '2011-10-08T18:04:20.100' + tz], ['2011-W40-6T18:04:20.11' + tz2, '2011-10-08T18:04:20.110' + tz], ['2011-W40-6T18:04:20.111' + tz2, '2011-10-08T18:04:20.111' + tz], ['2011-W40-6 18', '2011-10-08T18:00:00.000' + tz], ['2011-W40-6 18:04', '2011-10-08T18:04:00.000' + tz], ['2011-W40-6 18:04:20', '2011-10-08T18:04:20.000' + tz], ['2011-W40-6 18:04' + tz, '2011-10-08T18:04:00.000' + tz], ['2011-W40-6 18:04:20' + tz, '2011-10-08T18:04:20.000' + tz], ['2011-W40-6 18:04' + tz2, '2011-10-08T18:04:00.000' + tz], ['2011-W40-6 18:04:20' + tz2, '2011-10-08T18:04:20.000' + tz], ['2011-W40-6 18:04' + tz3, '2011-10-08T18:' + minutesForTz3 + ':00.000' + tz], ['2011-W40-6 18:04:20' + tz3, '2011-10-08T18:' + minutesForTz3 + ':20.000' + tz], ['2011-W40-6 18:04:20.1' + tz2, '2011-10-08T18:04:20.100' + tz], ['2011-W40-6 18:04:20.11' + tz2, '2011-10-08T18:04:20.110' + tz], ['2011-W40-6 18:04:20.111' + tz2, '2011-10-08T18:04:20.111' + tz], ['2011-281', '2011-10-08T00:00:00.000' + tz], ['2011-281T18', '2011-10-08T18:00:00.000' + tz], ['2011-281T18:04', '2011-10-08T18:04:00.000' + tz], ['2011-281T18:04:20', '2011-10-08T18:04:20.000' + tz], ['2011-281T18:04' + tz, '2011-10-08T18:04:00.000' + tz], ['2011-281T18:04:20' + tz, '2011-10-08T18:04:20.000' + tz], ['2011-281T18:04' + tz2, '2011-10-08T18:04:00.000' + tz], ['2011-281T18:04:20' + tz2, '2011-10-08T18:04:20.000' + tz], ['2011-281T18:04' + tz3, '2011-10-08T18:' + minutesForTz3 + ':00.000' + tz], ['2011-281T18:04:20' + tz3, '2011-10-08T18:' + minutesForTz3 + ':20.000' + tz], ['2011-281T18:04:20.1' + tz2, '2011-10-08T18:04:20.100' + tz], ['2011-281T18:04:20.11' + tz2, '2011-10-08T18:04:20.110' + tz], ['2011-281T18:04:20.111' + tz2, '2011-10-08T18:04:20.111' + tz], ['2011-281 18', '2011-10-08T18:00:00.000' + tz], ['2011-281 18:04', '2011-10-08T18:04:00.000' + tz], ['2011-281 18:04:20', '2011-10-08T18:04:20.000' + tz], ['2011-281 18:04' + tz, '2011-10-08T18:04:00.000' + tz], ['2011-281 18:04:20' + tz, '2011-10-08T18:04:20.000' + tz], ['2011-281 18:04' + tz2, '2011-10-08T18:04:00.000' + tz], ['2011-281 18:04:20' + tz2, '2011-10-08T18:04:20.000' + tz], ['2011-281 18:04' + tz3, '2011-10-08T18:' + minutesForTz3 + ':00.000' + tz], ['2011-281 18:04:20' + tz3, '2011-10-08T18:' + minutesForTz3 + ':20.000' + tz], ['2011-281 18:04:20.1' + tz2, '2011-10-08T18:04:20.100' + tz], ['2011-281 18:04:20.11' + tz2, '2011-10-08T18:04:20.110' + tz], ['2011-281 18:04:20.111' + tz2, '2011-10-08T18:04:20.111' + tz], ['20111008T18', '2011-10-08T18:00:00.000' + tz], ['20111008T1804', '2011-10-08T18:04:00.000' + tz], ['20111008T180420', '2011-10-08T18:04:20.000' + tz], ['20111008T1804' + tz, '2011-10-08T18:04:00.000' + tz], ['20111008T180420' + tz, '2011-10-08T18:04:20.000' + tz], ['20111008T1804' + tz2, '2011-10-08T18:04:00.000' + tz], ['20111008T180420' + tz2, '2011-10-08T18:04:20.000' + tz], ['20111008T1804' + tz3, '2011-10-08T18:' + minutesForTz3 + ':00.000' + tz], ['20111008T180420' + tz3, '2011-10-08T18:' + minutesForTz3 + ':20.000' + tz], ['20111008T180420,1' + tz2, '2011-10-08T18:04:20.100' + tz], ['20111008T180420,11' + tz2, '2011-10-08T18:04:20.110' + tz], ['20111008T180420,111' + tz2, '2011-10-08T18:04:20.111' + tz], ['20111008 18', '2011-10-08T18:00:00.000' + tz], ['20111008 1804', '2011-10-08T18:04:00.000' + tz], ['20111008 180420', '2011-10-08T18:04:20.000' + tz], ['20111008 1804' + tz, '2011-10-08T18:04:00.000' + tz], ['20111008 180420' + tz, '2011-10-08T18:04:20.000' + tz], ['20111008 1804' + tz2, '2011-10-08T18:04:00.000' + tz], ['20111008 180420' + tz2, '2011-10-08T18:04:20.000' + tz], ['20111008 1804' + tz3, '2011-10-08T18:' + minutesForTz3 + ':00.000' + tz], ['20111008 180420' + tz3, '2011-10-08T18:' + minutesForTz3 + ':20.000' + tz], ['20111008 180420,1' + tz2, '2011-10-08T18:04:20.100' + tz], ['20111008 180420,11' + tz2, '2011-10-08T18:04:20.110' + tz], ['20111008 180420,111' + tz2, '2011-10-08T18:04:20.111' + tz], ['2011W40', '2011-10-03T00:00:00.000' + tz], ['2011W406', '2011-10-08T00:00:00.000' + tz], ['2011W406T18', '2011-10-08T18:00:00.000' + tz], ['2011W406T1804', '2011-10-08T18:04:00.000' + tz], ['2011W406T180420', '2011-10-08T18:04:20.000' + tz], ['2011W406 1804' + tz2, '2011-10-08T18:04:00.000' + tz], ['2011W406T1804' + tz, '2011-10-08T18:04:00.000' + tz], ['2011W406T180420' + tz, '2011-10-08T18:04:20.000' + tz], ['2011W406T1804' + tz2, '2011-10-08T18:04:00.000' + tz], ['2011W406T180420' + tz2, '2011-10-08T18:04:20.000' + tz], ['2011W406T1804' + tz3, '2011-10-08T18:' + minutesForTz3 + ':00.000' + tz], ['2011W406T180420' + tz3, '2011-10-08T18:' + minutesForTz3 + ':20.000' + tz], ['2011W406T180420,1' + tz2, '2011-10-08T18:04:20.100' + tz], ['2011W406T180420,11' + tz2, '2011-10-08T18:04:20.110' + tz], ['2011W406T180420,111' + tz2, '2011-10-08T18:04:20.111' + tz], ['2011W406 18', '2011-10-08T18:00:00.000' + tz], ['2011W406 1804', '2011-10-08T18:04:00.000' + tz], ['2011W406 180420', '2011-10-08T18:04:20.000' + tz], ['2011W406 1804' + tz, '2011-10-08T18:04:00.000' + tz], ['2011W406 180420' + tz, '2011-10-08T18:04:20.000' + tz], ['2011W406 180420' + tz2, '2011-10-08T18:04:20.000' + tz], ['2011W406 1804' + tz3, '2011-10-08T18:' + minutesForTz3 + ':00.000' + tz], ['2011W406 180420' + tz3, '2011-10-08T18:' + minutesForTz3 + ':20.000' + tz], ['2011W406 180420,1' + tz2, '2011-10-08T18:04:20.100' + tz], ['2011W406 180420,11' + tz2, '2011-10-08T18:04:20.110' + tz], ['2011W406 180420,111' + tz2, '2011-10-08T18:04:20.111' + tz], ['2011281', '2011-10-08T00:00:00.000' + tz], ['2011281T18', '2011-10-08T18:00:00.000' + tz], ['2011281T1804', '2011-10-08T18:04:00.000' + tz], ['2011281T180420', '2011-10-08T18:04:20.000' + tz], ['2011281T1804' + tz, '2011-10-08T18:04:00.000' + tz], ['2011281T180420' + tz, '2011-10-08T18:04:20.000' + tz], ['2011281T1804' + tz2, '2011-10-08T18:04:00.000' + tz], ['2011281T180420' + tz2, '2011-10-08T18:04:20.000' + tz], ['2011281T1804' + tz3, '2011-10-08T18:' + minutesForTz3 + ':00.000' + tz], ['2011281T180420' + tz3, '2011-10-08T18:' + minutesForTz3 + ':20.000' + tz], ['2011281T180420,1' + tz2, '2011-10-08T18:04:20.100' + tz], ['2011281T180420,11' + tz2, '2011-10-08T18:04:20.110' + tz], ['2011281T180420,111' + tz2, '2011-10-08T18:04:20.111' + tz], ['2011281 18', '2011-10-08T18:00:00.000' + tz], ['2011281 1804', '2011-10-08T18:04:00.000' + tz], ['2011281 180420', '2011-10-08T18:04:20.000' + tz], ['2011281 1804' + tz, '2011-10-08T18:04:00.000' + tz], ['2011281 180420' + tz, '2011-10-08T18:04:20.000' + tz], ['2011281 1804' + tz2, '2011-10-08T18:04:00.000' + tz], ['2011281 180420' + tz2, '2011-10-08T18:04:20.000' + tz], ['2011281 1804' + tz3, '2011-10-08T18:' + minutesForTz3 + ':00.000' + tz], ['2011281 180420' + tz3, '2011-10-08T18:' + minutesForTz3 + ':20.000' + tz], ['2011281 180420,1' + tz2, '2011-10-08T18:04:20.100' + tz], ['2011281 180420,11' + tz2, '2011-10-08T18:04:20.110' + tz], ['2011281 180420,111' + tz2, '2011-10-08T18:04:20.111' + tz] ], i; for (i = 0; i < formats.length; i++) { assert.equal(moment(formats[i][0]).format('YYYY-MM-DDTHH:mm:ss.SSSZ'), formats[i][1], 'moment should be able to parse ISO ' + formats[i][0]); assert.equal(moment(formats[i][0], moment.ISO_8601).format('YYYY-MM-DDTHH:mm:ss.SSSZ'), formats[i][1], 'moment should be able to parse specified ISO ' + formats[i][0]); assert.equal(moment(formats[i][0], moment.ISO_8601, true).format('YYYY-MM-DDTHH:mm:ss.SSSZ'), formats[i][1], 'moment should be able to parse specified strict ISO ' + formats[i][0]); } }); test('non iso 8601 strings', function (assert) { assert.ok(!moment('2015-10T10:15', moment.ISO_8601, true).isValid(), 'incomplete date with time'); assert.ok(!moment('2015-W10T10:15', moment.ISO_8601, true).isValid(), 'incomplete week date with time'); assert.ok(!moment('201510', moment.ISO_8601, true).isValid(), 'basic YYYYMM is not allowed'); assert.ok(!moment('2015W10T1015', moment.ISO_8601, true).isValid(), 'incomplete week date with time (basic)'); assert.ok(!moment('2015-10-08T1015', moment.ISO_8601, true).isValid(), 'mixing extended and basic format'); assert.ok(!moment('20151008T10:15', moment.ISO_8601, true).isValid(), 'mixing basic and extended format'); }); test('parsing iso week year/week/weekday', function (assert) { assert.equal(moment.utc('2007-W01').format(), '2007-01-01T00:00:00Z', '2008 week 1 (1st Jan Mon)'); assert.equal(moment.utc('2008-W01').format(), '2007-12-31T00:00:00Z', '2008 week 1 (1st Jan Tue)'); assert.equal(moment.utc('2003-W01').format(), '2002-12-30T00:00:00Z', '2008 week 1 (1st Jan Wed)'); assert.equal(moment.utc('2009-W01').format(), '2008-12-29T00:00:00Z', '2009 week 1 (1st Jan Thu)'); assert.equal(moment.utc('2010-W01').format(), '2010-01-04T00:00:00Z', '2010 week 1 (1st Jan Fri)'); assert.equal(moment.utc('2011-W01').format(), '2011-01-03T00:00:00Z', '2011 week 1 (1st Jan Sat)'); assert.equal(moment.utc('2012-W01').format(), '2012-01-02T00:00:00Z', '2012 week 1 (1st Jan Sun)'); }); test('parsing week year/week/weekday (dow 1, doy 4)', function (assert) { moment.locale('dow:1,doy:4', {week: {dow: 1, doy: 4}}); assert.equal(moment.utc('2007-01', 'gggg-ww').format(), '2007-01-01T00:00:00Z', '2007 week 1 (1st Jan Mon)'); assert.equal(moment.utc('2008-01', 'gggg-ww').format(), '2007-12-31T00:00:00Z', '2008 week 1 (1st Jan Tue)'); assert.equal(moment.utc('2003-01', 'gggg-ww').format(), '2002-12-30T00:00:00Z', '2003 week 1 (1st Jan Wed)'); assert.equal(moment.utc('2009-01', 'gggg-ww').format(), '2008-12-29T00:00:00Z', '2009 week 1 (1st Jan Thu)'); assert.equal(moment.utc('2010-01', 'gggg-ww').format(), '2010-01-04T00:00:00Z', '2010 week 1 (1st Jan Fri)'); assert.equal(moment.utc('2011-01', 'gggg-ww').format(), '2011-01-03T00:00:00Z', '2011 week 1 (1st Jan Sat)'); assert.equal(moment.utc('2012-01', 'gggg-ww').format(), '2012-01-02T00:00:00Z', '2012 week 1 (1st Jan Sun)'); moment.defineLocale('dow:1,doy:4', null); }); test('parsing week year/week/weekday (dow 1, doy 7)', function (assert) { moment.locale('dow:1,doy:7', {week: {dow: 1, doy: 7}}); assert.equal(moment.utc('2007-01', 'gggg-ww').format(), '2007-01-01T00:00:00Z', '2007 week 1 (1st Jan Mon)'); assert.equal(moment.utc('2008-01', 'gggg-ww').format(), '2007-12-31T00:00:00Z', '2008 week 1 (1st Jan Tue)'); assert.equal(moment.utc('2003-01', 'gggg-ww').format(), '2002-12-30T00:00:00Z', '2003 week 1 (1st Jan Wed)'); assert.equal(moment.utc('2009-01', 'gggg-ww').format(), '2008-12-29T00:00:00Z', '2009 week 1 (1st Jan Thu)'); assert.equal(moment.utc('2010-01', 'gggg-ww').format(), '2009-12-28T00:00:00Z', '2010 week 1 (1st Jan Fri)'); assert.equal(moment.utc('2011-01', 'gggg-ww').format(), '2010-12-27T00:00:00Z', '2011 week 1 (1st Jan Sat)'); assert.equal(moment.utc('2012-01', 'gggg-ww').format(), '2011-12-26T00:00:00Z', '2012 week 1 (1st Jan Sun)'); moment.defineLocale('dow:1,doy:7', null); }); test('parsing week year/week/weekday (dow 0, doy 6)', function (assert) { moment.locale('dow:0,doy:6', {week: {dow: 0, doy: 6}}); assert.equal(moment.utc('2007-01', 'gggg-ww').format(), '2006-12-31T00:00:00Z', '2007 week 1 (1st Jan Mon)'); assert.equal(moment.utc('2008-01', 'gggg-ww').format(), '2007-12-30T00:00:00Z', '2008 week 1 (1st Jan Tue)'); assert.equal(moment.utc('2003-01', 'gggg-ww').format(), '2002-12-29T00:00:00Z', '2003 week 1 (1st Jan Wed)'); assert.equal(moment.utc('2009-01', 'gggg-ww').format(), '2008-12-28T00:00:00Z', '2009 week 1 (1st Jan Thu)'); assert.equal(moment.utc('2010-01', 'gggg-ww').format(), '2009-12-27T00:00:00Z', '2010 week 1 (1st Jan Fri)'); assert.equal(moment.utc('2011-01', 'gggg-ww').format(), '2010-12-26T00:00:00Z', '2011 week 1 (1st Jan Sat)'); assert.equal(moment.utc('2012-01', 'gggg-ww').format(), '2012-01-01T00:00:00Z', '2012 week 1 (1st Jan Sun)'); moment.defineLocale('dow:0,doy:6', null); }); test('parsing week year/week/weekday (dow 6, doy 12)', function (assert) { moment.locale('dow:6,doy:12', {week: {dow: 6, doy: 12}}); assert.equal(moment.utc('2007-01', 'gggg-ww').format(), '2006-12-30T00:00:00Z', '2007 week 1 (1st Jan Mon)'); assert.equal(moment.utc('2008-01', 'gggg-ww').format(), '2007-12-29T00:00:00Z', '2008 week 1 (1st Jan Tue)'); assert.equal(moment.utc('2003-01', 'gggg-ww').format(), '2002-12-28T00:00:00Z', '2003 week 1 (1st Jan Wed)'); assert.equal(moment.utc('2009-01', 'gggg-ww').format(), '2008-12-27T00:00:00Z', '2009 week 1 (1st Jan Thu)'); assert.equal(moment.utc('2010-01', 'gggg-ww').format(), '2009-12-26T00:00:00Z', '2010 week 1 (1st Jan Fri)'); assert.equal(moment.utc('2011-01', 'gggg-ww').format(), '2011-01-01T00:00:00Z', '2011 week 1 (1st Jan Sat)'); assert.equal(moment.utc('2012-01', 'gggg-ww').format(), '2011-12-31T00:00:00Z', '2012 week 1 (1st Jan Sun)'); moment.defineLocale('dow:6,doy:12', null); }); test('parsing ISO with Z', function (assert) { var i, mom, formats = [ ['2011-10-08T18:04', '2011-10-08T18:04:00.000'], ['2011-10-08T18:04:20', '2011-10-08T18:04:20.000'], ['2011-10-08T18:04:20.1', '2011-10-08T18:04:20.100'], ['2011-10-08T18:04:20.11', '2011-10-08T18:04:20.110'], ['2011-10-08T18:04:20.111', '2011-10-08T18:04:20.111'], ['2011-W40-6T18', '2011-10-08T18:00:00.000'], ['2011-W40-6T18:04', '2011-10-08T18:04:00.000'], ['2011-W40-6T18:04:20', '2011-10-08T18:04:20.000'], ['2011-W40-6T18:04:20.1', '2011-10-08T18:04:20.100'], ['2011-W40-6T18:04:20.11', '2011-10-08T18:04:20.110'], ['2011-W40-6T18:04:20.111', '2011-10-08T18:04:20.111'], ['2011-281T18', '2011-10-08T18:00:00.000'], ['2011-281T18:04', '2011-10-08T18:04:00.000'], ['2011-281T18:04:20', '2011-10-08T18:04:20.000'], ['2011-281T18:04:20', '2011-10-08T18:04:20.000'], ['2011-281T18:04:20.1', '2011-10-08T18:04:20.100'], ['2011-281T18:04:20.11', '2011-10-08T18:04:20.110'], ['2011-281T18:04:20.111', '2011-10-08T18:04:20.111'] ]; for (i = 0; i < formats.length; i++) { mom = moment(formats[i][0] + 'Z').utc(); assert.equal(mom.format('YYYY-MM-DDTHH:mm:ss.SSS'), formats[i][1], 'moment should be able to parse ISO in UTC ' + formats[i][0] + 'Z'); mom = moment(formats[i][0] + ' Z').utc(); assert.equal(mom.format('YYYY-MM-DDTHH:mm:ss.SSS'), formats[i][1], 'moment should be able to parse ISO in UTC ' + formats[i][0] + ' Z'); } }); test('parsing iso with T', function (assert) { assert.equal(moment('2011-10-08T18')._f, 'YYYY-MM-DDTHH', 'should include \'T\' in the format'); assert.equal(moment('2011-10-08T18:20')._f, 'YYYY-MM-DDTHH:mm', 'should include \'T\' in the format'); assert.equal(moment('2011-10-08T18:20:13')._f, 'YYYY-MM-DDTHH:mm:ss', 'should include \'T\' in the format'); assert.equal(moment('2011-10-08T18:20:13.321')._f, 'YYYY-MM-DDTHH:mm:ss.SSSS', 'should include \'T\' in the format'); assert.equal(moment('2011-10-08 18')._f, 'YYYY-MM-DD HH', 'should not include \'T\' in the format'); assert.equal(moment('2011-10-08 18:20')._f, 'YYYY-MM-DD HH:mm', 'should not include \'T\' in the format'); assert.equal(moment('2011-10-08 18:20:13')._f, 'YYYY-MM-DD HH:mm:ss', 'should not include \'T\' in the format'); assert.equal(moment('2011-10-08 18:20:13.321')._f, 'YYYY-MM-DD HH:mm:ss.SSSS', 'should not include \'T\' in the format'); }); test('parsing iso Z timezone', function (assert) { var i, formats = [ ['2011-10-08T18:04Z', '2011-10-08T18:04:00.000+00:00'], ['2011-10-08T18:04:20Z', '2011-10-08T18:04:20.000+00:00'], ['2011-10-08T18:04:20.111Z', '2011-10-08T18:04:20.111+00:00'] ]; for (i = 0; i < formats.length; i++) { assert.equal(moment.utc(formats[i][0]).format('YYYY-MM-DDTHH:mm:ss.SSSZ'), formats[i][1], 'moment should be able to parse ISO ' + formats[i][0]); } }); test('parsing iso Z timezone into local', function (assert) { var m = moment('2011-10-08T18:04:20.111Z'); assert.equal(m.utc().format('YYYY-MM-DDTHH:mm:ss.SSS'), '2011-10-08T18:04:20.111', 'moment should be able to parse ISO 2011-10-08T18:04:20.111Z'); }); test('parsing iso with more subsecond precision digits', function (assert) { assert.equal(moment.utc('2013-07-31T22:00:00.0000000Z').format(), '2013-07-31T22:00:00Z', 'more than 3 subsecond digits'); }); test('null or empty', function (assert) { assert.equal(moment('').isValid(), false, 'moment(\'\') is not valid'); assert.equal(moment(null).isValid(), false, 'moment(null) is not valid'); assert.equal(moment(null, 'YYYY-MM-DD').isValid(), false, 'moment(\'\', \'format\') is not valid'); assert.equal(moment('', 'YYYY-MM-DD').isValid(), false, 'moment(\'\', \'format\') is not valid'); assert.equal(moment.utc('').isValid(), false, 'moment.utc(\'\') is not valid'); assert.equal(moment.utc(null).isValid(), false, 'moment.utc(null) is not valid'); assert.equal(moment.utc(null, 'YYYY-MM-DD').isValid(), false, 'moment.utc(null) is not valid'); assert.equal(moment.utc('', 'YYYY-MM-DD').isValid(), false, 'moment.utc(\'\', \'YYYY-MM-DD\') is not valid'); }); test('first century', function (assert) { assert.equal(moment([0, 0, 1]).format('YYYY-MM-DD'), '0000-01-01', 'Year AD 0'); assert.equal(moment([99, 0, 1]).format('YYYY-MM-DD'), '0099-01-01', 'Year AD 99'); assert.equal(moment([999, 0, 1]).format('YYYY-MM-DD'), '0999-01-01', 'Year AD 999'); assert.equal(moment('0 1 1', 'YYYY MM DD').format('YYYY-MM-DD'), '0000-01-01', 'Year AD 0'); assert.equal(moment('999 1 1', 'YYYY MM DD').format('YYYY-MM-DD'), '0999-01-01', 'Year AD 999'); assert.equal(moment('0 1 1', 'YYYYY MM DD').format('YYYYY-MM-DD'), '00000-01-01', 'Year AD 0'); assert.equal(moment('99 1 1', 'YYYYY MM DD').format('YYYYY-MM-DD'), '00099-01-01', 'Year AD 99'); assert.equal(moment('999 1 1', 'YYYYY MM DD').format('YYYYY-MM-DD'), '00999-01-01', 'Year AD 999'); }); test('six digit years', function (assert) { assert.equal(moment([-270000, 0, 1]).format('YYYYY-MM-DD'), '-270000-01-01', 'format BC 270,001'); assert.equal(moment([270000, 0, 1]).format('YYYYY-MM-DD'), '270000-01-01', 'format AD 270,000'); assert.equal(moment('-270000-01-01', 'YYYYY-MM-DD').toDate().getFullYear(), -270000, 'parse BC 270,001'); assert.equal(moment('270000-01-01', 'YYYYY-MM-DD').toDate().getFullYear(), 270000, 'parse AD 270,000'); assert.equal(moment('+270000-01-01', 'YYYYY-MM-DD').toDate().getFullYear(), 270000, 'parse AD +270,000'); assert.equal(moment.utc('-270000-01-01', 'YYYYY-MM-DD').toDate().getUTCFullYear(), -270000, 'parse utc BC 270,001'); assert.equal(moment.utc('270000-01-01', 'YYYYY-MM-DD').toDate().getUTCFullYear(), 270000, 'parse utc AD 270,000'); assert.equal(moment.utc('+270000-01-01', 'YYYYY-MM-DD').toDate().getUTCFullYear(), 270000, 'parse utc AD +270,000'); }); test('negative four digit years', function (assert) { assert.equal(moment('-1000-01-01', 'YYYYY-MM-DD').toDate().getFullYear(), -1000, 'parse BC 1,001'); assert.equal(moment.utc('-1000-01-01', 'YYYYY-MM-DD').toDate().getUTCFullYear(), -1000, 'parse utc BC 1,001'); }); test('strict parsing', function (assert) { assert.equal(moment('2014-', 'YYYY-Q', true).isValid(), false, 'fail missing quarter'); assert.equal(moment('2012-05', 'YYYY-MM', true).format('YYYY-MM'), '2012-05', 'parse correct string'); assert.equal(moment(' 2012-05', 'YYYY-MM', true).isValid(), false, 'fail on extra whitespace'); assert.equal(moment('foo 2012-05', '[foo] YYYY-MM', true).format('YYYY-MM'), '2012-05', 'handle fixed text'); assert.equal(moment('2012 05', 'YYYY-MM', true).isValid(), false, 'fail on different separator'); assert.equal(moment('2012 05', 'YYYY MM DD', true).isValid(), false, 'fail on too many tokens'); assert.equal(moment('05 30 2010', ['DD MM YYYY', 'MM DD YYYY'], true).format('MM DD YYYY'), '05 30 2010', 'array with bad date'); assert.equal(moment('05 30 2010', ['', 'MM DD YYYY'], true).format('MM DD YYYY'), '05 30 2010', 'array with invalid format'); assert.equal(moment('05 30 2010', [' DD MM YYYY', 'MM DD YYYY'], true).format('MM DD YYYY'), '05 30 2010', 'array with non-matching format'); assert.equal(moment('2010.*...', 'YYYY.*', true).isValid(), false, 'invalid format with regex chars'); assert.equal(moment('2010.*', 'YYYY.*', true).year(), 2010, 'valid format with regex chars'); assert.equal(moment('.*2010.*', '.*YYYY.*', true).year(), 2010, 'valid format with regex chars on both sides'); //strict tokens assert.equal(moment('-5-05-25', 'YYYY-MM-DD', true).isValid(), false, 'invalid negative year'); assert.equal(moment('2-05-25', 'YYYY-MM-DD', true).isValid(), false, 'invalid one-digit year'); assert.equal(moment('20-05-25', 'YYYY-MM-DD', true).isValid(), false, 'invalid two-digit year'); assert.equal(moment('201-05-25', 'YYYY-MM-DD', true).isValid(), false, 'invalid three-digit year'); assert.equal(moment('2010-05-25', 'YYYY-MM-DD', true).isValid(), true, 'valid four-digit year'); assert.equal(moment('22010-05-25', 'YYYY-MM-DD', true).isValid(), false, 'invalid five-digit year'); assert.equal(moment('12-05-25', 'YY-MM-DD', true).isValid(), true, 'valid two-digit year'); assert.equal(moment('2012-05-25', 'YY-MM-DD', true).isValid(), false, 'invalid four-digit year'); assert.equal(moment('-5-05-25', 'Y-MM-DD', true).isValid(), true, 'valid negative year'); assert.equal(moment('2-05-25', 'Y-MM-DD', true).isValid(), true, 'valid one-digit year'); assert.equal(moment('20-05-25', 'Y-MM-DD', true).isValid(), true, 'valid two-digit year'); assert.equal(moment('201-05-25', 'Y-MM-DD', true).isValid(), true, 'valid three-digit year'); assert.equal(moment('2012-5-25', 'YYYY-M-DD', true).isValid(), true, 'valid one-digit month'); assert.equal(moment('2012-5-25', 'YYYY-MM-DD', true).isValid(), false, 'invalid one-digit month'); assert.equal(moment('2012-05-25', 'YYYY-M-DD', true).isValid(), true, 'valid one-digit month'); assert.equal(moment('2012-05-25', 'YYYY-MM-DD', true).isValid(), true, 'valid one-digit month'); assert.equal(moment('2012-05-2', 'YYYY-MM-D', true).isValid(), true, 'valid one-digit day'); assert.equal(moment('2012-05-2', 'YYYY-MM-DD', true).isValid(), false, 'invalid one-digit day'); assert.equal(moment('2012-05-02', 'YYYY-MM-D', true).isValid(), true, 'valid two-digit day'); assert.equal(moment('2012-05-02', 'YYYY-MM-DD', true).isValid(), true, 'valid two-digit day'); assert.equal(moment('+002012-05-25', 'YYYYY-MM-DD', true).isValid(), true, 'valid six-digit year'); assert.equal(moment('+2012-05-25', 'YYYYY-MM-DD', true).isValid(), false, 'invalid four-digit year'); //thse are kinda pointless, but they should work as expected assert.equal(moment('1', 'S', true).isValid(), true, 'valid one-digit milisecond'); assert.equal(moment('12', 'S', true).isValid(), false, 'invalid two-digit milisecond'); assert.equal(moment('123', 'S', true).isValid(), false, 'invalid three-digit milisecond'); assert.equal(moment('1', 'SS', true).isValid(), false, 'invalid one-digit milisecond'); assert.equal(moment('12', 'SS', true).isValid(), true, 'valid two-digit milisecond'); assert.equal(moment('123', 'SS', true).isValid(), false, 'invalid three-digit milisecond'); assert.equal(moment('1', 'SSS', true).isValid(), false, 'invalid one-digit milisecond'); assert.equal(moment('12', 'SSS', true).isValid(), false, 'invalid two-digit milisecond'); assert.equal(moment('123', 'SSS', true).isValid(), true, 'valid three-digit milisecond'); // strict parsing respects month length assert.ok(moment('1 January 2000', 'D MMMM YYYY', true).isValid(), 'capital long-month + MMMM'); assert.ok(!moment('1 January 2000', 'D MMM YYYY', true).isValid(), 'capital long-month + MMM'); assert.ok(!moment('1 Jan 2000', 'D MMMM YYYY', true).isValid(), 'capital short-month + MMMM'); assert.ok(moment('1 Jan 2000', 'D MMM YYYY', true).isValid(), 'capital short-month + MMM'); assert.ok(moment('1 january 2000', 'D MMMM YYYY', true).isValid(), 'lower long-month + MMMM'); assert.ok(!moment('1 january 2000', 'D MMM YYYY', true).isValid(), 'lower long-month + MMM'); assert.ok(!moment('1 jan 2000', 'D MMMM YYYY', true).isValid(), 'lower short-month + MMMM'); assert.ok(moment('1 jan 2000', 'D MMM YYYY', true).isValid(), 'lower short-month + MMM'); }); test('parsing into a locale', function (assert) { moment.defineLocale('parselocale', { months : 'one_two_three_four_five_six_seven_eight_nine_ten_eleven_twelve'.split('_'), monthsShort : 'one_two_three_four_five_six_seven_eight_nine_ten_eleven_twelve'.split('_') }); moment.locale('en'); assert.equal(moment('2012 seven', 'YYYY MMM', 'parselocale').month(), 6, 'should be able to parse in a specific locale'); moment.locale('parselocale'); assert.equal(moment('2012 july', 'YYYY MMM', 'en').month(), 6, 'should be able to parse in a specific locale'); moment.defineLocale('parselocale', null); }); function getVerifier(test) { return function (input, format, expected, description, asymetrical) { var m = moment(input, format); test.equal(m.format('YYYY MM DD'), expected, 'compare: ' + description); //test round trip if (!asymetrical) { test.equal(m.format(format), input, 'round trip: ' + description); } }; } test('parsing week and weekday information', function (assert) { var ver = getVerifier(assert); // year ver('12', 'gg', '2012 01 01', 'week-year two digits'); ver('2012', 'gggg', '2012 01 01', 'week-year four digits'); ver('99', 'gg', '1998 12 27', 'week-year two digits previous year'); ver('1999', 'gggg', '1998 12 27', 'week-year four digits previous year'); ver('99', 'GG', '1999 01 04', 'iso week-year two digits'); ver('1999', 'GGGG', '1999 01 04', 'iso week-year four digits'); ver('13', 'GG', '2012 12 31', 'iso week-year two digits previous year'); ver('2013', 'GGGG', '2012 12 31', 'iso week-year four digits previous year'); // year + week ver('1999 37', 'gggg w', '1999 09 05', 'week'); ver('1999 37', 'gggg ww', '1999 09 05', 'week double'); ver('1999 37', 'GGGG W', '1999 09 13', 'iso week'); ver('1999 37', 'GGGG WW', '1999 09 13', 'iso week double'); ver('1999 37 4', 'GGGG WW E', '1999 09 16', 'iso day'); ver('1999 37 04', 'GGGG WW E', '1999 09 16', 'iso day wide', true); ver('1999 37 4', 'gggg ww e', '1999 09 09', 'day'); ver('1999 37 04', 'gggg ww e', '1999 09 09', 'day wide', true); // year + week + day ver('1999 37 4', 'gggg ww d', '1999 09 09', 'd'); ver('1999 37 Th', 'gggg ww dd', '1999 09 09', 'dd'); ver('1999 37 Thu', 'gggg ww ddd', '1999 09 09', 'ddd'); ver('1999 37 Thursday', 'gggg ww dddd', '1999 09 09', 'dddd'); // lower-order only assert.equal(moment('22', 'ww').week(), 22, 'week sets the week by itself'); assert.equal(moment('22', 'ww').weekYear(), moment().weekYear(), 'week keeps this year'); assert.equal(moment('2012 22', 'YYYY ww').weekYear(), 2012, 'week keeps parsed year'); assert.equal(moment('22', 'WW').isoWeek(), 22, 'iso week sets the week by itself'); assert.equal(moment('2012 22', 'YYYY WW').weekYear(), 2012, 'iso week keeps parsed year'); assert.equal(moment('22', 'WW').isoWeekYear(), moment().isoWeekYear(), 'iso week keeps this year'); // order ver('6 2013 2', 'e gggg w', '2013 01 12', 'order doesn\'t matter'); ver('6 2013 2', 'E GGGG W', '2013 01 12', 'iso order doesn\'t matter'); //can parse other stuff too assert.equal(moment('1999-W37-4 3:30', 'GGGG-[W]WW-E HH:mm').format('YYYY MM DD HH:mm'), '1999 09 16 03:30', 'parsing weeks and hours'); // In safari, all years before 1300 are shifted back with one day. // path_to_url if (new Date('1300-01-01').getUTCFullYear() === 1300) { // Years less than 100 ver('0098-06', 'GGGG-WW', '0098 02 03', 'small years work', true); } }); test('parsing localized weekdays', function (assert) { var ver = getVerifier(assert); try { moment.locale('dow:1,doy:4', { 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('_'), week: {dow: 1, doy: 4} }); ver('1999 37 4', 'GGGG WW E', '1999 09 16', 'iso ignores locale'); ver('1999 37 7', 'GGGG WW E', '1999 09 19', 'iso ignores locale'); ver('1999 37 0', 'gggg ww e', '1999 09 13', 'localized e uses local doy and dow: 0 = monday'); ver('1999 37 4', 'gggg ww e', '1999 09 17', 'localized e uses local doy and dow: 4 = friday'); ver('1999 37 1', 'gggg ww d', '1999 09 13', 'localized d uses 0-indexed days: 1 = monday'); ver('1999 37 Lu', 'gggg ww dd', '1999 09 13', 'localized d uses 0-indexed days: Mo'); ver('1999 37 lun.', 'gggg ww ddd', '1999 09 13', 'localized d uses 0-indexed days: Mon'); ver('1999 37 lundi', 'gggg ww dddd', '1999 09 13', 'localized d uses 0-indexed days: Monday'); ver('1999 37 4', 'gggg ww d', '1999 09 16', 'localized d uses 0-indexed days: 4'); //sunday goes at the end of the week ver('1999 37 0', 'gggg ww d', '1999 09 19', 'localized d uses 0-indexed days: 0 = sund'); ver('1999 37 Di', 'gggg ww dd', '1999 09 19', 'localized d uses 0-indexed days: 0 = sund'); } finally { moment.defineLocale('dow:1,doy:4', null); moment.locale('en'); } }); test('parsing with customized two-digit year', function (assert) { var original = moment.parseTwoDigitYear; try { assert.equal(moment('68', 'YY').year(), 2068); assert.equal(moment('69', 'YY').year(), 1969); moment.parseTwoDigitYear = function (input) { return +input + (+input > 30 ? 1900 : 2000); }; assert.equal(moment('68', 'YY').year(), 1968); assert.equal(moment('67', 'YY').year(), 1967); assert.equal(moment('31', 'YY').year(), 1931); assert.equal(moment('30', 'YY').year(), 2030); } finally { moment.parseTwoDigitYear = original; } }); test('array with strings', function (assert) { assert.equal(moment(['2014', '7', '31']).isValid(), true, 'string array + isValid'); }); test('object with strings', function (assert) { assert.equal(moment({year: '2014', month: '7', day: '31'}).isValid(), true, 'string object + isValid'); }); test('utc with array of formats', function (assert) { assert.equal(moment.utc('2014-01-01', ['YYYY-MM-DD', 'YYYY-MM']).format(), '2014-01-01T00:00:00Z', 'moment.utc works with array of formats'); }); test('parsing invalid string weekdays', function (assert) { assert.equal(false, moment('a', 'dd').isValid(), 'dd with invalid weekday, non-strict'); assert.equal(false, moment('a', 'dd', true).isValid(), 'dd with invalid weekday, strict'); assert.equal(false, moment('a', 'ddd').isValid(), 'ddd with invalid weekday, non-strict'); assert.equal(false, moment('a', 'ddd', true).isValid(), 'ddd with invalid weekday, strict'); assert.equal(false, moment('a', 'dddd').isValid(), 'dddd with invalid weekday, non-strict'); assert.equal(false, moment('a', 'dddd', true).isValid(), 'dddd with invalid weekday, strict'); }); test('milliseconds', function (assert) { assert.equal(moment('1', 'S').millisecond(), 100); assert.equal(moment('12', 'SS').millisecond(), 120); assert.equal(moment('123', 'SSS').millisecond(), 123); assert.equal(moment('1234', 'SSSS').millisecond(), 123); assert.equal(moment('12345', 'SSSSS').millisecond(), 123); assert.equal(moment('123456', 'SSSSSS').millisecond(), 123); assert.equal(moment('1234567', 'SSSSSSS').millisecond(), 123); assert.equal(moment('12345678', 'SSSSSSSS').millisecond(), 123); assert.equal(moment('123456789', 'SSSSSSSSS').millisecond(), 123); }); test('hmm', function (assert) { assert.equal(moment('123', 'hmm', true).format('HH:mm:ss'), '01:23:00', '123 with hmm'); assert.equal(moment('123a', 'hmmA', true).format('HH:mm:ss'), '01:23:00', '123a with hmmA'); assert.equal(moment('123p', 'hmmA', true).format('HH:mm:ss'), '13:23:00', '123p with hmmA'); assert.equal(moment('1234', 'hmm', true).format('HH:mm:ss'), '12:34:00', '1234 with hmm'); assert.equal(moment('1234a', 'hmmA', true).format('HH:mm:ss'), '00:34:00', '1234a with hmmA'); assert.equal(moment('1234p', 'hmmA', true).format('HH:mm:ss'), '12:34:00', '1234p with hmmA'); assert.equal(moment('12345', 'hmmss', true).format('HH:mm:ss'), '01:23:45', '12345 with hmmss'); assert.equal(moment('12345a', 'hmmssA', true).format('HH:mm:ss'), '01:23:45', '12345a with hmmssA'); assert.equal(moment('12345p', 'hmmssA', true).format('HH:mm:ss'), '13:23:45', '12345p with hmmssA'); assert.equal(moment('112345', 'hmmss', true).format('HH:mm:ss'), '11:23:45', '112345 with hmmss'); assert.equal(moment('112345a', 'hmmssA', true).format('HH:mm:ss'), '11:23:45', '112345a with hmmssA'); assert.equal(moment('112345p', 'hmmssA', true).format('HH:mm:ss'), '23:23:45', '112345p with hmmssA'); assert.equal(moment('023', 'Hmm', true).format('HH:mm:ss'), '00:23:00', '023 with Hmm'); assert.equal(moment('123', 'Hmm', true).format('HH:mm:ss'), '01:23:00', '123 with Hmm'); assert.equal(moment('1234', 'Hmm', true).format('HH:mm:ss'), '12:34:00', '1234 with Hmm'); assert.equal(moment('1534', 'Hmm', true).format('HH:mm:ss'), '15:34:00', '1234 with Hmm'); assert.equal(moment('12345', 'Hmmss', true).format('HH:mm:ss'), '01:23:45', '12345 with Hmmss'); assert.equal(moment('112345', 'Hmmss', true).format('HH:mm:ss'), '11:23:45', '112345 with Hmmss'); assert.equal(moment('172345', 'Hmmss', true).format('HH:mm:ss'), '17:23:45', '112345 with Hmmss'); }); test('Y token', function (assert) { assert.equal(moment('1-1-2010', 'M-D-Y', true).year(), 2010, 'parsing Y'); }); test('parsing flags retain parsed date parts', function (assert) { var a = moment('10 p', 'hh:mm a'); assert.equal(a.parsingFlags().parsedDateParts[3], 10, 'parsed 10 as the hour'); assert.equal(a.parsingFlags().parsedDateParts[0], undefined, 'year was not parsed'); assert.equal(a.parsingFlags().meridiem, 'p', 'meridiem flag was added'); var b = moment('10:30', ['MMDDYY', 'HH:mm']); assert.equal(b.parsingFlags().parsedDateParts[3], 10, 'multiple format parshing matched hour'); assert.equal(b.parsingFlags().parsedDateParts[0], undefined, 'array is properly copied, no residual data from first token parse'); }); test('parsing only meridiem results in invalid date', function (assert) { assert.ok(!moment('alkj', 'hh:mm a').isValid(), 'because an a token is used, a meridiem will be parsed but nothing else was so invalid'); assert.ok(moment('02:30 p more extra stuff', 'hh:mm a').isValid(), 'because other tokens were parsed, date is valid'); assert.ok(moment('1/1/2016 extra data', ['a', 'M/D/YYYY']).isValid(), 'took second format, does not pick up on meridiem parsed from first format (good copy)'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('creation data'); test('valid date', function (assert) { var dat = moment('1992-10-22'); var orig = dat.creationData(); assert.equal(dat.isValid(), true, '1992-10-22 is valid'); assert.equal(orig.input, '1992-10-22', 'original input is not correct.'); assert.equal(orig.format, 'YYYY-MM-DD', 'original format is defined.'); assert.equal(orig.locale._abbr, 'en', 'default locale is en'); assert.equal(orig.isUTC, false, 'not a UTC date'); }); test('valid date at fr locale', function (assert) { var dat = moment('1992-10-22', 'YYYY-MM-DD', 'fr'); var orig = dat.creationData(); assert.equal(orig.locale._abbr, 'fr', 'locale is fr'); }); test('valid date with formats', function (assert) { var dat = moment('29-06-1995', ['MM-DD-YYYY', 'DD-MM', 'DD-MM-YYYY']); var orig = dat.creationData(); assert.equal(orig.format, 'DD-MM-YYYY', 'DD-MM-YYYY format is defined.'); }); test('strict', function (assert) { assert.ok(moment('2015-01-02', 'YYYY-MM-DD', true).creationData().strict, 'strict is true'); assert.ok(!moment('2015-01-02', 'YYYY-MM-DD').creationData().strict, 'strict is true'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('days in month'); test('days in month', function (assert) { each([31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], function (days, i) { var firstDay = moment([2012, i]), lastDay = moment([2012, i, days]); assert.equal(firstDay.daysInMonth(), days, firstDay.format('L') + ' should have ' + days + ' days.'); assert.equal(lastDay.daysInMonth(), days, lastDay.format('L') + ' should have ' + days + ' days.'); }); }); test('days in month leap years', function (assert) { assert.equal(moment([2010, 1]).daysInMonth(), 28, 'Feb 2010 should have 28 days'); assert.equal(moment([2100, 1]).daysInMonth(), 28, 'Feb 2100 should have 28 days'); assert.equal(moment([2008, 1]).daysInMonth(), 29, 'Feb 2008 should have 29 days'); assert.equal(moment([2000, 1]).daysInMonth(), 29, 'Feb 2000 should have 29 days'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } 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; } var hookCallback; function 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 isUndefined(input) { return input === void 0; } function warn(msg) { if (hooks.suppressDeprecationWarnings === false && (typeof console !== 'undefined') && console.warn) { console.warn('Deprecation warning: ' + msg); } } function deprecate(msg, fn) { var firstTime = true; return extend(function () { if (hooks.deprecationHandler != null) { 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 (hooks.deprecationHandler != null) { hooks.deprecationHandler(name, msg); } if (!deprecations[name]) { warn(msg); deprecations[name] = true; } } hooks.suppressDeprecationWarnings = false; hooks.deprecationHandler = null; module('deprecate'); test('deprecate', function (assert) { // NOTE: hooks inside deprecate.js and moment are different, so this is can // not be test.expectedDeprecations(...) var fn = function () {}; var deprecatedFn = deprecate('testing deprecation', fn); deprecatedFn(); expect(0); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } function equal(assert, a, b, message) { assert.ok(Math.abs(a - b) < 0.00000001, '(' + a + ' === ' + b + ') ' + message); } function dstForYear(year) { var start = moment([year]), end = moment([year + 1]), current = start.clone(), last; while (current < end) { last = current.clone(); current.add(24, 'hour'); if (last.utcOffset() !== current.utcOffset()) { end = current.clone(); current = last.clone(); break; } } while (current < end) { last = current.clone(); current.add(1, 'hour'); if (last.utcOffset() !== current.utcOffset()) { return { moment : last, diff : -(current.utcOffset() - last.utcOffset()) / 60 }; } } } module('diff'); test('diff', function (assert) { assert.equal(moment(1000).diff(0), 1000, '1 second - 0 = 1000'); assert.equal(moment(1000).diff(500), 500, '1 second - 0.5 seconds = 500'); assert.equal(moment(0).diff(1000), -1000, '0 - 1 second = -1000'); assert.equal(moment(new Date(1000)).diff(1000), 0, '1 second - 1 second = 0'); var oneHourDate = new Date(2015, 5, 21), nowDate = new Date(+oneHourDate); oneHourDate.setHours(oneHourDate.getHours() + 1); assert.equal(moment(oneHourDate).diff(nowDate), 60 * 60 * 1000, '1 hour from now = 3600000'); }); test('diff key after', function (assert) { assert.equal(moment([2010]).diff([2011], 'years'), -1, 'year diff'); assert.equal(moment([2010]).diff([2010, 2], 'months'), -2, 'month diff'); assert.equal(moment([2010]).diff([2010, 0, 7], 'weeks'), 0, 'week diff'); assert.equal(moment([2010]).diff([2010, 0, 8], 'weeks'), -1, 'week diff'); assert.equal(moment([2010]).diff([2010, 0, 21], 'weeks'), -2, 'week diff'); assert.equal(moment([2010]).diff([2010, 0, 22], 'weeks'), -3, 'week diff'); assert.equal(moment([2010]).diff([2010, 0, 4], 'days'), -3, 'day diff'); assert.equal(moment([2010]).diff([2010, 0, 1, 4], 'hours'), -4, 'hour diff'); assert.equal(moment([2010]).diff([2010, 0, 1, 0, 5], 'minutes'), -5, 'minute diff'); assert.equal(moment([2010]).diff([2010, 0, 1, 0, 0, 6], 'seconds'), -6, 'second diff'); }); test('diff key before', function (assert) { assert.equal(moment([2011]).diff([2010], 'years'), 1, 'year diff'); assert.equal(moment([2010, 2]).diff([2010], 'months'), 2, 'month diff'); assert.equal(moment([2010, 0, 4]).diff([2010], 'days'), 3, 'day diff'); assert.equal(moment([2010, 0, 7]).diff([2010], 'weeks'), 0, 'week diff'); assert.equal(moment([2010, 0, 8]).diff([2010], 'weeks'), 1, 'week diff'); assert.equal(moment([2010, 0, 21]).diff([2010], 'weeks'), 2, 'week diff'); assert.equal(moment([2010, 0, 22]).diff([2010], 'weeks'), 3, 'week diff'); assert.equal(moment([2010, 0, 1, 4]).diff([2010], 'hours'), 4, 'hour diff'); assert.equal(moment([2010, 0, 1, 0, 5]).diff([2010], 'minutes'), 5, 'minute diff'); assert.equal(moment([2010, 0, 1, 0, 0, 6]).diff([2010], 'seconds'), 6, 'second diff'); }); test('diff key before singular', function (assert) { assert.equal(moment([2011]).diff([2010], 'year'), 1, 'year diff singular'); assert.equal(moment([2010, 2]).diff([2010], 'month'), 2, 'month diff singular'); assert.equal(moment([2010, 0, 4]).diff([2010], 'day'), 3, 'day diff singular'); assert.equal(moment([2010, 0, 7]).diff([2010], 'week'), 0, 'week diff singular'); assert.equal(moment([2010, 0, 8]).diff([2010], 'week'), 1, 'week diff singular'); assert.equal(moment([2010, 0, 21]).diff([2010], 'week'), 2, 'week diff singular'); assert.equal(moment([2010, 0, 22]).diff([2010], 'week'), 3, 'week diff singular'); assert.equal(moment([2010, 0, 1, 4]).diff([2010], 'hour'), 4, 'hour diff singular'); assert.equal(moment([2010, 0, 1, 0, 5]).diff([2010], 'minute'), 5, 'minute diff singular'); assert.equal(moment([2010, 0, 1, 0, 0, 6]).diff([2010], 'second'), 6, 'second diff singular'); }); test('diff key before abbreviated', function (assert) { assert.equal(moment([2011]).diff([2010], 'y'), 1, 'year diff abbreviated'); assert.equal(moment([2010, 2]).diff([2010], 'M'), 2, 'month diff abbreviated'); assert.equal(moment([2010, 0, 4]).diff([2010], 'd'), 3, 'day diff abbreviated'); assert.equal(moment([2010, 0, 7]).diff([2010], 'w'), 0, 'week diff abbreviated'); assert.equal(moment([2010, 0, 8]).diff([2010], 'w'), 1, 'week diff abbreviated'); assert.equal(moment([2010, 0, 21]).diff([2010], 'w'), 2, 'week diff abbreviated'); assert.equal(moment([2010, 0, 22]).diff([2010], 'w'), 3, 'week diff abbreviated'); assert.equal(moment([2010, 0, 1, 4]).diff([2010], 'h'), 4, 'hour diff abbreviated'); assert.equal(moment([2010, 0, 1, 0, 5]).diff([2010], 'm'), 5, 'minute diff abbreviated'); assert.equal(moment([2010, 0, 1, 0, 0, 6]).diff([2010], 's'), 6, 'second diff abbreviated'); }); test('diff month', function (assert) { assert.equal(moment([2011, 0, 31]).diff([2011, 2, 1], 'months'), -1, 'month diff'); }); test('diff across DST', function (assert) { var dst = dstForYear(2012), a, b, daysInMonth; if (!dst) { assert.equal(42, 42, 'at least one assertion'); return; } a = dst.moment; b = a.clone().utc().add(12, 'hours').local(); daysInMonth = (a.daysInMonth() + b.daysInMonth()) / 2; assert.equal(b.diff(a, 'milliseconds', true), 12 * 60 * 60 * 1000, 'ms diff across DST'); assert.equal(b.diff(a, 'seconds', true), 12 * 60 * 60, 'second diff across DST'); assert.equal(b.diff(a, 'minutes', true), 12 * 60, 'minute diff across DST'); assert.equal(b.diff(a, 'hours', true), 12, 'hour diff across DST'); assert.equal(b.diff(a, 'days', true), (12 - dst.diff) / 24, 'day diff across DST'); equal(assert, b.diff(a, 'weeks', true), (12 - dst.diff) / 24 / 7, 'week diff across DST'); assert.ok(0.95 / (2 * 31) < b.diff(a, 'months', true), 'month diff across DST, lower bound'); assert.ok(b.diff(a, 'month', true) < 1.05 / (2 * 28), 'month diff across DST, upper bound'); assert.ok(0.95 / (2 * 31 * 12) < b.diff(a, 'years', true), 'year diff across DST, lower bound'); assert.ok(b.diff(a, 'year', true) < 1.05 / (2 * 28 * 12), 'year diff across DST, upper bound'); a = dst.moment; b = a.clone().utc().add(12 + dst.diff, 'hours').local(); daysInMonth = (a.daysInMonth() + b.daysInMonth()) / 2; assert.equal(b.diff(a, 'milliseconds', true), (12 + dst.diff) * 60 * 60 * 1000, 'ms diff across DST'); assert.equal(b.diff(a, 'seconds', true), (12 + dst.diff) * 60 * 60, 'second diff across DST'); assert.equal(b.diff(a, 'minutes', true), (12 + dst.diff) * 60, 'minute diff across DST'); assert.equal(b.diff(a, 'hours', true), (12 + dst.diff), 'hour diff across DST'); assert.equal(b.diff(a, 'days', true), 12 / 24, 'day diff across DST'); equal(assert, b.diff(a, 'weeks', true), 12 / 24 / 7, 'week diff across DST'); assert.ok(0.95 / (2 * 31) < b.diff(a, 'months', true), 'month diff across DST, lower bound'); assert.ok(b.diff(a, 'month', true) < 1.05 / (2 * 28), 'month diff across DST, upper bound'); assert.ok(0.95 / (2 * 31 * 12) < b.diff(a, 'years', true), 'year diff across DST, lower bound'); assert.ok(b.diff(a, 'year', true) < 1.05 / (2 * 28 * 12), 'year diff across DST, upper bound'); }); test('diff overflow', function (assert) { assert.equal(moment([2011]).diff([2010], 'months'), 12, 'month diff'); assert.equal(moment([2010, 0, 2]).diff([2010], 'hours'), 24, 'hour diff'); assert.equal(moment([2010, 0, 1, 2]).diff([2010], 'minutes'), 120, 'minute diff'); assert.equal(moment([2010, 0, 1, 0, 4]).diff([2010], 'seconds'), 240, 'second diff'); }); test('diff between utc and local', function (assert) { if (moment([2012]).utcOffset() === moment([2011]).utcOffset()) { // Russia's utc offset on 1st of Jan 2012 vs 2011 is different assert.equal(moment([2012]).utc().diff([2011], 'years'), 1, 'year diff'); } assert.equal(moment([2010, 2, 2]).utc().diff([2010, 0, 2], 'months'), 2, 'month diff'); assert.equal(moment([2010, 0, 4]).utc().diff([2010], 'days'), 3, 'day diff'); assert.equal(moment([2010, 0, 22]).utc().diff([2010], 'weeks'), 3, 'week diff'); assert.equal(moment([2010, 0, 1, 4]).utc().diff([2010], 'hours'), 4, 'hour diff'); assert.equal(moment([2010, 0, 1, 0, 5]).utc().diff([2010], 'minutes'), 5, 'minute diff'); assert.equal(moment([2010, 0, 1, 0, 0, 6]).utc().diff([2010], 'seconds'), 6, 'second diff'); }); test('diff floored', function (assert) { assert.equal(moment([2010, 0, 1, 23]).diff([2010], 'day'), 0, '23 hours = 0 days'); assert.equal(moment([2010, 0, 1, 23, 59]).diff([2010], 'day'), 0, '23:59 hours = 0 days'); assert.equal(moment([2010, 0, 1, 24]).diff([2010], 'day'), 1, '24 hours = 1 day'); assert.equal(moment([2010, 0, 2]).diff([2011, 0, 1], 'year'), 0, 'year rounded down'); assert.equal(moment([2011, 0, 1]).diff([2010, 0, 2], 'year'), 0, 'year rounded down'); assert.equal(moment([2010, 0, 2]).diff([2011, 0, 2], 'year'), -1, 'year rounded down'); assert.equal(moment([2011, 0, 2]).diff([2010, 0, 2], 'year'), 1, 'year rounded down'); }); test('year diffs include dates', function (assert) { assert.ok(moment([2012, 1, 19]).diff(moment([2002, 1, 20]), 'years', true) < 10, 'year diff should include date of month'); }); test('month diffs', function (assert) { // due to floating point math errors, these tests just need to be accurate within 0.00000001 assert.equal(moment([2012, 0, 1]).diff([2012, 1, 1], 'months', true), -1, 'Jan 1 to Feb 1 should be 1 month'); equal(assert, moment([2012, 0, 1]).diff([2012, 0, 1, 12], 'months', true), -0.5 / 31, 'Jan 1 to Jan 1 noon should be 0.5 / 31 months'); assert.equal(moment([2012, 0, 15]).diff([2012, 1, 15], 'months', true), -1, 'Jan 15 to Feb 15 should be 1 month'); assert.equal(moment([2012, 0, 28]).diff([2012, 1, 28], 'months', true), -1, 'Jan 28 to Feb 28 should be 1 month'); assert.ok(moment([2012, 0, 31]).diff([2012, 1, 29], 'months', true), -1, 'Jan 31 to Feb 29 should be 1 month'); assert.ok(-1 > moment([2012, 0, 31]).diff([2012, 2, 1], 'months', true), 'Jan 31 to Mar 1 should be more than 1 month'); assert.ok(-30 / 28 < moment([2012, 0, 31]).diff([2012, 2, 1], 'months', true), 'Jan 31 to Mar 1 should be less than 1 month and 1 day'); equal(assert, moment([2012, 0, 1]).diff([2012, 0, 31], 'months', true), -(30 / 31), 'Jan 1 to Jan 31 should be 30 / 31 months'); assert.ok(0 < moment('2014-02-01').diff(moment('2014-01-31'), 'months', true), 'jan-31 to feb-1 diff is positive'); }); test('exact month diffs', function (assert) { // generate all pairs of months and compute month diff, with fixed day // of month = 15. var m1, m2; for (m1 = 0; m1 < 12; ++m1) { for (m2 = m1; m2 < 12; ++m2) { assert.equal(moment([2013, m2, 15]).diff(moment([2013, m1, 15]), 'months', true), m2 - m1, 'month diff from 2013-' + m1 + '-15 to 2013-' + m2 + '-15'); } } }); test('year diffs', function (assert) { // due to floating point math errors, these tests just need to be accurate within 0.00000001 equal(assert, moment([2012, 0, 1]).diff([2013, 0, 1], 'years', true), -1, 'Jan 1 2012 to Jan 1 2013 should be 1 year'); equal(assert, moment([2012, 1, 28]).diff([2013, 1, 28], 'years', true), -1, 'Feb 28 2012 to Feb 28 2013 should be 1 year'); equal(assert, moment([2012, 2, 1]).diff([2013, 2, 1], 'years', true), -1, 'Mar 1 2012 to Mar 1 2013 should be 1 year'); equal(assert, moment([2012, 11, 1]).diff([2013, 11, 1], 'years', true), -1, 'Dec 1 2012 to Dec 1 2013 should be 1 year'); equal(assert, moment([2012, 11, 31]).diff([2013, 11, 31], 'years', true), -1, 'Dec 31 2012 to Dec 31 2013 should be 1 year'); equal(assert, moment([2012, 0, 1]).diff([2013, 6, 1], 'years', true), -1.5, 'Jan 1 2012 to Jul 1 2013 should be 1.5 years'); equal(assert, moment([2012, 0, 31]).diff([2013, 6, 31], 'years', true), -1.5, 'Jan 31 2012 to Jul 31 2013 should be 1.5 years'); equal(assert, moment([2012, 0, 1]).diff([2013, 0, 1, 12], 'years', true), -1 - (0.5 / 31) / 12, 'Jan 1 2012 to Jan 1 2013 noon should be 1+(0.5 / 31) / 12 years'); equal(assert, moment([2012, 0, 1]).diff([2013, 6, 1, 12], 'years', true), -1.5 - (0.5 / 31) / 12, 'Jan 1 2012 to Jul 1 2013 noon should be 1.5+(0.5 / 31) / 12 years'); equal(assert, moment([2012, 1, 29]).diff([2013, 1, 28], 'years', true), -1, 'Feb 29 2012 to Feb 28 2013 should be 1-(1 / 28.5) / 12 years'); }); test('negative zero', function (assert) { function isNegative (n) { return (1 / n) < 0; } assert.ok(!isNegative(moment([2012, 0, 1]).diff(moment([2012, 0, 1]), 'months')), 'month diff on same date is zero, not -0'); assert.ok(!isNegative(moment([2012, 0, 1]).diff(moment([2012, 0, 1]), 'years')), 'year diff on same date is zero, not -0'); assert.ok(!isNegative(moment([2012, 0, 1]).diff(moment([2012, 0, 1]), 'quarters')), 'quarter diff on same date is zero, not -0'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('duration'); test('object instantiation', function (assert) { var d = moment.duration({ years: 2, months: 3, weeks: 2, days: 1, hours: 8, minutes: 9, seconds: 20, milliseconds: 12 }); assert.equal(d.years(), 2, 'years'); assert.equal(d.months(), 3, 'months'); assert.equal(d.weeks(), 2, 'weeks'); assert.equal(d.days(), 15, 'days'); // two weeks + 1 day assert.equal(d.hours(), 8, 'hours'); assert.equal(d.minutes(), 9, 'minutes'); assert.equal(d.seconds(), 20, 'seconds'); assert.equal(d.milliseconds(), 12, 'milliseconds'); }); test('object instantiation with strings', function (assert) { var d = moment.duration({ years: '2', months: '3', weeks: '2', days: '1', hours: '8', minutes: '9', seconds: '20', milliseconds: '12' }); assert.equal(d.years(), 2, 'years'); assert.equal(d.months(), 3, 'months'); assert.equal(d.weeks(), 2, 'weeks'); assert.equal(d.days(), 15, 'days'); // two weeks + 1 day assert.equal(d.hours(), 8, 'hours'); assert.equal(d.minutes(), 9, 'minutes'); assert.equal(d.seconds(), 20, 'seconds'); assert.equal(d.milliseconds(), 12, 'milliseconds'); }); test('milliseconds instantiation', function (assert) { assert.equal(moment.duration(72).milliseconds(), 72, 'milliseconds'); }); test('undefined instantiation', function (assert) { assert.equal(moment.duration(undefined).milliseconds(), 0, 'milliseconds'); }); test('null instantiation', function (assert) { assert.equal(moment.duration(null).milliseconds(), 0, 'milliseconds'); }); test('instantiation by type', function (assert) { assert.equal(moment.duration(1, 'years').years(), 1, 'years'); assert.equal(moment.duration(1, 'y').years(), 1, 'y'); assert.equal(moment.duration(2, 'months').months(), 2, 'months'); assert.equal(moment.duration(2, 'M').months(), 2, 'M'); assert.equal(moment.duration(3, 'weeks').weeks(), 3, 'weeks'); assert.equal(moment.duration(3, 'w').weeks(), 3, 'weeks'); assert.equal(moment.duration(4, 'days').days(), 4, 'days'); assert.equal(moment.duration(4, 'd').days(), 4, 'd'); assert.equal(moment.duration(5, 'hours').hours(), 5, 'hours'); assert.equal(moment.duration(5, 'h').hours(), 5, 'h'); assert.equal(moment.duration(6, 'minutes').minutes(), 6, 'minutes'); assert.equal(moment.duration(6, 'm').minutes(), 6, 'm'); assert.equal(moment.duration(7, 'seconds').seconds(), 7, 'seconds'); assert.equal(moment.duration(7, 's').seconds(), 7, 's'); assert.equal(moment.duration(8, 'milliseconds').milliseconds(), 8, 'milliseconds'); assert.equal(moment.duration(8, 'ms').milliseconds(), 8, 'ms'); }); test('shortcuts', function (assert) { assert.equal(moment.duration({y: 1}).years(), 1, 'years = y'); assert.equal(moment.duration({M: 2}).months(), 2, 'months = M'); assert.equal(moment.duration({w: 3}).weeks(), 3, 'weeks = w'); assert.equal(moment.duration({d: 4}).days(), 4, 'days = d'); assert.equal(moment.duration({h: 5}).hours(), 5, 'hours = h'); assert.equal(moment.duration({m: 6}).minutes(), 6, 'minutes = m'); assert.equal(moment.duration({s: 7}).seconds(), 7, 'seconds = s'); assert.equal(moment.duration({ms: 8}).milliseconds(), 8, 'milliseconds = ms'); }); test('generic getter', function (assert) { assert.equal(moment.duration(1, 'years').get('years'), 1, 'years'); assert.equal(moment.duration(1, 'years').get('year'), 1, 'years = year'); assert.equal(moment.duration(1, 'years').get('y'), 1, 'years = y'); assert.equal(moment.duration(2, 'months').get('months'), 2, 'months'); assert.equal(moment.duration(2, 'months').get('month'), 2, 'months = month'); assert.equal(moment.duration(2, 'months').get('M'), 2, 'months = M'); assert.equal(moment.duration(3, 'weeks').get('weeks'), 3, 'weeks'); assert.equal(moment.duration(3, 'weeks').get('week'), 3, 'weeks = week'); assert.equal(moment.duration(3, 'weeks').get('w'), 3, 'weeks = w'); assert.equal(moment.duration(4, 'days').get('days'), 4, 'days'); assert.equal(moment.duration(4, 'days').get('day'), 4, 'days = day'); assert.equal(moment.duration(4, 'days').get('d'), 4, 'days = d'); assert.equal(moment.duration(5, 'hours').get('hours'), 5, 'hours'); assert.equal(moment.duration(5, 'hours').get('hour'), 5, 'hours = hour'); assert.equal(moment.duration(5, 'hours').get('h'), 5, 'hours = h'); assert.equal(moment.duration(6, 'minutes').get('minutes'), 6, 'minutes'); assert.equal(moment.duration(6, 'minutes').get('minute'), 6, 'minutes = minute'); assert.equal(moment.duration(6, 'minutes').get('m'), 6, 'minutes = m'); assert.equal(moment.duration(7, 'seconds').get('seconds'), 7, 'seconds'); assert.equal(moment.duration(7, 'seconds').get('second'), 7, 'seconds = second'); assert.equal(moment.duration(7, 'seconds').get('s'), 7, 'seconds = s'); assert.equal(moment.duration(8, 'milliseconds').get('milliseconds'), 8, 'milliseconds'); assert.equal(moment.duration(8, 'milliseconds').get('millisecond'), 8, 'milliseconds = millisecond'); assert.equal(moment.duration(8, 'milliseconds').get('ms'), 8, 'milliseconds = ms'); }); test('instantiation from another duration', function (assert) { var simple = moment.duration(1234), lengthy = moment.duration(60 * 60 * 24 * 360 * 1e3), complicated = moment.duration({ years: 2, months: 3, weeks: 4, days: 1, hours: 8, minutes: 9, seconds: 20, milliseconds: 12 }), modified = moment.duration(1, 'day').add(moment.duration(1, 'day')); assert.deepEqual(moment.duration(simple), simple, 'simple clones are equal'); assert.deepEqual(moment.duration(lengthy), lengthy, 'lengthy clones are equal'); assert.deepEqual(moment.duration(complicated), complicated, 'complicated clones are equal'); assert.deepEqual(moment.duration(modified), modified, 'cloning modified duration works'); }); test('instantiation from 24-hour time zero', function (assert) { assert.equal(moment.duration('00:00').years(), 0, '0 years'); assert.equal(moment.duration('00:00').days(), 0, '0 days'); assert.equal(moment.duration('00:00').hours(), 0, '0 hours'); assert.equal(moment.duration('00:00').minutes(), 0, '0 minutes'); assert.equal(moment.duration('00:00').seconds(), 0, '0 seconds'); assert.equal(moment.duration('00:00').milliseconds(), 0, '0 milliseconds'); }); test('instantiation from 24-hour time <24 hours', function (assert) { assert.equal(moment.duration('06:45').years(), 0, '0 years'); assert.equal(moment.duration('06:45').days(), 0, '0 days'); assert.equal(moment.duration('06:45').hours(), 6, '6 hours'); assert.equal(moment.duration('06:45').minutes(), 45, '45 minutes'); assert.equal(moment.duration('06:45').seconds(), 0, '0 seconds'); assert.equal(moment.duration('06:45').milliseconds(), 0, '0 milliseconds'); }); test('instantiation from 24-hour time >24 hours', function (assert) { assert.equal(moment.duration('26:45').years(), 0, '0 years'); assert.equal(moment.duration('26:45').days(), 1, '0 days'); assert.equal(moment.duration('26:45').hours(), 2, '2 hours'); assert.equal(moment.duration('26:45').minutes(), 45, '45 minutes'); assert.equal(moment.duration('26:45').seconds(), 0, '0 seconds'); assert.equal(moment.duration('26:45').milliseconds(), 0, '0 milliseconds'); }); test('instatiation from serialized C# TimeSpan zero', function (assert) { assert.equal(moment.duration('00:00:00').years(), 0, '0 years'); assert.equal(moment.duration('00:00:00').days(), 0, '0 days'); assert.equal(moment.duration('00:00:00').hours(), 0, '0 hours'); assert.equal(moment.duration('00:00:00').minutes(), 0, '0 minutes'); assert.equal(moment.duration('00:00:00').seconds(), 0, '0 seconds'); assert.equal(moment.duration('00:00:00').milliseconds(), 0, '0 milliseconds'); }); test('instatiation from serialized C# TimeSpan with days', function (assert) { assert.equal(moment.duration('1.02:03:04.9999999').years(), 0, '0 years'); assert.equal(moment.duration('1.02:03:04.9999999').days(), 1, '1 day'); assert.equal(moment.duration('1.02:03:04.9999999').hours(), 2, '2 hours'); assert.equal(moment.duration('1.02:03:04.9999999').minutes(), 3, '3 minutes'); assert.equal(moment.duration('1.02:03:04.9999999').seconds(), 4, '4 seconds'); assert.equal(moment.duration('1.02:03:04.9999999').milliseconds(), 999, '999 milliseconds'); assert.equal(moment.duration('1 02:03:04.9999999').years(), 0, '0 years'); assert.equal(moment.duration('1 02:03:04.9999999').days(), 1, '1 day'); assert.equal(moment.duration('1 02:03:04.9999999').hours(), 2, '2 hours'); assert.equal(moment.duration('1 02:03:04.9999999').minutes(), 3, '3 minutes'); assert.equal(moment.duration('1 02:03:04.9999999').seconds(), 4, '4 seconds'); assert.equal(moment.duration('1 02:03:04.9999999').milliseconds(), 999, '999 milliseconds'); }); test('instatiation from serialized C# TimeSpan without days', function (assert) { assert.equal(moment.duration('01:02:03.9999999').years(), 0, '0 years'); assert.equal(moment.duration('01:02:03.9999999').days(), 0, '0 days'); assert.equal(moment.duration('01:02:03.9999999').hours(), 1, '1 hour'); assert.equal(moment.duration('01:02:03.9999999').minutes(), 2, '2 minutes'); assert.equal(moment.duration('01:02:03.9999999').seconds(), 3, '3 seconds'); assert.equal(moment.duration('01:02:03.9999999').milliseconds(), 999, '999 milliseconds'); assert.equal(moment.duration('23:59:59.9999999').days(), 0, '0 days'); assert.equal(moment.duration('23:59:59.9999999').hours(), 23, '23 hours'); assert.equal(moment.duration('500:59:59.9999999').days(), 20, '500 hours overflows to 20 days'); assert.equal(moment.duration('500:59:59.9999999').hours(), 20, '500 hours overflows to 20 hours'); }); test('instatiation from serialized C# TimeSpan without days or milliseconds', function (assert) { assert.equal(moment.duration('01:02:03').years(), 0, '0 years'); assert.equal(moment.duration('01:02:03').days(), 0, '0 days'); assert.equal(moment.duration('01:02:03').hours(), 1, '1 hour'); assert.equal(moment.duration('01:02:03').minutes(), 2, '2 minutes'); assert.equal(moment.duration('01:02:03').seconds(), 3, '3 seconds'); assert.equal(moment.duration('01:02:03').milliseconds(), 0, '0 milliseconds'); }); test('instatiation from serialized C# TimeSpan without milliseconds', function (assert) { assert.equal(moment.duration('1.02:03:04').years(), 0, '0 years'); assert.equal(moment.duration('1.02:03:04').days(), 1, '1 day'); assert.equal(moment.duration('1.02:03:04').hours(), 2, '2 hours'); assert.equal(moment.duration('1.02:03:04').minutes(), 3, '3 minutes'); assert.equal(moment.duration('1.02:03:04').seconds(), 4, '4 seconds'); assert.equal(moment.duration('1.02:03:04').milliseconds(), 0, '0 milliseconds'); }); test('instatiation from serialized C# TimeSpan maxValue', function (assert) { var d = moment.duration('10675199.02:48:05.4775807'); assert.equal(d.years(), 29227, '29227 years'); assert.equal(d.months(), 8, '8 months'); assert.equal(d.days(), 12, '12 day'); // if you have to change this value -- just do it assert.equal(d.hours(), 2, '2 hours'); assert.equal(d.minutes(), 48, '48 minutes'); assert.equal(d.seconds(), 5, '5 seconds'); assert.equal(d.milliseconds(), 477, '477 milliseconds'); }); test('instatiation from serialized C# TimeSpan minValue', function (assert) { var d = moment.duration('-10675199.02:48:05.4775808'); assert.equal(d.years(), -29227, '29653 years'); assert.equal(d.months(), -8, '8 day'); assert.equal(d.days(), -12, '12 day'); // if you have to change this value -- just do it assert.equal(d.hours(), -2, '2 hours'); assert.equal(d.minutes(), -48, '48 minutes'); assert.equal(d.seconds(), -5, '5 seconds'); assert.equal(d.milliseconds(), -477, '477 milliseconds'); }); test('instantiation from ISO 8601 duration', function (assert) { assert.equal(moment.duration('P1Y2M3DT4H5M6S').asSeconds(), moment.duration({y: 1, M: 2, d: 3, h: 4, m: 5, s: 6}).asSeconds(), 'all fields'); assert.equal(moment.duration('P3W3D').asSeconds(), moment.duration({w: 3, d: 3}).asSeconds(), 'week and day fields'); assert.equal(moment.duration('P1M').asSeconds(), moment.duration({M: 1}).asSeconds(), 'single month field'); assert.equal(moment.duration('PT1M').asSeconds(), moment.duration({m: 1}).asSeconds(), 'single minute field'); assert.equal(moment.duration('P1MT2H').asSeconds(), moment.duration({M: 1, h: 2}).asSeconds(), 'random fields missing'); assert.equal(moment.duration('-P60D').asSeconds(), moment.duration({d: -60}).asSeconds(), 'negative days'); assert.equal(moment.duration('PT0.5S').asSeconds(), moment.duration({s: 0.5}).asSeconds(), 'fractional seconds'); assert.equal(moment.duration('PT0,5S').asSeconds(), moment.duration({s: 0.5}).asSeconds(), 'fractional seconds (comma)'); }); test('serialization to ISO 8601 duration strings', function (assert) { assert.equal(moment.duration({y: 1, M: 2, d: 3, h: 4, m: 5, s: 6}).toISOString(), 'P1Y2M3DT4H5M6S', 'all fields'); assert.equal(moment.duration({M: -1}).toISOString(), '-P1M', 'one month ago'); assert.equal(moment.duration({m: -1}).toISOString(), '-PT1M', 'one minute ago'); assert.equal(moment.duration({s: -0.5}).toISOString(), '-PT0.5S', 'one half second ago'); assert.equal(moment.duration({y: -0.5, M: 1}).toISOString(), '-P5M', 'a month after half a year ago'); assert.equal(moment.duration({}).toISOString(), 'P0D', 'zero duration'); assert.equal(moment.duration({M: 16, d:40, s: 86465}).toISOString(), 'P1Y4M40DT24H1M5S', 'all fields'); }); test('toString acts as toISOString', function (assert) { assert.equal(moment.duration({y: 1, M: 2, d: 3, h: 4, m: 5, s: 6}).toString(), 'P1Y2M3DT4H5M6S', 'all fields'); assert.equal(moment.duration({M: -1}).toString(), '-P1M', 'one month ago'); assert.equal(moment.duration({m: -1}).toString(), '-PT1M', 'one minute ago'); assert.equal(moment.duration({s: -0.5}).toString(), '-PT0.5S', 'one half second ago'); assert.equal(moment.duration({y: -0.5, M: 1}).toString(), '-P5M', 'a month after half a year ago'); assert.equal(moment.duration({}).toString(), 'P0D', 'zero duration'); assert.equal(moment.duration({M: 16, d:40, s: 86465}).toString(), 'P1Y4M40DT24H1M5S', 'all fields'); }); test('toIsoString deprecation', function (assert) { test.expectedDeprecations('toIsoString()'); assert.equal(moment.duration({}).toIsoString(), moment.duration({}).toISOString(), 'toIsoString delegates to toISOString'); }); test('`isodate` (python) test cases', function (assert) { assert.equal(moment.duration('P18Y9M4DT11H9M8S').asSeconds(), moment.duration({y: 18, M: 9, d: 4, h: 11, m: 9, s: 8}).asSeconds(), 'python isodate 1'); assert.equal(moment.duration('P2W').asSeconds(), moment.duration({w: 2}).asSeconds(), 'python isodate 2'); assert.equal(moment.duration('P3Y6M4DT12H30M5S').asSeconds(), moment.duration({y: 3, M: 6, d: 4, h: 12, m: 30, s: 5}).asSeconds(), 'python isodate 3'); assert.equal(moment.duration('P23DT23H').asSeconds(), moment.duration({d: 23, h: 23}).asSeconds(), 'python isodate 4'); assert.equal(moment.duration('P4Y').asSeconds(), moment.duration({y: 4}).asSeconds(), 'python isodate 5'); assert.equal(moment.duration('P1M').asSeconds(), moment.duration({M: 1}).asSeconds(), 'python isodate 6'); assert.equal(moment.duration('PT1M').asSeconds(), moment.duration({m: 1}).asSeconds(), 'python isodate 7'); assert.equal(moment.duration('P0.5Y').asSeconds(), moment.duration({y: 0.5}).asSeconds(), 'python isodate 8'); assert.equal(moment.duration('PT36H').asSeconds(), moment.duration({h: 36}).asSeconds(), 'python isodate 9'); assert.equal(moment.duration('P1DT12H').asSeconds(), moment.duration({d: 1, h: 12}).asSeconds(), 'python isodate 10'); assert.equal(moment.duration('-P2W').asSeconds(), moment.duration({w: -2}).asSeconds(), 'python isodate 11'); assert.equal(moment.duration('-P2.2W').asSeconds(), moment.duration({w: -2.2}).asSeconds(), 'python isodate 12'); assert.equal(moment.duration('P1DT2H3M4S').asSeconds(), moment.duration({d: 1, h: 2, m: 3, s: 4}).asSeconds(), 'python isodate 13'); assert.equal(moment.duration('P1DT2H3M').asSeconds(), moment.duration({d: 1, h: 2, m: 3}).asSeconds(), 'python isodate 14'); assert.equal(moment.duration('P1DT2H').asSeconds(), moment.duration({d: 1, h: 2}).asSeconds(), 'python isodate 15'); assert.equal(moment.duration('PT2H').asSeconds(), moment.duration({h: 2}).asSeconds(), 'python isodate 16'); assert.equal(moment.duration('PT2.3H').asSeconds(), moment.duration({h: 2.3}).asSeconds(), 'python isodate 17'); assert.equal(moment.duration('PT2H3M4S').asSeconds(), moment.duration({h: 2, m: 3, s: 4}).asSeconds(), 'python isodate 18'); assert.equal(moment.duration('PT3M4S').asSeconds(), moment.duration({m: 3, s: 4}).asSeconds(), 'python isodate 19'); assert.equal(moment.duration('PT22S').asSeconds(), moment.duration({s: 22}).asSeconds(), 'python isodate 20'); assert.equal(moment.duration('PT22.22S').asSeconds(), moment.duration({s: 22.22}).asSeconds(), 'python isodate 21'); assert.equal(moment.duration('-P2Y').asSeconds(), moment.duration({y: -2}).asSeconds(), 'python isodate 22'); assert.equal(moment.duration('-P3Y6M4DT12H30M5S').asSeconds(), moment.duration({y: -3, M: -6, d: -4, h: -12, m: -30, s: -5}).asSeconds(), 'python isodate 23'); assert.equal(moment.duration('-P1DT2H3M4S').asSeconds(), moment.duration({d: -1, h: -2, m: -3, s: -4}).asSeconds(), 'python isodate 24'); assert.equal(moment.duration('PT-6H3M').asSeconds(), moment.duration({h: -6, m: 3}).asSeconds(), 'python isodate 25'); assert.equal(moment.duration('-PT-6H3M').asSeconds(), moment.duration({h: 6, m: -3}).asSeconds(), 'python isodate 26'); assert.equal(moment.duration('-P-3Y-6M-4DT-12H-30M-5S').asSeconds(), moment.duration({y: 3, M: 6, d: 4, h: 12, m: 30, s: 5}).asSeconds(), 'python isodate 27'); assert.equal(moment.duration('P-3Y-6M-4DT-12H-30M-5S').asSeconds(), moment.duration({y: -3, M: -6, d: -4, h: -12, m: -30, s: -5}).asSeconds(), 'python isodate 28'); assert.equal(moment.duration('-P-2W').asSeconds(), moment.duration({w: 2}).asSeconds(), 'python isodate 29'); assert.equal(moment.duration('P-2W').asSeconds(), moment.duration({w: -2}).asSeconds(), 'python isodate 30'); }); test('ISO 8601 misuse cases', function (assert) { assert.equal(moment.duration('P').asSeconds(), 0, 'lonely P'); assert.equal(moment.duration('PT').asSeconds(), 0, 'just P and T'); assert.equal(moment.duration('P1H').asSeconds(), 0, 'missing T'); assert.equal(moment.duration('P1D1Y').asSeconds(), 0, 'out of order'); assert.equal(moment.duration('PT.5S').asSeconds(), 0.5, 'accept no leading zero for decimal'); assert.equal(moment.duration('PT1,S').asSeconds(), 1, 'accept trailing decimal separator'); assert.equal(moment.duration('PT1M0,,5S').asSeconds(), 60, 'extra decimal separators are ignored as 0'); }); test('humanize', function (assert) { moment.locale('en'); assert.equal(moment.duration({seconds: 44}).humanize(), 'a few seconds', '44 seconds = a few seconds'); assert.equal(moment.duration({seconds: 45}).humanize(), 'a minute', '45 seconds = a minute'); assert.equal(moment.duration({seconds: 89}).humanize(), 'a minute', '89 seconds = a minute'); assert.equal(moment.duration({seconds: 90}).humanize(), '2 minutes', '90 seconds = 2 minutes'); assert.equal(moment.duration({minutes: 44}).humanize(), '44 minutes', '44 minutes = 44 minutes'); assert.equal(moment.duration({minutes: 45}).humanize(), 'an hour', '45 minutes = an hour'); assert.equal(moment.duration({minutes: 89}).humanize(), 'an hour', '89 minutes = an hour'); assert.equal(moment.duration({minutes: 90}).humanize(), '2 hours', '90 minutes = 2 hours'); assert.equal(moment.duration({hours: 5}).humanize(), '5 hours', '5 hours = 5 hours'); assert.equal(moment.duration({hours: 21}).humanize(), '21 hours', '21 hours = 21 hours'); assert.equal(moment.duration({hours: 22}).humanize(), 'a day', '22 hours = a day'); assert.equal(moment.duration({hours: 35}).humanize(), 'a day', '35 hours = a day'); assert.equal(moment.duration({hours: 36}).humanize(), '2 days', '36 hours = 2 days'); assert.equal(moment.duration({days: 1}).humanize(), 'a day', '1 day = a day'); assert.equal(moment.duration({days: 5}).humanize(), '5 days', '5 days = 5 days'); assert.equal(moment.duration({weeks: 1}).humanize(), '7 days', '1 week = 7 days'); assert.equal(moment.duration({days: 25}).humanize(), '25 days', '25 days = 25 days'); assert.equal(moment.duration({days: 26}).humanize(), 'a month', '26 days = a month'); assert.equal(moment.duration({days: 30}).humanize(), 'a month', '30 days = a month'); assert.equal(moment.duration({days: 45}).humanize(), 'a month', '45 days = a month'); assert.equal(moment.duration({days: 46}).humanize(), '2 months', '46 days = 2 months'); assert.equal(moment.duration({days: 74}).humanize(), '2 months', '74 days = 2 months'); assert.equal(moment.duration({days: 77}).humanize(), '3 months', '77 days = 3 months'); assert.equal(moment.duration({months: 1}).humanize(), 'a month', '1 month = a month'); assert.equal(moment.duration({months: 5}).humanize(), '5 months', '5 months = 5 months'); assert.equal(moment.duration({days: 344}).humanize(), 'a year', '344 days = a year'); assert.equal(moment.duration({days: 345}).humanize(), 'a year', '345 days = a year'); assert.equal(moment.duration({days: 547}).humanize(), 'a year', '547 days = a year'); assert.equal(moment.duration({days: 548}).humanize(), '2 years', '548 days = 2 years'); assert.equal(moment.duration({years: 1}).humanize(), 'a year', '1 year = a year'); assert.equal(moment.duration({years: 5}).humanize(), '5 years', '5 years = 5 years'); assert.equal(moment.duration(7200000).humanize(), '2 hours', '7200000 = 2 minutes'); }); test('humanize duration with suffix', function (assert) { moment.locale('en'); assert.equal(moment.duration({seconds: 44}).humanize(true), 'in a few seconds', '44 seconds = a few seconds'); assert.equal(moment.duration({seconds: -44}).humanize(true), 'a few seconds ago', '44 seconds = a few seconds'); }); test('bubble value up', function (assert) { assert.equal(moment.duration({milliseconds: 61001}).milliseconds(), 1, '61001 milliseconds has 1 millisecond left over'); assert.equal(moment.duration({milliseconds: 61001}).seconds(), 1, '61001 milliseconds has 1 second left over'); assert.equal(moment.duration({milliseconds: 61001}).minutes(), 1, '61001 milliseconds has 1 minute left over'); assert.equal(moment.duration({minutes: 350}).minutes(), 50, '350 minutes has 50 minutes left over'); assert.equal(moment.duration({minutes: 350}).hours(), 5, '350 minutes has 5 hours left over'); }); test('clipping', function (assert) { assert.equal(moment.duration({months: 11}).months(), 11, '11 months is 11 months'); assert.equal(moment.duration({months: 11}).years(), 0, '11 months makes no year'); assert.equal(moment.duration({months: 12}).months(), 0, '12 months is 0 months left over'); assert.equal(moment.duration({months: 12}).years(), 1, '12 months makes 1 year'); assert.equal(moment.duration({months: 13}).months(), 1, '13 months is 1 month left over'); assert.equal(moment.duration({months: 13}).years(), 1, '13 months makes 1 year'); assert.equal(moment.duration({days: 30}).days(), 30, '30 days is 30 days'); assert.equal(moment.duration({days: 30}).months(), 0, '30 days makes no month'); assert.equal(moment.duration({days: 31}).days(), 0, '31 days is 0 days left over'); assert.equal(moment.duration({days: 31}).months(), 1, '31 days is a month'); assert.equal(moment.duration({days: 32}).days(), 1, '32 days is 1 day left over'); assert.equal(moment.duration({days: 32}).months(), 1, '32 days is a month'); assert.equal(moment.duration({hours: 23}).hours(), 23, '23 hours is 23 hours'); assert.equal(moment.duration({hours: 23}).days(), 0, '23 hours makes no day'); assert.equal(moment.duration({hours: 24}).hours(), 0, '24 hours is 0 hours left over'); assert.equal(moment.duration({hours: 24}).days(), 1, '24 hours makes 1 day'); assert.equal(moment.duration({hours: 25}).hours(), 1, '25 hours is 1 hour left over'); assert.equal(moment.duration({hours: 25}).days(), 1, '25 hours makes 1 day'); }); test('bubbling consistency', function (assert) { var days = 0, months = 0, newDays, newMonths, totalDays, d; for (totalDays = 1; totalDays <= 500; ++totalDays) { d = moment.duration(totalDays, 'days'); newDays = d.days(); newMonths = d.months() + d.years() * 12; assert.ok( (months === newMonths && days + 1 === newDays) || (months + 1 === newMonths && newDays === 0), 'consistent total days ' + totalDays + ' was ' + months + ' ' + days + ' now ' + newMonths + ' ' + newDays); days = newDays; months = newMonths; } }); test('effective equivalency', function (assert) { assert.deepEqual(moment.duration({seconds: 1})._data, moment.duration({milliseconds: 1000})._data, '1 second is the same as 1000 milliseconds'); assert.deepEqual(moment.duration({seconds: 60})._data, moment.duration({minutes: 1})._data, '1 minute is the same as 60 seconds'); assert.deepEqual(moment.duration({minutes: 60})._data, moment.duration({hours: 1})._data, '1 hour is the same as 60 minutes'); assert.deepEqual(moment.duration({hours: 24})._data, moment.duration({days: 1})._data, '1 day is the same as 24 hours'); assert.deepEqual(moment.duration({days: 7})._data, moment.duration({weeks: 1})._data, '1 week is the same as 7 days'); assert.deepEqual(moment.duration({days: 31})._data, moment.duration({months: 1})._data, '1 month is the same as 30 days'); assert.deepEqual(moment.duration({months: 12})._data, moment.duration({years: 1})._data, '1 years is the same as 12 months'); }); test('asGetters', function (assert) { // 400 years have exactly 146097 days // years assert.equal(moment.duration(1, 'year').asYears(), 1, '1 year as years'); assert.equal(moment.duration(1, 'year').asMonths(), 12, '1 year as months'); assert.equal(moment.duration(400, 'year').asMonths(), 4800, '400 years as months'); assert.equal(moment.duration(1, 'year').asWeeks().toFixed(3), 52.143, '1 year as weeks'); assert.equal(moment.duration(1, 'year').asDays(), 365, '1 year as days'); assert.equal(moment.duration(2, 'year').asDays(), 730, '2 years as days'); assert.equal(moment.duration(3, 'year').asDays(), 1096, '3 years as days'); assert.equal(moment.duration(4, 'year').asDays(), 1461, '4 years as days'); assert.equal(moment.duration(400, 'year').asDays(), 146097, '400 years as days'); assert.equal(moment.duration(1, 'year').asHours(), 8760, '1 year as hours'); assert.equal(moment.duration(1, 'year').asMinutes(), 525600, '1 year as minutes'); assert.equal(moment.duration(1, 'year').asSeconds(), 31536000, '1 year as seconds'); assert.equal(moment.duration(1, 'year').asMilliseconds(), 31536000000, '1 year as milliseconds'); // months assert.equal(moment.duration(1, 'month').asYears().toFixed(4), 0.0833, '1 month as years'); assert.equal(moment.duration(1, 'month').asMonths(), 1, '1 month as months'); assert.equal(moment.duration(1, 'month').asWeeks().toFixed(3), 4.286, '1 month as weeks'); assert.equal(moment.duration(1, 'month').asDays(), 30, '1 month as days'); assert.equal(moment.duration(2, 'month').asDays(), 61, '2 months as days'); assert.equal(moment.duration(3, 'month').asDays(), 91, '3 months as days'); assert.equal(moment.duration(4, 'month').asDays(), 122, '4 months as days'); assert.equal(moment.duration(5, 'month').asDays(), 152, '5 months as days'); assert.equal(moment.duration(6, 'month').asDays(), 183, '6 months as days'); assert.equal(moment.duration(7, 'month').asDays(), 213, '7 months as days'); assert.equal(moment.duration(8, 'month').asDays(), 243, '8 months as days'); assert.equal(moment.duration(9, 'month').asDays(), 274, '9 months as days'); assert.equal(moment.duration(10, 'month').asDays(), 304, '10 months as days'); assert.equal(moment.duration(11, 'month').asDays(), 335, '11 months as days'); assert.equal(moment.duration(12, 'month').asDays(), 365, '12 months as days'); assert.equal(moment.duration(24, 'month').asDays(), 730, '24 months as days'); assert.equal(moment.duration(36, 'month').asDays(), 1096, '36 months as days'); assert.equal(moment.duration(48, 'month').asDays(), 1461, '48 months as days'); assert.equal(moment.duration(4800, 'month').asDays(), 146097, '4800 months as days'); assert.equal(moment.duration(1, 'month').asHours(), 720, '1 month as hours'); assert.equal(moment.duration(1, 'month').asMinutes(), 43200, '1 month as minutes'); assert.equal(moment.duration(1, 'month').asSeconds(), 2592000, '1 month as seconds'); assert.equal(moment.duration(1, 'month').asMilliseconds(), 2592000000, '1 month as milliseconds'); // weeks assert.equal(moment.duration(1, 'week').asYears().toFixed(4), 0.0192, '1 week as years'); assert.equal(moment.duration(1, 'week').asMonths().toFixed(3), 0.230, '1 week as months'); assert.equal(moment.duration(1, 'week').asWeeks(), 1, '1 week as weeks'); assert.equal(moment.duration(1, 'week').asDays(), 7, '1 week as days'); assert.equal(moment.duration(1, 'week').asHours(), 168, '1 week as hours'); assert.equal(moment.duration(1, 'week').asMinutes(), 10080, '1 week as minutes'); assert.equal(moment.duration(1, 'week').asSeconds(), 604800, '1 week as seconds'); assert.equal(moment.duration(1, 'week').asMilliseconds(), 604800000, '1 week as milliseconds'); // days assert.equal(moment.duration(1, 'day').asYears().toFixed(4), 0.0027, '1 day as years'); assert.equal(moment.duration(1, 'day').asMonths().toFixed(3), 0.033, '1 day as months'); assert.equal(moment.duration(1, 'day').asWeeks().toFixed(3), 0.143, '1 day as weeks'); assert.equal(moment.duration(1, 'day').asDays(), 1, '1 day as days'); assert.equal(moment.duration(1, 'day').asHours(), 24, '1 day as hours'); assert.equal(moment.duration(1, 'day').asMinutes(), 1440, '1 day as minutes'); assert.equal(moment.duration(1, 'day').asSeconds(), 86400, '1 day as seconds'); assert.equal(moment.duration(1, 'day').asMilliseconds(), 86400000, '1 day as milliseconds'); // hours assert.equal(moment.duration(1, 'hour').asYears().toFixed(6), 0.000114, '1 hour as years'); assert.equal(moment.duration(1, 'hour').asMonths().toFixed(5), 0.00137, '1 hour as months'); assert.equal(moment.duration(1, 'hour').asWeeks().toFixed(5), 0.00595, '1 hour as weeks'); assert.equal(moment.duration(1, 'hour').asDays().toFixed(4), 0.0417, '1 hour as days'); assert.equal(moment.duration(1, 'hour').asHours(), 1, '1 hour as hours'); assert.equal(moment.duration(1, 'hour').asMinutes(), 60, '1 hour as minutes'); assert.equal(moment.duration(1, 'hour').asSeconds(), 3600, '1 hour as seconds'); assert.equal(moment.duration(1, 'hour').asMilliseconds(), 3600000, '1 hour as milliseconds'); // minutes assert.equal(moment.duration(1, 'minute').asYears().toFixed(8), 0.00000190, '1 minute as years'); assert.equal(moment.duration(1, 'minute').asMonths().toFixed(7), 0.0000228, '1 minute as months'); assert.equal(moment.duration(1, 'minute').asWeeks().toFixed(7), 0.0000992, '1 minute as weeks'); assert.equal(moment.duration(1, 'minute').asDays().toFixed(6), 0.000694, '1 minute as days'); assert.equal(moment.duration(1, 'minute').asHours().toFixed(4), 0.0167, '1 minute as hours'); assert.equal(moment.duration(1, 'minute').asMinutes(), 1, '1 minute as minutes'); assert.equal(moment.duration(1, 'minute').asSeconds(), 60, '1 minute as seconds'); assert.equal(moment.duration(1, 'minute').asMilliseconds(), 60000, '1 minute as milliseconds'); // seconds assert.equal(moment.duration(1, 'second').asYears().toFixed(10), 0.0000000317, '1 second as years'); assert.equal(moment.duration(1, 'second').asMonths().toFixed(9), 0.000000380, '1 second as months'); assert.equal(moment.duration(1, 'second').asWeeks().toFixed(8), 0.00000165, '1 second as weeks'); assert.equal(moment.duration(1, 'second').asDays().toFixed(7), 0.0000116, '1 second as days'); assert.equal(moment.duration(1, 'second').asHours().toFixed(6), 0.000278, '1 second as hours'); assert.equal(moment.duration(1, 'second').asMinutes().toFixed(4), 0.0167, '1 second as minutes'); assert.equal(moment.duration(1, 'second').asSeconds(), 1, '1 second as seconds'); assert.equal(moment.duration(1, 'second').asMilliseconds(), 1000, '1 second as milliseconds'); // milliseconds assert.equal(moment.duration(1, 'millisecond').asYears().toFixed(13), 0.0000000000317, '1 millisecond as years'); assert.equal(moment.duration(1, 'millisecond').asMonths().toFixed(12), 0.000000000380, '1 millisecond as months'); assert.equal(moment.duration(1, 'millisecond').asWeeks().toFixed(11), 0.00000000165, '1 millisecond as weeks'); assert.equal(moment.duration(1, 'millisecond').asDays().toFixed(10), 0.0000000116, '1 millisecond as days'); assert.equal(moment.duration(1, 'millisecond').asHours().toFixed(9), 0.000000278, '1 millisecond as hours'); assert.equal(moment.duration(1, 'millisecond').asMinutes().toFixed(7), 0.0000167, '1 millisecond as minutes'); assert.equal(moment.duration(1, 'millisecond').asSeconds(), 0.001, '1 millisecond as seconds'); assert.equal(moment.duration(1, 'millisecond').asMilliseconds(), 1, '1 millisecond as milliseconds'); }); test('as getters for small units', function (assert) { var dS = moment.duration(1, 'milliseconds'), ds = moment.duration(3, 'seconds'), dm = moment.duration(13, 'minutes'); // Tests for issue #1867. // Floating point errors for small duration units were introduced in version 2.8.0. assert.equal(dS.as('milliseconds'), 1, 'as("milliseconds")'); assert.equal(dS.asMilliseconds(), 1, 'asMilliseconds()'); assert.equal(ds.as('seconds'), 3, 'as("seconds")'); assert.equal(ds.asSeconds(), 3, 'asSeconds()'); assert.equal(dm.as('minutes'), 13, 'as("minutes")'); assert.equal(dm.asMinutes(), 13, 'asMinutes()'); }); test('minutes getter for floating point hours', function (assert) { // Tests for issue #2978. // For certain floating point hours, .minutes() getter produced incorrect values due to the rounding errors assert.equal(moment.duration(2.3, 'h').minutes(), 18, 'minutes()'); assert.equal(moment.duration(4.1, 'h').minutes(), 6, 'minutes()'); }); test('isDuration', function (assert) { assert.ok(moment.isDuration(moment.duration(12345678)), 'correctly says true'); assert.ok(!moment.isDuration(moment()), 'moment object is not a duration'); assert.ok(!moment.isDuration({milliseconds: 1}), 'plain object is not a duration'); }); test('add', function (assert) { var d = moment.duration({months: 4, weeks: 3, days: 2}); // for some reason, d._data._months does not get updated; use d._months instead. assert.equal(d.add(1, 'month')._months, 5, 'Add months'); assert.equal(d.add(5, 'days')._days, 28, 'Add days'); assert.equal(d.add(10000)._milliseconds, 10000, 'Add milliseconds'); assert.equal(d.add({h: 23, m: 59})._milliseconds, 23 * 60 * 60 * 1000 + 59 * 60 * 1000 + 10000, 'Add hour:minute'); }); test('add and bubble', function (assert) { var d; assert.equal(moment.duration(1, 'second').add(1000, 'milliseconds').seconds(), 2, 'Adding milliseconds should bubble up to seconds'); assert.equal(moment.duration(1, 'minute').add(60, 'second').minutes(), 2, 'Adding seconds should bubble up to minutes'); assert.equal(moment.duration(1, 'hour').add(60, 'minutes').hours(), 2, 'Adding minutes should bubble up to hours'); assert.equal(moment.duration(1, 'day').add(24, 'hours').days(), 2, 'Adding hours should bubble up to days'); d = moment.duration(-1, 'day').add(1, 'hour'); assert.equal(d.hours(), -23, '-1 day + 1 hour == -23 hour (component)'); assert.equal(d.asHours(), -23, '-1 day + 1 hour == -23 hours'); d = moment.duration(-1, 'year').add(1, 'day'); assert.equal(d.days(), -30, '- 1 year + 1 day == -30 days (component)'); assert.equal(d.months(), -11, '- 1 year + 1 day == -11 months (component)'); assert.equal(d.years(), 0, '- 1 year + 1 day == 0 years (component)'); assert.equal(d.asDays(), -364, '- 1 year + 1 day == -364 days'); d = moment.duration(-1, 'year').add(1, 'hour'); assert.equal(d.hours(), -23, '- 1 year + 1 hour == -23 hours (component)'); assert.equal(d.days(), -30, '- 1 year + 1 hour == -30 days (component)'); assert.equal(d.months(), -11, '- 1 year + 1 hour == -11 months (component)'); assert.equal(d.years(), 0, '- 1 year + 1 hour == 0 years (component)'); }); test('subtract and bubble', function (assert) { var d; assert.equal(moment.duration(2, 'second').subtract(1000, 'milliseconds').seconds(), 1, 'Subtracting milliseconds should bubble up to seconds'); assert.equal(moment.duration(2, 'minute').subtract(60, 'second').minutes(), 1, 'Subtracting seconds should bubble up to minutes'); assert.equal(moment.duration(2, 'hour').subtract(60, 'minutes').hours(), 1, 'Subtracting minutes should bubble up to hours'); assert.equal(moment.duration(2, 'day').subtract(24, 'hours').days(), 1, 'Subtracting hours should bubble up to days'); d = moment.duration(1, 'day').subtract(1, 'hour'); assert.equal(d.hours(), 23, '1 day - 1 hour == 23 hour (component)'); assert.equal(d.asHours(), 23, '1 day - 1 hour == 23 hours'); d = moment.duration(1, 'year').subtract(1, 'day'); assert.equal(d.days(), 30, '1 year - 1 day == 30 days (component)'); assert.equal(d.months(), 11, '1 year - 1 day == 11 months (component)'); assert.equal(d.years(), 0, '1 year - 1 day == 0 years (component)'); assert.equal(d.asDays(), 364, '1 year - 1 day == 364 days'); d = moment.duration(1, 'year').subtract(1, 'hour'); assert.equal(d.hours(), 23, '1 year - 1 hour == 23 hours (component)'); assert.equal(d.days(), 30, '1 year - 1 hour == 30 days (component)'); assert.equal(d.months(), 11, '1 year - 1 hour == 11 months (component)'); assert.equal(d.years(), 0, '1 year - 1 hour == 0 years (component)'); }); test('subtract', function (assert) { var d = moment.duration({months: 2, weeks: 2, days: 0, hours: 5}); // for some reason, d._data._months does not get updated; use d._months instead. assert.equal(d.subtract(1, 'months')._months, 1, 'Subtract months'); assert.equal(d.subtract(14, 'days')._days, 0, 'Subtract days'); assert.equal(d.subtract(10000)._milliseconds, 5 * 60 * 60 * 1000 - 10000, 'Subtract milliseconds'); assert.equal(d.subtract({h: 1, m: 59})._milliseconds, 3 * 60 * 60 * 1000 + 1 * 60 * 1000 - 10000, 'Subtract hour:minute'); }); test('JSON.stringify duration', function (assert) { var d = moment.duration(1024, 'h'); assert.equal(JSON.stringify(d), '"' + d.toISOString() + '"', 'JSON.stringify on duration should return ISO string'); }); test('duration plugins', function (assert) { var durationObject = moment.duration(); moment.duration.fn.foo = function (arg) { assert.equal(this, durationObject); assert.equal(arg, 5); }; durationObject.foo(5); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('duration from moments'); test('pure year diff', function (assert) { var m1 = moment('2012-01-01T00:00:00.000Z'), m2 = moment('2013-01-01T00:00:00.000Z'); assert.equal(moment.duration({from: m1, to: m2}).as('years'), 1, 'year moment difference'); assert.equal(moment.duration({from: m2, to: m1}).as('years'), -1, 'negative year moment difference'); }); test('month and day diff', function (assert) { var m1 = moment('2012-01-15T00:00:00.000Z'), m2 = moment('2012-02-17T00:00:00.000Z'), d = moment.duration({from: m1, to: m2}); assert.equal(d.get('days'), 2); assert.equal(d.get('months'), 1); }); test('day diff, separate months', function (assert) { var m1 = moment('2012-01-15T00:00:00.000Z'), m2 = moment('2012-02-13T00:00:00.000Z'), d = moment.duration({from: m1, to: m2}); assert.equal(d.as('days'), 29); }); test('hour diff', function (assert) { var m1 = moment('2012-01-15T17:00:00.000Z'), m2 = moment('2012-01-16T03:00:00.000Z'), d = moment.duration({from: m1, to: m2}); assert.equal(d.as('hours'), 10); }); test('minute diff', function (assert) { var m1 = moment('2012-01-15T17:45:00.000Z'), m2 = moment('2012-01-16T03:15:00.000Z'), d = moment.duration({from: m1, to: m2}); assert.equal(d.as('hours'), 9.5); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('format'); test('format YY', function (assert) { var b = moment(new Date(2009, 1, 14, 15, 25, 50, 125)); assert.equal(b.format('YY'), '09', 'YY ---> 09'); }); test('format escape brackets', function (assert) { moment.locale('en'); var b = moment(new Date(2009, 1, 14, 15, 25, 50, 125)); assert.equal(b.format('[day]'), 'day', 'Single bracket'); assert.equal(b.format('[day] YY [YY]'), 'day 09 YY', 'Double bracket'); assert.equal(b.format('[YY'), '[09', 'Un-ended bracket'); assert.equal(b.format('[[YY]]'), '[YY]', 'Double nested brackets'); assert.equal(b.format('[[]'), '[', 'Escape open bracket'); assert.equal(b.format('[Last]'), 'Last', 'localized tokens'); assert.equal(b.format('[L] L'), 'L 02/14/2009', 'localized tokens with escaped localized tokens'); assert.equal(b.format('[L LL LLL LLLL aLa]'), 'L LL LLL LLLL aLa', 'localized tokens with escaped localized tokens'); assert.equal(b.format('[LLL] LLL'), 'LLL February 14, 2009 3:25 PM', 'localized tokens with escaped localized tokens (recursion)'); assert.equal(b.format('YYYY[\n]DD[\n]'), '2009\n14\n', 'Newlines'); }); test('handle negative years', function (assert) { moment.locale('en'); assert.equal(moment.utc().year(-1).format('YY'), '-01', 'YY with negative year'); assert.equal(moment.utc().year(-1).format('YYYY'), '-0001', 'YYYY with negative year'); assert.equal(moment.utc().year(-12).format('YY'), '-12', 'YY with negative year'); assert.equal(moment.utc().year(-12).format('YYYY'), '-0012', 'YYYY with negative year'); assert.equal(moment.utc().year(-123).format('YY'), '-23', 'YY with negative year'); assert.equal(moment.utc().year(-123).format('YYYY'), '-0123', 'YYYY with negative year'); assert.equal(moment.utc().year(-1234).format('YY'), '-34', 'YY with negative year'); assert.equal(moment.utc().year(-1234).format('YYYY'), '-1234', 'YYYY with negative year'); assert.equal(moment.utc().year(-12345).format('YY'), '-45', 'YY with negative year'); assert.equal(moment.utc().year(-12345).format('YYYY'), '-12345', 'YYYY with negative year'); }); test('format milliseconds', function (assert) { var b = moment(new Date(2009, 1, 14, 15, 25, 50, 123)); assert.equal(b.format('S'), '1', 'Deciseconds'); assert.equal(b.format('SS'), '12', 'Centiseconds'); assert.equal(b.format('SSS'), '123', 'Milliseconds'); b.milliseconds(789); assert.equal(b.format('S'), '7', 'Deciseconds'); assert.equal(b.format('SS'), '78', 'Centiseconds'); assert.equal(b.format('SSS'), '789', 'Milliseconds'); }); test('format timezone', function (assert) { var b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)); assert.ok(b.format('Z').match(/^[\+\-]\d\d:\d\d$/), b.format('Z') + ' should be something like \'+07:30\''); assert.ok(b.format('ZZ').match(/^[\+\-]\d{4}$/), b.format('ZZ') + ' should be something like \'+0700\''); }); test('format multiple with utc offset', function (assert) { var b = moment('2012-10-08 -1200', ['YYYY-MM-DD HH:mm ZZ', 'YYYY-MM-DD ZZ', 'YYYY-MM-DD']); assert.equal(b.format('YYYY-MM'), '2012-10', 'Parsing multiple formats should not crash with different sized formats'); }); test('isDST', function (assert) { var janOffset = new Date(2011, 0, 1).getTimezoneOffset(), julOffset = new Date(2011, 6, 1).getTimezoneOffset(), janIsDst = janOffset < julOffset, julIsDst = julOffset < janOffset, jan1 = moment([2011]), jul1 = moment([2011, 6]); if (janIsDst && julIsDst) { assert.ok(0, 'January and July cannot both be in DST'); assert.ok(0, 'January and July cannot both be in DST'); } else if (janIsDst) { assert.ok(jan1.isDST(), 'January 1 is DST'); assert.ok(!jul1.isDST(), 'July 1 is not DST'); } else if (julIsDst) { assert.ok(!jan1.isDST(), 'January 1 is not DST'); assert.ok(jul1.isDST(), 'July 1 is DST'); } else { assert.ok(!jan1.isDST(), 'January 1 is not DST'); assert.ok(!jul1.isDST(), 'July 1 is not DST'); } }); test('unix timestamp', function (assert) { var m = moment('1234567890.123', 'X'); assert.equal(m.format('X'), '1234567890', 'unix timestamp without milliseconds'); assert.equal(m.format('X.S'), '1234567890.1', 'unix timestamp with deciseconds'); assert.equal(m.format('X.SS'), '1234567890.12', 'unix timestamp with centiseconds'); assert.equal(m.format('X.SSS'), '1234567890.123', 'unix timestamp with milliseconds'); m = moment(1234567890.123, 'X'); assert.equal(m.format('X'), '1234567890', 'unix timestamp as integer'); }); test('unix offset milliseconds', function (assert) { var m = moment('1234567890123', 'x'); assert.equal(m.format('x'), '1234567890123', 'unix offset in milliseconds'); m = moment(1234567890123, 'x'); assert.equal(m.format('x'), '1234567890123', 'unix offset in milliseconds as integer'); }); test('utcOffset sanity checks', function (assert) { assert.equal(moment().utcOffset() % 15, 0, 'utc offset should be a multiple of 15 (was ' + moment().utcOffset() + ')'); assert.equal(moment().utcOffset(), -(new Date()).getTimezoneOffset(), 'utcOffset should return the opposite of getTimezoneOffset'); }); test('default format', function (assert) { var isoRegex = /\d{4}.\d\d.\d\dT\d\d.\d\d.\d\d[\+\-]\d\d:\d\d/; assert.ok(isoRegex.exec(moment().format()), 'default format (' + moment().format() + ') should match ISO'); }); test('default UTC format', function (assert) { var isoRegex = /\d{4}.\d\d.\d\dT\d\d.\d\d.\d\dZ/; assert.ok(isoRegex.exec(moment.utc().format()), 'default UTC format (' + moment.utc().format() + ') should match ISO'); }); test('toJSON', function (assert) { var supportsJson = typeof JSON !== 'undefined' && JSON.stringify && JSON.stringify.call, date = moment('2012-10-09T21:30:40.678+0100'); assert.equal(date.toJSON(), '2012-10-09T20:30:40.678Z', 'should output ISO8601 on moment.fn.toJSON'); if (supportsJson) { assert.equal(JSON.stringify({ date : date }), '{"date":"2012-10-09T20:30:40.678Z"}', 'should output ISO8601 on JSON.stringify'); } }); test('toISOString', function (assert) { var date = moment.utc('2012-10-09T20:30:40.678'); assert.equal(date.toISOString(), '2012-10-09T20:30:40.678Z', 'should output ISO8601 on moment.fn.toISOString'); // big years date = moment.utc('+020123-10-09T20:30:40.678'); assert.equal(date.toISOString(), '+020123-10-09T20:30:40.678Z', 'ISO8601 format on big positive year'); // negative years date = moment.utc('-000001-10-09T20:30:40.678'); assert.equal(date.toISOString(), '-000001-10-09T20:30:40.678Z', 'ISO8601 format on negative year'); // big negative years date = moment.utc('-020123-10-09T20:30:40.678'); assert.equal(date.toISOString(), '-020123-10-09T20:30:40.678Z', 'ISO8601 format on big negative year'); }); test('long years', function (assert) { assert.equal(moment.utc().year(2).format('YYYYYY'), '+000002', 'small year with YYYYYY'); assert.equal(moment.utc().year(2012).format('YYYYYY'), '+002012', 'regular year with YYYYYY'); assert.equal(moment.utc().year(20123).format('YYYYYY'), '+020123', 'big year with YYYYYY'); assert.equal(moment.utc().year(-1).format('YYYYYY'), '-000001', 'small negative year with YYYYYY'); assert.equal(moment.utc().year(-2012).format('YYYYYY'), '-002012', 'negative year with YYYYYY'); assert.equal(moment.utc().year(-20123).format('YYYYYY'), '-020123', 'big negative year with YYYYYY'); }); test('iso week formats', function (assert) { // path_to_url var cases = { '2005-01-02': '2004-53', '2005-12-31': '2005-52', '2007-01-01': '2007-01', '2007-12-30': '2007-52', '2007-12-31': '2008-01', '2008-01-01': '2008-01', '2008-12-28': '2008-52', '2008-12-29': '2009-01', '2008-12-30': '2009-01', '2008-12-31': '2009-01', '2009-01-01': '2009-01', '2009-12-31': '2009-53', '2010-01-01': '2009-53', '2010-01-02': '2009-53', '2010-01-03': '2009-53', '404-12-31': '0404-53', '405-12-31': '0405-52' }, i, isoWeek, formatted2, formatted1; for (i in cases) { isoWeek = cases[i].split('-').pop(); formatted2 = moment(i, 'YYYY-MM-DD').format('WW'); assert.equal(isoWeek, formatted2, i + ': WW should be ' + isoWeek + ', but ' + formatted2); isoWeek = isoWeek.replace(/^0+/, ''); formatted1 = moment(i, 'YYYY-MM-DD').format('W'); assert.equal(isoWeek, formatted1, i + ': W should be ' + isoWeek + ', but ' + formatted1); } }); test('iso week year formats', function (assert) { // path_to_url var cases = { '2005-01-02': '2004-53', '2005-12-31': '2005-52', '2007-01-01': '2007-01', '2007-12-30': '2007-52', '2007-12-31': '2008-01', '2008-01-01': '2008-01', '2008-12-28': '2008-52', '2008-12-29': '2009-01', '2008-12-30': '2009-01', '2008-12-31': '2009-01', '2009-01-01': '2009-01', '2009-12-31': '2009-53', '2010-01-01': '2009-53', '2010-01-02': '2009-53', '2010-01-03': '2009-53', '404-12-31': '0404-53', '405-12-31': '0405-52' }, i, isoWeekYear, formatted5, formatted4, formatted2; for (i in cases) { isoWeekYear = cases[i].split('-')[0]; formatted5 = moment(i, 'YYYY-MM-DD').format('GGGGG'); assert.equal('0' + isoWeekYear, formatted5, i + ': GGGGG should be ' + isoWeekYear + ', but ' + formatted5); formatted4 = moment(i, 'YYYY-MM-DD').format('GGGG'); assert.equal(isoWeekYear, formatted4, i + ': GGGG should be ' + isoWeekYear + ', but ' + formatted4); formatted2 = moment(i, 'YYYY-MM-DD').format('GG'); assert.equal(isoWeekYear.slice(2, 4), formatted2, i + ': GG should be ' + isoWeekYear + ', but ' + formatted2); } }); test('week year formats', function (assert) { // path_to_url var cases = { '2005-01-02': '2004-53', '2005-12-31': '2005-52', '2007-01-01': '2007-01', '2007-12-30': '2007-52', '2007-12-31': '2008-01', '2008-01-01': '2008-01', '2008-12-28': '2008-52', '2008-12-29': '2009-01', '2008-12-30': '2009-01', '2008-12-31': '2009-01', '2009-01-01': '2009-01', '2009-12-31': '2009-53', '2010-01-01': '2009-53', '2010-01-02': '2009-53', '2010-01-03': '2009-53', '404-12-31': '0404-53', '405-12-31': '0405-52' }, i, isoWeekYear, formatted5, formatted4, formatted2; moment.defineLocale('dow:1,doy:4', {week: {dow: 1, doy: 4}}); for (i in cases) { isoWeekYear = cases[i].split('-')[0]; formatted5 = moment(i, 'YYYY-MM-DD').format('ggggg'); assert.equal('0' + isoWeekYear, formatted5, i + ': ggggg should be ' + isoWeekYear + ', but ' + formatted5); formatted4 = moment(i, 'YYYY-MM-DD').format('gggg'); assert.equal(isoWeekYear, formatted4, i + ': gggg should be ' + isoWeekYear + ', but ' + formatted4); formatted2 = moment(i, 'YYYY-MM-DD').format('gg'); assert.equal(isoWeekYear.slice(2, 4), formatted2, i + ': gg should be ' + isoWeekYear + ', but ' + formatted2); } moment.defineLocale('dow:1,doy:4', null); }); test('iso weekday formats', function (assert) { assert.equal(moment([1985, 1, 4]).format('E'), '1', 'Feb 4 1985 is Monday -- 1st day'); assert.equal(moment([2029, 8, 18]).format('E'), '2', 'Sep 18 2029 is Tuesday -- 2nd day'); assert.equal(moment([2013, 3, 24]).format('E'), '3', 'Apr 24 2013 is Wednesday -- 3rd day'); assert.equal(moment([2015, 2, 5]).format('E'), '4', 'Mar 5 2015 is Thursday -- 4th day'); assert.equal(moment([1970, 0, 2]).format('E'), '5', 'Jan 2 1970 is Friday -- 5th day'); assert.equal(moment([2001, 4, 12]).format('E'), '6', 'May 12 2001 is Saturday -- 6th day'); assert.equal(moment([2000, 0, 2]).format('E'), '7', 'Jan 2 2000 is Sunday -- 7th day'); }); test('weekday formats', function (assert) { moment.defineLocale('dow: 3,doy: 5', {week: {dow: 3, doy: 5}}); assert.equal(moment([1985, 1, 6]).format('e'), '0', 'Feb 6 1985 is Wednesday -- 0th day'); assert.equal(moment([2029, 8, 20]).format('e'), '1', 'Sep 20 2029 is Thursday -- 1st day'); assert.equal(moment([2013, 3, 26]).format('e'), '2', 'Apr 26 2013 is Friday -- 2nd day'); assert.equal(moment([2015, 2, 7]).format('e'), '3', 'Mar 7 2015 is Saturday -- 3nd day'); assert.equal(moment([1970, 0, 4]).format('e'), '4', 'Jan 4 1970 is Sunday -- 4th day'); assert.equal(moment([2001, 4, 14]).format('e'), '5', 'May 14 2001 is Monday -- 5th day'); assert.equal(moment([2000, 0, 4]).format('e'), '6', 'Jan 4 2000 is Tuesday -- 6th day'); moment.defineLocale('dow: 3,doy: 5', null); }); test('toString is just human readable format', function (assert) { var b = moment(new Date(2009, 1, 5, 15, 25, 50, 125)); assert.equal(b.toString(), b.format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ')); }); test('toJSON skips postformat', function (assert) { moment.defineLocale('postformat', { postformat: function (s) { s.replace(/./g, 'X'); } }); assert.equal(moment.utc([2000, 0, 1]).toJSON(), '2000-01-01T00:00:00.000Z', 'toJSON doesn\'t postformat'); moment.defineLocale('postformat', null); }); test('calendar day timezone', function (assert) { moment.locale('en'); var zones = [60, -60, 90, -90, 360, -360, 720, -720], b = moment().utc().startOf('day').subtract({m : 1}), c = moment().local().startOf('day').subtract({m : 1}), d = moment().local().startOf('day').subtract({d : 2}), i, z, a; for (i = 0; i < zones.length; ++i) { z = zones[i]; a = moment().utcOffset(z).startOf('day').subtract({m: 1}); assert.equal(moment(a).utcOffset(z).calendar(), 'Yesterday at 11:59 PM', 'Yesterday at 11:59 PM, not Today, or the wrong time, tz = ' + z); } assert.equal(moment(b).utc().calendar(), 'Yesterday at 11:59 PM', 'Yesterday at 11:59 PM, not Today, or the wrong time'); assert.equal(moment(c).local().calendar(), 'Yesterday at 11:59 PM', 'Yesterday at 11:59 PM, not Today, or the wrong time'); assert.equal(moment(c).local().calendar(d), 'Tomorrow at 11:59 PM', 'Tomorrow at 11:59 PM, not Yesterday, or the wrong time'); }); test('calendar with custom formats', function (assert) { assert.equal(moment().calendar(null, {sameDay: '[Today]'}), 'Today', 'Today'); assert.equal(moment().add(1, 'days').calendar(null, {nextDay: '[Tomorrow]'}), 'Tomorrow', 'Tomorrow'); assert.equal(moment([1985, 1, 4]).calendar(null, {sameElse: 'YYYY-MM-DD'}), '1985-02-04', 'Else'); }); test('invalid', function (assert) { assert.equal(moment.invalid().format(), 'Invalid date'); assert.equal(moment.invalid().format('YYYY-MM-DD'), 'Invalid date'); }); test('quarter formats', function (assert) { assert.equal(moment([1985, 1, 4]).format('Q'), '1', 'Feb 4 1985 is Q1'); assert.equal(moment([2029, 8, 18]).format('Q'), '3', 'Sep 18 2029 is Q3'); assert.equal(moment([2013, 3, 24]).format('Q'), '2', 'Apr 24 2013 is Q2'); assert.equal(moment([2015, 2, 5]).format('Q'), '1', 'Mar 5 2015 is Q1'); assert.equal(moment([1970, 0, 2]).format('Q'), '1', 'Jan 2 1970 is Q1'); assert.equal(moment([2001, 11, 12]).format('Q'), '4', 'Dec 12 2001 is Q4'); assert.equal(moment([2000, 0, 2]).format('[Q]Q-YYYY'), 'Q1-2000', 'Jan 2 2000 is Q1'); }); test('quarter ordinal formats', function (assert) { assert.equal(moment([1985, 1, 4]).format('Qo'), '1st', 'Feb 4 1985 is 1st quarter'); assert.equal(moment([2029, 8, 18]).format('Qo'), '3rd', 'Sep 18 2029 is 3rd quarter'); assert.equal(moment([2013, 3, 24]).format('Qo'), '2nd', 'Apr 24 2013 is 2nd quarter'); assert.equal(moment([2015, 2, 5]).format('Qo'), '1st', 'Mar 5 2015 is 1st quarter'); assert.equal(moment([1970, 0, 2]).format('Qo'), '1st', 'Jan 2 1970 is 1st quarter'); assert.equal(moment([2001, 11, 12]).format('Qo'), '4th', 'Dec 12 2001 is 4th quarter'); assert.equal(moment([2000, 0, 2]).format('Qo [quarter] YYYY'), '1st quarter 2000', 'Jan 2 2000 is 1st quarter'); }); // test('full expanded format is returned from abbreviated formats', function (assert) { // function objectKeys(obj) { // if (Object.keys) { // return Object.keys(obj); // } else { // // IE8 // var res = [], i; // for (i in obj) { // if (obj.hasOwnProperty(i)) { // res.push(i); // } // } // return res; // } // } // var locales = // 'ar-sa ar-tn ar az be bg bn bo br bs ca cs cv cy da de-at de dv el ' + // 'en-au en-ca en-gb en-ie en-nz eo es et eu fa fi fo fr-ca fr-ch fr fy ' + // 'gd gl he hi hr hu hy-am id is it ja jv ka kk km ko lb lo lt lv me mk ml ' + // 'mr ms-my ms my nb ne nl nn pl pt-br pt ro ru se si sk sl sq sr-cyrl ' + // 'sr sv sw ta te th tl-ph tlh tr tzl tzm-latn tzm uk uz vi zh-cn zh-tw'; // each(locales.split(' '), function (locale) { // var data, tokens; // data = moment().locale(locale).localeData()._longDateFormat; // tokens = objectKeys(data); // each(tokens, function (token) { // // Check each format string to make sure it does not contain any // // tokens that need to be expanded. // each(tokens, function (i) { // // strip escaped sequences // var format = data[i].replace(/(\[[^\]]*\])/g, ''); // assert.equal(false, !!~format.indexOf(token), 'locale ' + locale + ' contains ' + token + ' in ' + i); // }); // }); // }); // }); test('milliseconds', function (assert) { var m = moment('123', 'SSS'); assert.equal(m.format('S'), '1'); assert.equal(m.format('SS'), '12'); assert.equal(m.format('SSS'), '123'); assert.equal(m.format('SSSS'), '1230'); assert.equal(m.format('SSSSS'), '12300'); assert.equal(m.format('SSSSSS'), '123000'); assert.equal(m.format('SSSSSSS'), '1230000'); assert.equal(m.format('SSSSSSSS'), '12300000'); assert.equal(m.format('SSSSSSSSS'), '123000000'); }); test('hmm and hmmss', function (assert) { assert.equal(moment('12:34:56', 'HH:mm:ss').format('hmm'), '1234'); assert.equal(moment('01:34:56', 'HH:mm:ss').format('hmm'), '134'); assert.equal(moment('13:34:56', 'HH:mm:ss').format('hmm'), '134'); assert.equal(moment('12:34:56', 'HH:mm:ss').format('hmmss'), '123456'); assert.equal(moment('01:34:56', 'HH:mm:ss').format('hmmss'), '13456'); assert.equal(moment('13:34:56', 'HH:mm:ss').format('hmmss'), '13456'); }); test('Hmm and Hmmss', function (assert) { assert.equal(moment('12:34:56', 'HH:mm:ss').format('Hmm'), '1234'); assert.equal(moment('01:34:56', 'HH:mm:ss').format('Hmm'), '134'); assert.equal(moment('13:34:56', 'HH:mm:ss').format('Hmm'), '1334'); assert.equal(moment('12:34:56', 'HH:mm:ss').format('Hmmss'), '123456'); assert.equal(moment('01:34:56', 'HH:mm:ss').format('Hmmss'), '13456'); assert.equal(moment('08:34:56', 'HH:mm:ss').format('Hmmss'), '83456'); assert.equal(moment('18:34:56', 'HH:mm:ss').format('Hmmss'), '183456'); }); test('k and kk', function (assert) { assert.equal(moment('01:23:45', 'HH:mm:ss').format('k'), '1'); assert.equal(moment('12:34:56', 'HH:mm:ss').format('k'), '12'); assert.equal(moment('01:23:45', 'HH:mm:ss').format('kk'), '01'); assert.equal(moment('12:34:56', 'HH:mm:ss').format('kk'), '12'); assert.equal(moment('00:34:56', 'HH:mm:ss').format('kk'), '24'); assert.equal(moment('00:00:00', 'HH:mm:ss').format('kk'), '24'); }); test('Y token', function (assert) { assert.equal(moment('2010-01-01', 'YYYY-MM-DD', true).format('Y'), '2010', 'format 2010 with Y'); assert.equal(moment('-123-01-01', 'Y-MM-DD', true).format('Y'), '-123', 'format -123 with Y'); assert.equal(moment('12345-01-01', 'Y-MM-DD', true).format('Y'), '+12345', 'format 12345 with Y'); assert.equal(moment('0-01-01', 'Y-MM-DD', true).format('Y'), '0', 'format 0 with Y'); assert.equal(moment('1-01-01', 'Y-MM-DD', true).format('Y'), '1', 'format 1 with Y'); assert.equal(moment('9999-01-01', 'Y-MM-DD', true).format('Y'), '9999', 'format 9999 with Y'); assert.equal(moment('10000-01-01', 'Y-MM-DD', true).format('Y'), '+10000', 'format 10000 with Y'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('from_to'); test('from', function (assert) { var start = moment(); moment.locale('en'); assert.equal(start.from(start.clone().add(5, 'seconds')), 'a few seconds ago', '5 seconds = a few seconds ago'); assert.equal(start.from(start.clone().add(1, 'minute')), 'a minute ago', '1 minute = a minute ago'); assert.equal(start.from(start.clone().add(5, 'minutes')), '5 minutes ago', '5 minutes = 5 minutes ago'); assert.equal(start.from(start.clone().subtract(5, 'seconds')), 'in a few seconds', '5 seconds = in a few seconds'); assert.equal(start.from(start.clone().subtract(1, 'minute')), 'in a minute', '1 minute = in a minute'); assert.equal(start.from(start.clone().subtract(5, 'minutes')), 'in 5 minutes', '5 minutes = in 5 minutes'); }); test('from with absolute duration', function (assert) { var start = moment(); moment.locale('en'); assert.equal(start.from(start.clone().add(5, 'seconds'), true), 'a few seconds', '5 seconds = a few seconds'); assert.equal(start.from(start.clone().add(1, 'minute'), true), 'a minute', '1 minute = a minute'); assert.equal(start.from(start.clone().add(5, 'minutes'), true), '5 minutes', '5 minutes = 5 minutes'); assert.equal(start.from(start.clone().subtract(5, 'seconds'), true), 'a few seconds', '5 seconds = a few seconds'); assert.equal(start.from(start.clone().subtract(1, 'minute'), true), 'a minute', '1 minute = a minute'); assert.equal(start.from(start.clone().subtract(5, 'minutes'), true), '5 minutes', '5 minutes = 5 minutes'); }); test('to', function (assert) { var start = moment(); moment.locale('en'); assert.equal(start.to(start.clone().subtract(5, 'seconds')), 'a few seconds ago', '5 seconds = a few seconds ago'); assert.equal(start.to(start.clone().subtract(1, 'minute')), 'a minute ago', '1 minute = a minute ago'); assert.equal(start.to(start.clone().subtract(5, 'minutes')), '5 minutes ago', '5 minutes = 5 minutes ago'); assert.equal(start.to(start.clone().add(5, 'seconds')), 'in a few seconds', '5 seconds = in a few seconds'); assert.equal(start.to(start.clone().add(1, 'minute')), 'in a minute', '1 minute = in a minute'); assert.equal(start.to(start.clone().add(5, 'minutes')), 'in 5 minutes', '5 minutes = in 5 minutes'); }); test('to with absolute duration', function (assert) { var start = moment(); moment.locale('en'); assert.equal(start.to(start.clone().add(5, 'seconds'), true), 'a few seconds', '5 seconds = a few seconds'); assert.equal(start.to(start.clone().add(1, 'minute'), true), 'a minute', '1 minute = a minute'); assert.equal(start.to(start.clone().add(5, 'minutes'), true), '5 minutes', '5 minutes = 5 minutes'); assert.equal(start.to(start.clone().subtract(5, 'seconds'), true), 'a few seconds', '5 seconds = a few seconds'); assert.equal(start.to(start.clone().subtract(1, 'minute'), true), 'a minute', '1 minute = a minute'); assert.equal(start.to(start.clone().subtract(5, 'minutes'), true), '5 minutes', '5 minutes = 5 minutes'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('getters and setters'); test('getters', function (assert) { var a = moment([2011, 9, 12, 6, 7, 8, 9]); assert.equal(a.year(), 2011, 'year'); assert.equal(a.month(), 9, 'month'); assert.equal(a.date(), 12, 'date'); assert.equal(a.day(), 3, 'day'); assert.equal(a.hours(), 6, 'hour'); assert.equal(a.minutes(), 7, 'minute'); assert.equal(a.seconds(), 8, 'second'); assert.equal(a.milliseconds(), 9, 'milliseconds'); }); test('getters programmatic', function (assert) { var a = moment([2011, 9, 12, 6, 7, 8, 9]); assert.equal(a.get('year'), 2011, 'year'); assert.equal(a.get('month'), 9, 'month'); assert.equal(a.get('date'), 12, 'date'); assert.equal(a.get('day'), 3, 'day'); assert.equal(a.get('hour'), 6, 'hour'); assert.equal(a.get('minute'), 7, 'minute'); assert.equal(a.get('second'), 8, 'second'); assert.equal(a.get('milliseconds'), 9, 'milliseconds'); //actual getters tested elsewhere assert.equal(a.get('weekday'), a.weekday(), 'weekday'); assert.equal(a.get('isoWeekday'), a.isoWeekday(), 'isoWeekday'); assert.equal(a.get('week'), a.week(), 'week'); assert.equal(a.get('isoWeek'), a.isoWeek(), 'isoWeek'); assert.equal(a.get('dayOfYear'), a.dayOfYear(), 'dayOfYear'); }); test('setters plural', function (assert) { var a = moment(); test.expectedDeprecations('years accessor', 'months accessor', 'dates accessor'); a.years(2011); a.months(9); a.dates(12); a.hours(6); a.minutes(7); a.seconds(8); a.milliseconds(9); assert.equal(a.years(), 2011, 'years'); assert.equal(a.months(), 9, 'months'); assert.equal(a.dates(), 12, 'dates'); assert.equal(a.days(), 3, 'days'); assert.equal(a.hours(), 6, 'hours'); assert.equal(a.minutes(), 7, 'minutes'); assert.equal(a.seconds(), 8, 'seconds'); assert.equal(a.milliseconds(), 9, 'milliseconds'); }); test('setters singular', function (assert) { var a = moment(); a.year(2011); a.month(9); a.date(12); a.hour(6); a.minute(7); a.second(8); a.millisecond(9); assert.equal(a.year(), 2011, 'year'); assert.equal(a.month(), 9, 'month'); assert.equal(a.date(), 12, 'date'); assert.equal(a.day(), 3, 'day'); assert.equal(a.hour(), 6, 'hour'); assert.equal(a.minute(), 7, 'minute'); assert.equal(a.second(), 8, 'second'); assert.equal(a.millisecond(), 9, 'milliseconds'); }); test('setters', function (assert) { var a = moment(); a.year(2011); a.month(9); a.date(12); a.hours(6); a.minutes(7); a.seconds(8); a.milliseconds(9); assert.equal(a.year(), 2011, 'year'); assert.equal(a.month(), 9, 'month'); assert.equal(a.date(), 12, 'date'); assert.equal(a.day(), 3, 'day'); assert.equal(a.hours(), 6, 'hour'); assert.equal(a.minutes(), 7, 'minute'); assert.equal(a.seconds(), 8, 'second'); assert.equal(a.milliseconds(), 9, 'milliseconds'); // Test month() behavior. See path_to_url a = moment('20130531', 'YYYYMMDD'); a.month(3); assert.equal(a.month(), 3, 'month edge case'); }); test('setter programmatic', function (assert) { var a = moment(); a.set('year', 2011); a.set('month', 9); a.set('date', 12); a.set('hours', 6); a.set('minutes', 7); a.set('seconds', 8); a.set('milliseconds', 9); assert.equal(a.year(), 2011, 'year'); assert.equal(a.month(), 9, 'month'); assert.equal(a.date(), 12, 'date'); assert.equal(a.day(), 3, 'day'); assert.equal(a.hours(), 6, 'hour'); assert.equal(a.minutes(), 7, 'minute'); assert.equal(a.seconds(), 8, 'second'); assert.equal(a.milliseconds(), 9, 'milliseconds'); // Test month() behavior. See path_to_url a = moment('20130531', 'YYYYMMDD'); a.month(3); assert.equal(a.month(), 3, 'month edge case'); }); test('setters programatic with weeks', function (assert) { var a = moment(); a.set('weekYear', 2001); a.set('week', 49); a.set('day', 4); assert.equal(a.weekYear(), 2001, 'weekYear'); assert.equal(a.week(), 49, 'week'); assert.equal(a.day(), 4, 'day'); a.set('weekday', 1); assert.equal(a.weekday(), 1, 'weekday'); }); test('setters programatic with weeks ISO', function (assert) { var a = moment(); a.set('isoWeekYear', 2001); a.set('isoWeek', 49); a.set('isoWeekday', 4); assert.equal(a.isoWeekYear(), 2001, 'isoWeekYear'); assert.equal(a.isoWeek(), 49, 'isoWeek'); assert.equal(a.isoWeekday(), 4, 'isoWeekday'); }); test('setters strings', function (assert) { var a = moment([2012]).locale('en'); assert.equal(a.clone().day(0).day('Wednesday').day(), 3, 'day full name'); assert.equal(a.clone().day(0).day('Wed').day(), 3, 'day short name'); assert.equal(a.clone().day(0).day('We').day(), 3, 'day minimal name'); assert.equal(a.clone().day(0).day('invalid').day(), 0, 'invalid day name'); assert.equal(a.clone().month(0).month('April').month(), 3, 'month full name'); assert.equal(a.clone().month(0).month('Apr').month(), 3, 'month short name'); assert.equal(a.clone().month(0).month('invalid').month(), 0, 'invalid month name'); }); test('setters - falsey values', function (assert) { var a = moment(); // ensure minutes wasn't coincidentally 0 already a.minutes(1); a.minutes(0); assert.equal(a.minutes(), 0, 'falsey value'); }); test('chaining setters', function (assert) { var a = moment(); a.year(2011) .month(9) .date(12) .hours(6) .minutes(7) .seconds(8); assert.equal(a.year(), 2011, 'year'); assert.equal(a.month(), 9, 'month'); assert.equal(a.date(), 12, 'date'); assert.equal(a.day(), 3, 'day'); assert.equal(a.hours(), 6, 'hour'); assert.equal(a.minutes(), 7, 'minute'); assert.equal(a.seconds(), 8, 'second'); }); test('setter with multiple unit values', function (assert) { var a = moment(); a.set({ year: 2011, month: 9, date: 12, hours: 6, minutes: 7, seconds: 8, milliseconds: 9 }); assert.equal(a.year(), 2011, 'year'); assert.equal(a.month(), 9, 'month'); assert.equal(a.date(), 12, 'date'); assert.equal(a.day(), 3, 'day'); assert.equal(a.hours(), 6, 'hour'); assert.equal(a.minutes(), 7, 'minute'); assert.equal(a.seconds(), 8, 'second'); assert.equal(a.milliseconds(), 9, 'milliseconds'); }); test('day setter', function (assert) { var a = moment([2011, 0, 15]); assert.equal(moment(a).day(0).date(), 9, 'set from saturday to sunday'); assert.equal(moment(a).day(6).date(), 15, 'set from saturday to saturday'); assert.equal(moment(a).day(3).date(), 12, 'set from saturday to wednesday'); a = moment([2011, 0, 9]); assert.equal(moment(a).day(0).date(), 9, 'set from sunday to sunday'); assert.equal(moment(a).day(6).date(), 15, 'set from sunday to saturday'); assert.equal(moment(a).day(3).date(), 12, 'set from sunday to wednesday'); a = moment([2011, 0, 12]); assert.equal(moment(a).day(0).date(), 9, 'set from wednesday to sunday'); assert.equal(moment(a).day(6).date(), 15, 'set from wednesday to saturday'); assert.equal(moment(a).day(3).date(), 12, 'set from wednesday to wednesday'); assert.equal(moment(a).day(-7).date(), 2, 'set from wednesday to last sunday'); assert.equal(moment(a).day(-1).date(), 8, 'set from wednesday to last saturday'); assert.equal(moment(a).day(-4).date(), 5, 'set from wednesday to last wednesday'); assert.equal(moment(a).day(7).date(), 16, 'set from wednesday to next sunday'); assert.equal(moment(a).day(13).date(), 22, 'set from wednesday to next saturday'); assert.equal(moment(a).day(10).date(), 19, 'set from wednesday to next wednesday'); assert.equal(moment(a).day(14).date(), 23, 'set from wednesday to second next sunday'); assert.equal(moment(a).day(20).date(), 29, 'set from wednesday to second next saturday'); assert.equal(moment(a).day(17).date(), 26, 'set from wednesday to second next wednesday'); }); test('string setters', function (assert) { var a = moment(); a.year('2011'); a.month('9'); a.date('12'); a.hours('6'); a.minutes('7'); a.seconds('8'); a.milliseconds('9'); assert.equal(a.year(), 2011, 'year'); assert.equal(a.month(), 9, 'month'); assert.equal(a.date(), 12, 'date'); assert.equal(a.day(), 3, 'day'); assert.equal(a.hours(), 6, 'hour'); assert.equal(a.minutes(), 7, 'minute'); assert.equal(a.seconds(), 8, 'second'); assert.equal(a.milliseconds(), 9, 'milliseconds'); }); test('setters across DST +1', function (assert) { var oldUpdateOffset = moment.updateOffset, // Based on a real story somewhere in America/Los_Angeles dstAt = moment('2014-03-09T02:00:00-08:00').parseZone(), m; moment.updateOffset = function (mom, keepTime) { if (mom.isBefore(dstAt)) { mom.utcOffset(-8, keepTime); } else { mom.utcOffset(-7, keepTime); } }; m = moment('2014-03-15T00:00:00-07:00').parseZone(); m.year(2013); assert.equal(m.format(), '2013-03-15T00:00:00-08:00', 'year across +1'); m = moment('2014-03-15T00:00:00-07:00').parseZone(); m.month(0); assert.equal(m.format(), '2014-01-15T00:00:00-08:00', 'month across +1'); m = moment('2014-03-15T00:00:00-07:00').parseZone(); m.date(1); assert.equal(m.format(), '2014-03-01T00:00:00-08:00', 'date across +1'); m = moment('2014-03-09T03:05:00-07:00').parseZone(); m.hour(0); assert.equal(m.format(), '2014-03-09T00:05:00-08:00', 'hour across +1'); moment.updateOffset = oldUpdateOffset; }); test('setters across DST -1', function (assert) { var oldUpdateOffset = moment.updateOffset, // Based on a real story somewhere in America/Los_Angeles dstAt = moment('2014-11-02T02:00:00-07:00').parseZone(), m; moment.updateOffset = function (mom, keepTime) { if (mom.isBefore(dstAt)) { mom.utcOffset(-7, keepTime); } else { mom.utcOffset(-8, keepTime); } }; m = moment('2014-11-15T00:00:00-08:00').parseZone(); m.year(2013); assert.equal(m.format(), '2013-11-15T00:00:00-07:00', 'year across -1'); m = moment('2014-11-15T00:00:00-08:00').parseZone(); m.month(0); assert.equal(m.format(), '2014-01-15T00:00:00-07:00', 'month across -1'); m = moment('2014-11-15T00:00:00-08:00').parseZone(); m.date(1); assert.equal(m.format(), '2014-11-01T00:00:00-07:00', 'date across -1'); m = moment('2014-11-02T03:30:00-08:00').parseZone(); m.hour(0); assert.equal(m.format(), '2014-11-02T00:30:00-07:00', 'hour across -1'); moment.updateOffset = oldUpdateOffset; }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('instanceof'); test('instanceof', function (assert) { var mm = moment([2010, 0, 1]); var extend = function (a, b) { var i; for (i in b) { a[i] = b[i]; } return a; }; assert.equal(moment() instanceof moment, true, 'simple moment object'); assert.equal(extend({}, moment()) instanceof moment, false, 'extended moment object'); assert.equal(moment(null) instanceof moment, true, 'invalid moment object'); assert.equal(new Date() instanceof moment, false, 'date object is not moment object'); assert.equal(Object instanceof moment, false, 'Object is not moment object'); assert.equal('foo' instanceof moment, false, 'string is not moment object'); assert.equal(1 instanceof moment, false, 'number is not moment object'); assert.equal(NaN instanceof moment, false, 'NaN is not moment object'); assert.equal(null instanceof moment, false, 'null is not moment object'); assert.equal(undefined instanceof moment, false, 'undefined is not moment object'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('invalid'); test('invalid', function (assert) { var m = moment.invalid(); assert.equal(m.isValid(), false); assert.equal(m.parsingFlags().userInvalidated, true); assert.ok(isNaN(m.valueOf())); }); test('invalid with existing flag', function (assert) { var m = moment.invalid({invalidMonth : 'whatchamacallit'}); assert.equal(m.isValid(), false); assert.equal(m.parsingFlags().userInvalidated, false); assert.equal(m.parsingFlags().invalidMonth, 'whatchamacallit'); assert.ok(isNaN(m.valueOf())); }); test('invalid with custom flag', function (assert) { var m = moment.invalid({tooBusyWith : 'reiculating splines'}); assert.equal(m.isValid(), false); assert.equal(m.parsingFlags().userInvalidated, false); assert.equal(m.parsingFlags().tooBusyWith, 'reiculating splines'); assert.ok(isNaN(m.valueOf())); }); test('invalid operations', function (assert) { var invalids = [ moment.invalid(), moment('xyz', 'l'), moment('2015-01-35', 'YYYY-MM-DD'), moment('2015-01-25 a', 'YYYY-MM-DD', true) ], i, invalid, valid = moment(); test.expectedDeprecations('moment().min', 'moment().max'); for (i = 0; i < invalids.length; ++i) { invalid = invalids[i]; assert.ok(!invalid.clone().add(5, 'hours').isValid(), 'invalid.add is invalid'); assert.equal(invalid.calendar(), 'Invalid date', 'invalid.calendar is \'Invalid date\''); assert.ok(!invalid.clone().isValid(), 'invalid.clone is invalid'); assert.ok(isNaN(invalid.diff(valid)), 'invalid.diff(valid) is NaN'); assert.ok(isNaN(valid.diff(invalid)), 'valid.diff(invalid) is NaN'); assert.ok(isNaN(invalid.diff(invalid)), 'invalid.diff(invalid) is NaN'); assert.ok(!invalid.clone().endOf('month').isValid(), 'invalid.endOf is invalid'); assert.equal(invalid.format(), 'Invalid date', 'invalid.format is \'Invalid date\''); assert.equal(invalid.from(), 'Invalid date'); assert.equal(invalid.from(valid), 'Invalid date'); assert.equal(valid.from(invalid), 'Invalid date'); assert.equal(invalid.fromNow(), 'Invalid date'); assert.equal(invalid.to(), 'Invalid date'); assert.equal(invalid.to(valid), 'Invalid date'); assert.equal(valid.to(invalid), 'Invalid date'); assert.equal(invalid.toNow(), 'Invalid date'); assert.ok(isNaN(invalid.get('year')), 'invalid.get is NaN'); // TODO invalidAt assert.ok(!invalid.isAfter(valid)); assert.ok(!valid.isAfter(invalid)); assert.ok(!invalid.isAfter(invalid)); assert.ok(!invalid.isBefore(valid)); assert.ok(!valid.isBefore(invalid)); assert.ok(!invalid.isBefore(invalid)); assert.ok(!invalid.isBetween(valid, valid)); assert.ok(!valid.isBetween(invalid, valid)); assert.ok(!valid.isBetween(valid, invalid)); assert.ok(!invalid.isSame(invalid)); assert.ok(!invalid.isSame(valid)); assert.ok(!valid.isSame(invalid)); assert.ok(!invalid.isValid()); assert.equal(invalid.locale(), 'en'); assert.equal(invalid.localeData()._abbr, 'en'); assert.ok(!invalid.clone().max(valid).isValid()); assert.ok(!valid.clone().max(invalid).isValid()); assert.ok(!invalid.clone().max(invalid).isValid()); assert.ok(!invalid.clone().min(valid).isValid()); assert.ok(!valid.clone().min(invalid).isValid()); assert.ok(!invalid.clone().min(invalid).isValid()); assert.ok(!moment.min(invalid, valid).isValid()); assert.ok(!moment.min(valid, invalid).isValid()); assert.ok(!moment.max(invalid, valid).isValid()); assert.ok(!moment.max(valid, invalid).isValid()); assert.ok(!invalid.clone().set('year', 2005).isValid()); assert.ok(!invalid.clone().startOf('month').isValid()); assert.ok(!invalid.clone().subtract(5, 'days').isValid()); assert.deepEqual(invalid.toArray(), [NaN, NaN, NaN, NaN, NaN, NaN, NaN]); assert.deepEqual(invalid.toObject(), { years: NaN, months: NaN, date: NaN, hours: NaN, minutes: NaN, seconds: NaN, milliseconds: NaN }); assert.ok(moment.isDate(invalid.toDate())); assert.ok(isNaN(invalid.toDate().valueOf())); assert.equal(invalid.toJSON(), null); assert.equal(invalid.toString(), 'Invalid date'); assert.ok(isNaN(invalid.unix())); assert.ok(isNaN(invalid.valueOf())); assert.ok(isNaN(invalid.year())); assert.ok(isNaN(invalid.weekYear())); assert.ok(isNaN(invalid.isoWeekYear())); assert.ok(isNaN(invalid.quarter())); assert.ok(isNaN(invalid.quarters())); assert.ok(isNaN(invalid.month())); assert.ok(isNaN(invalid.daysInMonth())); assert.ok(isNaN(invalid.week())); assert.ok(isNaN(invalid.weeks())); assert.ok(isNaN(invalid.isoWeek())); assert.ok(isNaN(invalid.isoWeeks())); assert.ok(isNaN(invalid.weeksInYear())); assert.ok(isNaN(invalid.isoWeeksInYear())); assert.ok(isNaN(invalid.date())); assert.ok(isNaN(invalid.day())); assert.ok(isNaN(invalid.days())); assert.ok(isNaN(invalid.weekday())); assert.ok(isNaN(invalid.isoWeekday())); assert.ok(isNaN(invalid.dayOfYear())); assert.ok(isNaN(invalid.hour())); assert.ok(isNaN(invalid.hours())); assert.ok(isNaN(invalid.minute())); assert.ok(isNaN(invalid.minutes())); assert.ok(isNaN(invalid.second())); assert.ok(isNaN(invalid.seconds())); assert.ok(isNaN(invalid.millisecond())); assert.ok(isNaN(invalid.milliseconds())); assert.ok(isNaN(invalid.utcOffset())); assert.ok(!invalid.clone().year(2001).isValid()); assert.ok(!invalid.clone().weekYear(2001).isValid()); assert.ok(!invalid.clone().isoWeekYear(2001).isValid()); assert.ok(!invalid.clone().quarter(1).isValid()); assert.ok(!invalid.clone().quarters(1).isValid()); assert.ok(!invalid.clone().month(1).isValid()); assert.ok(!invalid.clone().week(1).isValid()); assert.ok(!invalid.clone().weeks(1).isValid()); assert.ok(!invalid.clone().isoWeek(1).isValid()); assert.ok(!invalid.clone().isoWeeks(1).isValid()); assert.ok(!invalid.clone().date(1).isValid()); assert.ok(!invalid.clone().day(1).isValid()); assert.ok(!invalid.clone().days(1).isValid()); assert.ok(!invalid.clone().weekday(1).isValid()); assert.ok(!invalid.clone().isoWeekday(1).isValid()); assert.ok(!invalid.clone().dayOfYear(1).isValid()); assert.ok(!invalid.clone().hour(1).isValid()); assert.ok(!invalid.clone().hours(1).isValid()); assert.ok(!invalid.clone().minute(1).isValid()); assert.ok(!invalid.clone().minutes(1).isValid()); assert.ok(!invalid.clone().second(1).isValid()); assert.ok(!invalid.clone().seconds(1).isValid()); assert.ok(!invalid.clone().millisecond(1).isValid()); assert.ok(!invalid.clone().milliseconds(1).isValid()); assert.ok(!invalid.clone().utcOffset(1).isValid()); assert.ok(!invalid.clone().utc().isValid()); assert.ok(!invalid.clone().local().isValid()); assert.ok(!invalid.clone().parseZone('05:30').isValid()); assert.ok(!invalid.hasAlignedHourOffset()); assert.ok(!invalid.isDST()); assert.ok(!invalid.isDSTShifted()); assert.ok(!invalid.isLocal()); assert.ok(!invalid.isUtcOffset()); assert.ok(!invalid.isUtc()); assert.ok(!invalid.isUTC()); assert.ok(!invalid.isLeapYear()); assert.equal(moment.duration({from: invalid, to: valid}).asMilliseconds(), 0); assert.equal(moment.duration({from: valid, to: invalid}).asMilliseconds(), 0); assert.equal(moment.duration({from: invalid, to: invalid}).asMilliseconds(), 0); } }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('is after'); test('is after without units', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 10)), mCopy = moment(m); assert.equal(m.isAfter(moment(new Date(2012, 3, 2, 3, 5, 5, 10))), false, 'year is later'); assert.equal(m.isAfter(moment(new Date(2010, 3, 2, 3, 3, 5, 10))), true, 'year is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 4, 2, 3, 4, 5, 10))), false, 'month is later'); assert.equal(m.isAfter(moment(new Date(2011, 2, 2, 3, 4, 5, 10))), true, 'month is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 3, 3, 4, 5, 10))), false, 'day is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 1, 3, 4, 5, 10))), true, 'day is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 4, 4, 5, 10))), false, 'hour is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 2, 4, 5, 10))), true, 'hour is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 5, 5, 10))), false, 'minute is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 3, 5, 10))), true, 'minute is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 6, 10))), false, 'second is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 4, 11))), true, 'second is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 5, 10))), false, 'millisecond match'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 5, 11))), false, 'millisecond is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 5, 9))), true, 'millisecond is earlier'); assert.equal(m.isAfter(m), false, 'moments are not after themselves'); assert.equal(+m, +mCopy, 'isAfter second should not change moment'); }); test('is after year', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isAfter(moment(new Date(2011, 5, 6, 7, 8, 9, 10)), 'year'), false, 'year match'); assert.equal(m.isAfter(moment(new Date(2010, 5, 6, 7, 8, 9, 10)), 'years'), true, 'plural should work'); assert.equal(m.isAfter(moment(new Date(2013, 5, 6, 7, 8, 9, 10)), 'year'), false, 'year is later'); assert.equal(m.isAfter(moment(new Date(2010, 5, 6, 7, 8, 9, 10)), 'year'), true, 'year is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 0, 1, 0, 0, 0, 0)), 'year'), false, 'exact start of year'); assert.equal(m.isAfter(moment(new Date(2011, 11, 31, 23, 59, 59, 999)), 'year'), false, 'exact end of year'); assert.equal(m.isAfter(moment(new Date(2012, 0, 1, 0, 0, 0, 0)), 'year'), false, 'start of next year'); assert.equal(m.isAfter(moment(new Date(2010, 11, 31, 23, 59, 59, 999)), 'year'), true, 'end of previous year'); assert.equal(m.isAfter(moment(new Date(1980, 11, 31, 23, 59, 59, 999)), 'year'), true, 'end of year far before'); assert.equal(m.isAfter(m, 'year'), false, 'same moments are not after the same year'); assert.equal(+m, +mCopy, 'isAfter year should not change moment'); }); test('is after month', function (assert) { var m = moment(new Date(2011, 2, 3, 4, 5, 6, 7)), mCopy = moment(m); assert.equal(m.isAfter(moment(new Date(2011, 2, 6, 7, 8, 9, 10)), 'month'), false, 'month match'); assert.equal(m.isAfter(moment(new Date(2010, 2, 6, 7, 8, 9, 10)), 'months'), true, 'plural should work'); assert.equal(m.isAfter(moment(new Date(2012, 2, 6, 7, 8, 9, 10)), 'month'), false, 'year is later'); assert.equal(m.isAfter(moment(new Date(2010, 2, 6, 7, 8, 9, 10)), 'month'), true, 'year is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 5, 6, 7, 8, 9, 10)), 'month'), false, 'month is later'); assert.equal(m.isAfter(moment(new Date(2011, 1, 6, 7, 8, 9, 10)), 'month'), true, 'month is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 2, 1, 0, 0, 0, 0)), 'month'), false, 'exact start of month'); assert.equal(m.isAfter(moment(new Date(2011, 2, 31, 23, 59, 59, 999)), 'month'), false, 'exact end of month'); assert.equal(m.isAfter(moment(new Date(2011, 3, 1, 0, 0, 0, 0)), 'month'), false, 'start of next month'); assert.equal(m.isAfter(moment(new Date(2011, 1, 27, 23, 59, 59, 999)), 'month'), true, 'end of previous month'); assert.equal(m.isAfter(moment(new Date(2010, 12, 31, 23, 59, 59, 999)), 'month'), true, 'later month but earlier year'); assert.equal(m.isAfter(m, 'month'), false, 'same moments are not after the same month'); assert.equal(+m, +mCopy, 'isAfter month should not change moment'); }); test('is after day', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 7, 8, 9, 10)), 'day'), false, 'day match'); assert.equal(m.isAfter(moment(new Date(2010, 3, 2, 7, 8, 9, 10)), 'days'), true, 'plural should work'); assert.equal(m.isAfter(moment(new Date(2012, 3, 2, 7, 8, 9, 10)), 'day'), false, 'year is later'); assert.equal(m.isAfter(moment(new Date(2010, 3, 2, 7, 8, 9, 10)), 'day'), true, 'year is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 4, 2, 7, 8, 9, 10)), 'day'), false, 'month is later'); assert.equal(m.isAfter(moment(new Date(2011, 2, 2, 7, 8, 9, 10)), 'day'), true, 'month is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 3, 7, 8, 9, 10)), 'day'), false, 'day is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 1, 7, 8, 9, 10)), 'day'), true, 'day is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 0, 0, 0, 0)), 'day'), false, 'exact start of day'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 23, 59, 59, 999)), 'day'), false, 'exact end of day'); assert.equal(m.isAfter(moment(new Date(2011, 3, 3, 0, 0, 0, 0)), 'day'), false, 'start of next day'); assert.equal(m.isAfter(moment(new Date(2011, 3, 1, 23, 59, 59, 999)), 'day'), true, 'end of previous day'); assert.equal(m.isAfter(moment(new Date(2010, 3, 10, 0, 0, 0, 0)), 'day'), true, 'later day but earlier year'); assert.equal(m.isAfter(m, 'day'), false, 'same moments are not after the same day'); assert.equal(+m, +mCopy, 'isAfter day should not change moment'); }); test('is after hour', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 8, 9, 10)), 'hour'), false, 'hour match'); assert.equal(m.isAfter(moment(new Date(2010, 3, 2, 3, 8, 9, 10)), 'hours'), true, 'plural should work'); assert.equal(m.isAfter(moment(new Date(2012, 3, 2, 3, 8, 9, 10)), 'hour'), false, 'year is later'); assert.equal(m.isAfter(moment(new Date(2010, 3, 2, 3, 8, 9, 10)), 'hour'), true, 'year is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 4, 2, 3, 8, 9, 10)), 'hour'), false, 'month is later'); assert.equal(m.isAfter(moment(new Date(2011, 1, 2, 3, 8, 9, 10)), 'hour'), true, 'month is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 3, 3, 8, 9, 10)), 'hour'), false, 'day is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 1, 3, 8, 9, 10)), 'hour'), true, 'day is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 4, 8, 9, 10)), 'hour'), false, 'hour is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 8, 9, 10)), 'hour'), false, 'hour is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 0, 0, 0)), 'hour'), false, 'exact start of hour'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 59, 59, 999)), 'hour'), false, 'exact end of hour'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 4, 0, 0, 0)), 'hour'), false, 'start of next hour'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 2, 59, 59, 999)), 'hour'), true, 'end of previous hour'); assert.equal(m.isAfter(m, 'hour'), false, 'same moments are not after the same hour'); assert.equal(+m, +mCopy, 'isAfter hour should not change moment'); }); test('is after minute', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 9, 10)), 'minute'), false, 'minute match'); assert.equal(m.isAfter(moment(new Date(2010, 3, 2, 3, 4, 9, 10)), 'minutes'), true, 'plural should work'); assert.equal(m.isAfter(moment(new Date(2012, 3, 2, 3, 4, 9, 10)), 'minute'), false, 'year is later'); assert.equal(m.isAfter(moment(new Date(2010, 3, 2, 3, 4, 9, 10)), 'minute'), true, 'year is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 4, 2, 3, 4, 9, 10)), 'minute'), false, 'month is later'); assert.equal(m.isAfter(moment(new Date(2011, 2, 2, 3, 4, 9, 10)), 'minute'), true, 'month is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 3, 3, 4, 9, 10)), 'minute'), false, 'day is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 1, 3, 4, 9, 10)), 'minute'), true, 'day is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 4, 4, 9, 10)), 'minute'), false, 'hour is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 2, 4, 9, 10)), 'minute'), true, 'hour is earler'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 5, 9, 10)), 'minute'), false, 'minute is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 3, 9, 10)), 'minute'), true, 'minute is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 0, 0)), 'minute'), false, 'exact start of minute'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 59, 999)), 'minute'), false, 'exact end of minute'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 5, 0, 0)), 'minute'), false, 'start of next minute'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 3, 59, 999)), 'minute'), true, 'end of previous minute'); assert.equal(m.isAfter(m, 'minute'), false, 'same moments are not after the same minute'); assert.equal(+m, +mCopy, 'isAfter minute should not change moment'); }); test('is after second', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 10)), mCopy = moment(m); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'second'), false, 'second match'); assert.equal(m.isAfter(moment(new Date(2010, 3, 2, 3, 4, 5, 10)), 'seconds'), true, 'plural should work'); assert.equal(m.isAfter(moment(new Date(2012, 3, 2, 3, 4, 5, 10)), 'second'), false, 'year is later'); assert.equal(m.isAfter(moment(new Date(2010, 3, 2, 3, 4, 5, 10)), 'second'), true, 'year is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 4, 2, 3, 4, 5, 10)), 'second'), false, 'month is later'); assert.equal(m.isAfter(moment(new Date(2011, 2, 2, 3, 4, 5, 10)), 'second'), true, 'month is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 3, 3, 4, 5, 10)), 'second'), false, 'day is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 1, 1, 4, 5, 10)), 'second'), true, 'day is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 4, 4, 5, 10)), 'second'), false, 'hour is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 1, 4, 1, 5, 10)), 'second'), true, 'hour is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 5, 5, 10)), 'second'), false, 'minute is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 3, 5, 10)), 'second'), true, 'minute is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 6, 10)), 'second'), false, 'second is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 4, 5)), 'second'), true, 'second is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 5, 0)), 'second'), false, 'exact start of second'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 5, 999)), 'second'), false, 'exact end of second'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 6, 0)), 'second'), false, 'start of next second'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 4, 999)), 'second'), true, 'end of previous second'); assert.equal(m.isAfter(m, 'second'), false, 'same moments are not after the same second'); assert.equal(+m, +mCopy, 'isAfter second should not change moment'); }); test('is after millisecond', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 10)), mCopy = moment(m); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'millisecond'), false, 'millisecond match'); assert.equal(m.isAfter(moment(new Date(2010, 3, 2, 3, 4, 5, 10)), 'milliseconds'), true, 'plural should work'); assert.equal(m.isAfter(moment(new Date(2012, 3, 2, 3, 4, 5, 10)), 'millisecond'), false, 'year is later'); assert.equal(m.isAfter(moment(new Date(2010, 3, 2, 3, 4, 5, 10)), 'millisecond'), true, 'year is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 4, 2, 3, 4, 5, 10)), 'millisecond'), false, 'month is later'); assert.equal(m.isAfter(moment(new Date(2011, 2, 2, 3, 4, 5, 10)), 'millisecond'), true, 'month is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 3, 3, 4, 5, 10)), 'millisecond'), false, 'day is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 1, 1, 4, 5, 10)), 'millisecond'), true, 'day is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 4, 4, 5, 10)), 'millisecond'), false, 'hour is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 1, 4, 1, 5, 10)), 'millisecond'), true, 'hour is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 5, 5, 10)), 'millisecond'), false, 'minute is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 3, 5, 10)), 'millisecond'), true, 'minute is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 6, 10)), 'millisecond'), false, 'second is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 4, 5)), 'millisecond'), true, 'second is earlier'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 6, 11)), 'millisecond'), false, 'millisecond is later'); assert.equal(m.isAfter(moment(new Date(2011, 3, 2, 3, 4, 4, 9)), 'millisecond'), true, 'millisecond is earlier'); assert.equal(m.isAfter(m, 'millisecond'), false, 'same moments are not after the same millisecond'); assert.equal(+m, +mCopy, 'isAfter millisecond should not change moment'); }); test('is after invalid', function (assert) { var m = moment(), invalid = moment.invalid(); assert.equal(m.isAfter(invalid), false, 'valid moment is not after invalid moment'); assert.equal(invalid.isAfter(m), false, 'invalid moment is not after valid moment'); assert.equal(m.isAfter(invalid, 'year'), false, 'invalid moment year'); assert.equal(m.isAfter(invalid, 'month'), false, 'invalid moment month'); assert.equal(m.isAfter(invalid, 'day'), false, 'invalid moment day'); assert.equal(m.isAfter(invalid, 'hour'), false, 'invalid moment hour'); assert.equal(m.isAfter(invalid, 'minute'), false, 'invalid moment minute'); assert.equal(m.isAfter(invalid, 'second'), false, 'invalid moment second'); assert.equal(m.isAfter(invalid, 'milliseconds'), false, 'invalid moment milliseconds'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } function isArray(input) { return input instanceof Array || Object.prototype.toString.call(input) === '[object Array]'; } test('isArray recognizes Array objects', function (assert) { assert.ok(isArray([1,2,3]), 'array args'); assert.ok(isArray([]), 'empty array'); assert.ok(isArray(new Array(1,2,3)), 'array constructor'); }); test('isArray rejects non-Array objects', function (assert) { assert.ok(!isArray(), 'nothing'); assert.ok(!isArray(undefined), 'undefined'); assert.ok(!isArray(null), 'null'); assert.ok(!isArray(123), 'number'); assert.ok(!isArray('[1,2,3]'), 'string'); assert.ok(!isArray(new Date()), 'date'); assert.ok(!isArray({a:1,b:2}), 'object'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('is before'); test('is after without units', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 10)), mCopy = moment(m); assert.equal(m.isBefore(moment(new Date(2012, 3, 2, 3, 5, 5, 10))), true, 'year is later'); assert.equal(m.isBefore(moment(new Date(2010, 3, 2, 3, 3, 5, 10))), false, 'year is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 4, 2, 3, 4, 5, 10))), true, 'month is later'); assert.equal(m.isBefore(moment(new Date(2011, 2, 2, 3, 4, 5, 10))), false, 'month is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 3, 3, 4, 5, 10))), true, 'day is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 1, 3, 4, 5, 10))), false, 'day is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 4, 4, 5, 10))), true, 'hour is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 2, 4, 5, 10))), false, 'hour is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 5, 5, 10))), true, 'minute is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 3, 5, 10))), false, 'minute is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 6, 10))), true, 'second is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 4, 11))), false, 'second is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 5, 10))), false, 'millisecond match'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 5, 11))), true, 'millisecond is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 5, 9))), false, 'millisecond is earlier'); assert.equal(m.isBefore(m), false, 'moments are not before themselves'); assert.equal(+m, +mCopy, 'isBefore second should not change moment'); }); test('is before year', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isBefore(moment(new Date(2011, 5, 6, 7, 8, 9, 10)), 'year'), false, 'year match'); assert.equal(m.isBefore(moment(new Date(2012, 5, 6, 7, 8, 9, 10)), 'years'), true, 'plural should work'); assert.equal(m.isBefore(moment(new Date(2013, 5, 6, 7, 8, 9, 10)), 'year'), true, 'year is later'); assert.equal(m.isBefore(moment(new Date(2010, 5, 6, 7, 8, 9, 10)), 'year'), false, 'year is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 0, 1, 0, 0, 0, 0)), 'year'), false, 'exact start of year'); assert.equal(m.isBefore(moment(new Date(2011, 11, 31, 23, 59, 59, 999)), 'year'), false, 'exact end of year'); assert.equal(m.isBefore(moment(new Date(2012, 0, 1, 0, 0, 0, 0)), 'year'), true, 'start of next year'); assert.equal(m.isBefore(moment(new Date(2010, 11, 31, 23, 59, 59, 999)), 'year'), false, 'end of previous year'); assert.equal(m.isBefore(moment(new Date(1980, 11, 31, 23, 59, 59, 999)), 'year'), false, 'end of year far before'); assert.equal(m.isBefore(m, 'year'), false, 'same moments are not before the same year'); assert.equal(+m, +mCopy, 'isBefore year should not change moment'); }); test('is before month', function (assert) { var m = moment(new Date(2011, 2, 3, 4, 5, 6, 7)), mCopy = moment(m); assert.equal(m.isBefore(moment(new Date(2011, 2, 6, 7, 8, 9, 10)), 'month'), false, 'month match'); assert.equal(m.isBefore(moment(new Date(2012, 2, 6, 7, 8, 9, 10)), 'months'), true, 'plural should work'); assert.equal(m.isBefore(moment(new Date(2012, 2, 6, 7, 8, 9, 10)), 'month'), true, 'year is later'); assert.equal(m.isBefore(moment(new Date(2010, 2, 6, 7, 8, 9, 10)), 'month'), false, 'year is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 5, 6, 7, 8, 9, 10)), 'month'), true, 'month is later'); assert.equal(m.isBefore(moment(new Date(2011, 1, 6, 7, 8, 9, 10)), 'month'), false, 'month is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 2, 1, 0, 0, 0, 0)), 'month'), false, 'exact start of month'); assert.equal(m.isBefore(moment(new Date(2011, 2, 31, 23, 59, 59, 999)), 'month'), false, 'exact end of month'); assert.equal(m.isBefore(moment(new Date(2011, 3, 1, 0, 0, 0, 0)), 'month'), true, 'start of next month'); assert.equal(m.isBefore(moment(new Date(2011, 1, 27, 23, 59, 59, 999)), 'month'), false, 'end of previous month'); assert.equal(m.isBefore(moment(new Date(2010, 12, 31, 23, 59, 59, 999)), 'month'), false, 'later month but earlier year'); assert.equal(m.isBefore(m, 'month'), false, 'same moments are not before the same month'); assert.equal(+m, +mCopy, 'isBefore month should not change moment'); }); test('is before day', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 7, 8, 9, 10)), 'day'), false, 'day match'); assert.equal(m.isBefore(moment(new Date(2012, 3, 2, 7, 8, 9, 10)), 'days'), true, 'plural should work'); assert.equal(m.isBefore(moment(new Date(2012, 3, 2, 7, 8, 9, 10)), 'day'), true, 'year is later'); assert.equal(m.isBefore(moment(new Date(2010, 3, 2, 7, 8, 9, 10)), 'day'), false, 'year is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 4, 2, 7, 8, 9, 10)), 'day'), true, 'month is later'); assert.equal(m.isBefore(moment(new Date(2011, 2, 2, 7, 8, 9, 10)), 'day'), false, 'month is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 3, 7, 8, 9, 10)), 'day'), true, 'day is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 1, 7, 8, 9, 10)), 'day'), false, 'day is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 0, 0, 0, 0)), 'day'), false, 'exact start of day'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 23, 59, 59, 999)), 'day'), false, 'exact end of day'); assert.equal(m.isBefore(moment(new Date(2011, 3, 3, 0, 0, 0, 0)), 'day'), true, 'start of next day'); assert.equal(m.isBefore(moment(new Date(2011, 3, 1, 23, 59, 59, 999)), 'day'), false, 'end of previous day'); assert.equal(m.isBefore(moment(new Date(2010, 3, 10, 0, 0, 0, 0)), 'day'), false, 'later day but earlier year'); assert.equal(m.isBefore(m, 'day'), false, 'same moments are not before the same day'); assert.equal(+m, +mCopy, 'isBefore day should not change moment'); }); test('is before hour', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 8, 9, 10)), 'hour'), false, 'hour match'); assert.equal(m.isBefore(moment(new Date(2012, 3, 2, 3, 8, 9, 10)), 'hours'), true, 'plural should work'); assert.equal(m.isBefore(moment(new Date(2012, 3, 2, 3, 8, 9, 10)), 'hour'), true, 'year is later'); assert.equal(m.isBefore(moment(new Date(2010, 3, 2, 3, 8, 9, 10)), 'hour'), false, 'year is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 4, 2, 3, 8, 9, 10)), 'hour'), true, 'month is later'); assert.equal(m.isBefore(moment(new Date(2011, 1, 2, 3, 8, 9, 10)), 'hour'), false, 'month is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 3, 3, 8, 9, 10)), 'hour'), true, 'day is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 1, 3, 8, 9, 10)), 'hour'), false, 'day is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 4, 8, 9, 10)), 'hour'), true, 'hour is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 8, 9, 10)), 'hour'), false, 'hour is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 0, 0, 0)), 'hour'), false, 'exact start of hour'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 59, 59, 999)), 'hour'), false, 'exact end of hour'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 4, 0, 0, 0)), 'hour'), true, 'start of next hour'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 2, 59, 59, 999)), 'hour'), false, 'end of previous hour'); assert.equal(m.isBefore(m, 'hour'), false, 'same moments are not before the same hour'); assert.equal(+m, +mCopy, 'isBefore hour should not change moment'); }); test('is before minute', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 9, 10)), 'minute'), false, 'minute match'); assert.equal(m.isBefore(moment(new Date(2012, 3, 2, 3, 4, 9, 10)), 'minutes'), true, 'plural should work'); assert.equal(m.isBefore(moment(new Date(2012, 3, 2, 3, 4, 9, 10)), 'minute'), true, 'year is later'); assert.equal(m.isBefore(moment(new Date(2010, 3, 2, 3, 4, 9, 10)), 'minute'), false, 'year is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 4, 2, 3, 4, 9, 10)), 'minute'), true, 'month is later'); assert.equal(m.isBefore(moment(new Date(2011, 2, 2, 3, 4, 9, 10)), 'minute'), false, 'month is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 3, 3, 4, 9, 10)), 'minute'), true, 'day is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 1, 3, 4, 9, 10)), 'minute'), false, 'day is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 4, 4, 9, 10)), 'minute'), true, 'hour is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 2, 4, 9, 10)), 'minute'), false, 'hour is earler'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 5, 9, 10)), 'minute'), true, 'minute is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 3, 9, 10)), 'minute'), false, 'minute is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 0, 0)), 'minute'), false, 'exact start of minute'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 59, 999)), 'minute'), false, 'exact end of minute'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 5, 0, 0)), 'minute'), true, 'start of next minute'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 3, 59, 999)), 'minute'), false, 'end of previous minute'); assert.equal(m.isBefore(m, 'minute'), false, 'same moments are not before the same minute'); assert.equal(+m, +mCopy, 'isBefore minute should not change moment'); }); test('is before second', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 10)), mCopy = moment(m); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'second'), false, 'second match'); assert.equal(m.isBefore(moment(new Date(2012, 3, 2, 3, 4, 5, 10)), 'seconds'), true, 'plural should work'); assert.equal(m.isBefore(moment(new Date(2012, 3, 2, 3, 4, 5, 10)), 'second'), true, 'year is later'); assert.equal(m.isBefore(moment(new Date(2010, 3, 2, 3, 4, 5, 10)), 'second'), false, 'year is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 4, 2, 3, 4, 5, 10)), 'second'), true, 'month is later'); assert.equal(m.isBefore(moment(new Date(2011, 2, 2, 3, 4, 5, 10)), 'second'), false, 'month is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 3, 3, 4, 5, 10)), 'second'), true, 'day is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 1, 1, 4, 5, 10)), 'second'), false, 'day is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 4, 4, 5, 10)), 'second'), true, 'hour is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 1, 4, 1, 5, 10)), 'second'), false, 'hour is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 5, 5, 10)), 'second'), true, 'minute is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 3, 5, 10)), 'second'), false, 'minute is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 6, 10)), 'second'), true, 'second is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 4, 5)), 'second'), false, 'second is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 5, 0)), 'second'), false, 'exact start of second'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 5, 999)), 'second'), false, 'exact end of second'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 6, 0)), 'second'), true, 'start of next second'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 4, 999)), 'second'), false, 'end of previous second'); assert.equal(m.isBefore(m, 'second'), false, 'same moments are not before the same second'); assert.equal(+m, +mCopy, 'isBefore second should not change moment'); }); test('is before millisecond', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 10)), mCopy = moment(m); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'millisecond'), false, 'millisecond match'); assert.equal(m.isBefore(moment(new Date(2010, 3, 2, 3, 4, 5, 10)), 'milliseconds'), false, 'plural should work'); assert.equal(m.isBefore(moment(new Date(2012, 3, 2, 3, 4, 5, 10)), 'millisecond'), true, 'year is later'); assert.equal(m.isBefore(moment(new Date(2010, 3, 2, 3, 4, 5, 10)), 'millisecond'), false, 'year is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 4, 2, 3, 4, 5, 10)), 'millisecond'), true, 'month is later'); assert.equal(m.isBefore(moment(new Date(2011, 2, 2, 3, 4, 5, 10)), 'millisecond'), false, 'month is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 3, 3, 4, 5, 10)), 'millisecond'), true, 'day is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 1, 1, 4, 5, 10)), 'millisecond'), false, 'day is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 4, 4, 5, 10)), 'millisecond'), true, 'hour is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 1, 4, 1, 5, 10)), 'millisecond'), false, 'hour is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 5, 5, 10)), 'millisecond'), true, 'minute is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 3, 5, 10)), 'millisecond'), false, 'minute is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 6, 10)), 'millisecond'), true, 'second is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 4, 5)), 'millisecond'), false, 'second is earlier'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 6, 11)), 'millisecond'), true, 'millisecond is later'); assert.equal(m.isBefore(moment(new Date(2011, 3, 2, 3, 4, 4, 9)), 'millisecond'), false, 'millisecond is earlier'); assert.equal(m.isBefore(m, 'millisecond'), false, 'same moments are not before the same millisecond'); assert.equal(+m, +mCopy, 'isBefore millisecond should not change moment'); }); test('is before invalid', function (assert) { var m = moment(), invalid = moment.invalid(); assert.equal(m.isBefore(invalid), false, 'valid moment is not before invalid moment'); assert.equal(invalid.isBefore(m), false, 'invalid moment is not before valid moment'); assert.equal(m.isBefore(invalid, 'year'), false, 'invalid moment year'); assert.equal(m.isBefore(invalid, 'month'), false, 'invalid moment month'); assert.equal(m.isBefore(invalid, 'day'), false, 'invalid moment day'); assert.equal(m.isBefore(invalid, 'hour'), false, 'invalid moment hour'); assert.equal(m.isBefore(invalid, 'minute'), false, 'invalid moment minute'); assert.equal(m.isBefore(invalid, 'second'), false, 'invalid moment second'); assert.equal(m.isBefore(invalid, 'milliseconds'), false, 'invalid moment milliseconds'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('is between'); test('is between without units', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 10)), mCopy = moment(m); assert.equal(m.isBetween( moment(new Date(2009, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10))), false, 'year is later'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2013, 3, 2, 3, 4, 5, 10))), false, 'year is earlier'); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10))), true, 'year is between'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10))), false, 'month is later'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 5, 2, 3, 4, 5, 10))), false, 'month is earlier'); assert.equal(m.isBetween( moment(new Date(2011, 2, 2, 3, 4, 5, 10)), moment(new Date(2011, 4, 2, 3, 4, 5, 10))), true, 'month is between'); assert.equal(m.isBetween( moment(new Date(2011, 3, 1, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10))), false, 'day is later'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 4, 3, 4, 5, 10))), false, 'day is earlier'); assert.equal(m.isBetween( moment(new Date(2011, 3, 1, 3, 4, 5, 10)), moment(new Date(2011, 3, 3, 3, 4, 5, 10))), true, 'day is between'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 1, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10))), false, 'hour is later'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 5, 4, 5, 10))), false, 'hour is earlier'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 2, 4, 5, 10)), moment(new Date(2011, 3, 2, 4, 4, 5, 10))), true, 'hour is between'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 6, 5, 10))), false, 'minute is later'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 2, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10))), false, 'minute is earlier'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 3, 5, 10)), moment(new Date(2011, 3, 2, 3, 5, 5, 10))), true, 'minute is between'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 7, 10))), false, 'second is later'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 3, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10))), false, 'second is earlier'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 4, 10)), moment(new Date(2011, 3, 2, 3, 4, 6, 10))), true, 'second is between'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 12))), false, 'millisecond is later'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 8)), moment(new Date(2011, 3, 2, 3, 4, 5, 10))), false, 'millisecond is earlier'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 9)), moment(new Date(2011, 3, 2, 3, 4, 5, 11))), true, 'millisecond is between'); assert.equal(m.isBetween(m, m), false, 'moments are not between themselves'); assert.equal(+m, +mCopy, 'isBetween second should not change moment'); }); test('is between without units inclusivity', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 10)), mCopy = moment(m); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10)), null, '()'), false, 'start and end are excluded, start is equal to moment'); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10)), null, '()'), false, 'start and end are excluded, end is equal to moment'); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10)), null, '()'), true, 'start and end are excluded, is between'); assert.equal(m.isBetween( moment(new Date(2009, 3, 2, 3, 4, 5, 10)), moment(new Date(2010, 3, 2, 3, 4, 5, 10)), null, '()'), false, 'start and end are excluded, is not between'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10)), null, '()'), false, 'start and end are excluded, should fail on same start/end date.'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10)), null, '(]'), false, 'start is excluded and end is included should fail on same start date'); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10)), null, '(]'), true, 'start is excluded and end is included should succeed on end date'); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10)), null, '(]'), true, 'start is excluded and end is included, is between'); assert.equal(m.isBetween( moment(new Date(2009, 3, 2, 3, 4, 5, 10)), moment(new Date(2010, 3, 2, 3, 4, 5, 10)), null, '(]'), false, 'start is excluded and end is included, is not between'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10)), null, '(]'), false, 'start is excluded and end is included, should fail on same start/end date.'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10)), null, '[)'), true, 'start is included and end is excluded should succeed on same start date'); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10)), null, '[)'), false, 'start is included and end is excluded should fail on same end date'); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10)), null, '[)'), true, 'start is included and end is excluded, is between'); assert.equal(m.isBetween( moment(new Date(2009, 3, 2, 3, 4, 5, 10)), moment(new Date(2010, 3, 2, 3, 4, 5, 10)), null, '[)'), false, 'start is included and end is excluded, is not between'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10)), null, '[)'), false, 'start is included and end is excluded, should fail on same end and start date'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10)), null, '[]'), true, 'start and end inclusive should succeed on same start date'); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10)), null, '[]'), true, 'start and end inclusive should succeed on same end date'); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10)), null, '[]'), true, 'start and end inclusive, is between'); assert.equal(m.isBetween( moment(new Date(2009, 3, 2, 3, 4, 5, 10)), moment(new Date(2010, 3, 2, 3, 4, 5, 10)), null, '[]'), false, 'start and end inclusive, is not between'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10)), null, '[]'), true, 'start and end inclusive, should handle same end and start date'); }); test('is between milliseconds inclusivity', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 10)), mCopy = moment(m); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10)), 'milliseconds'), true, 'options, no inclusive'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10)), 'milliseconds', '()'), false, 'start and end are excluded, start is equal to moment'); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'milliseconds', '()'), false, 'start and end are excluded, end is equal to moment'); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10)), 'milliseconds', '()'), true, 'start and end are excluded, is between'); assert.equal(m.isBetween( moment(new Date(2009, 3, 2, 3, 4, 5, 10)), moment(new Date(2010, 3, 2, 3, 4, 5, 10)), 'milliseconds', '()'), false, 'start and end are excluded, is not between'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'milliseconds', '()'), false, 'start and end are excluded, should fail on same start/end date.'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10)), 'milliseconds', '(]'), false, 'start is excluded and end is included should fail on same start date'); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'milliseconds', '(]'), true, 'start is excluded and end is included should succeed on end date'); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10)), 'milliseconds', '(]'), true, 'start is excluded and end is included, is between'); assert.equal(m.isBetween( moment(new Date(2009, 3, 2, 3, 4, 5, 10)), moment(new Date(2010, 3, 2, 3, 4, 5, 10)), 'milliseconds', '(]'), false, 'start is excluded and end is included, is not between'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'milliseconds', '(]'), false, 'start is excluded and end is included, should fail on same start/end date.'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10)), 'milliseconds', '[)'), true, 'start is included and end is excluded should succeed on same start date'); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'milliseconds', '[)'), false, 'start is included and end is excluded should fail on same end date'); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10)), 'milliseconds', '[)'), true, 'start is included and end is excluded, is between'); assert.equal(m.isBetween( moment(new Date(2009, 3, 2, 3, 4, 5, 10)), moment(new Date(2010, 3, 2, 3, 4, 5, 10)), 'milliseconds', '[)'), false, 'start is included and end is excluded, is not between'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'milliseconds', '[)'), false, 'start is included and end is excluded, should fail on same end and start date'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10)), 'milliseconds', '[]'), true, 'start and end inclusive should succeed on same start date'); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'milliseconds', '[]'), true, 'start and end inclusive should succeed on same end date'); assert.equal(m.isBetween( moment(new Date(2010, 3, 2, 3, 4, 5, 10)), moment(new Date(2012, 3, 2, 3, 4, 5, 10)), 'milliseconds', '[]'), true, 'start and end inclusive, is between'); assert.equal(m.isBetween( moment(new Date(2009, 3, 2, 3, 4, 5, 10)), moment(new Date(2010, 3, 2, 3, 4, 5, 10)), 'milliseconds', '[]'), false, 'start and end inclusive, is not between'); assert.equal(m.isBetween( moment(new Date(2011, 3, 2, 3, 4, 5, 10)), moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'milliseconds', '[]'), true, 'start and end inclusive, should handle same end and start date'); }); test('is between year', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isBetween( moment(new Date(2011, 5, 6, 7, 8, 9, 10)), moment(new Date(2011, 5, 6, 7, 8, 9, 10)), 'year'), false, 'year match'); assert.equal(m.isBetween( moment(new Date(2010, 5, 6, 7, 8, 9, 10)), moment(new Date(2012, 5, 6, 7, 8, 9, 10)), 'years'), true, 'plural should work'); assert.equal(m.isBetween( moment(new Date(2010, 5, 6, 7, 8, 9, 10)), moment(new Date(2012, 5, 6, 7, 8, 9, 10)), 'year'), true, 'year is between'); assert.equal(m.isBetween( moment(new Date(2011, 5, 6, 7, 8, 9, 10)), moment(new Date(2013, 5, 6, 7, 8, 9, 10)), 'year'), false, 'year is earlier'); assert.equal(m.isBetween( moment(new Date(2010, 5, 6, 7, 8, 9, 10)), moment(new Date(2011, 5, 6, 7, 8, 9, 10)), 'year'), false, 'year is later'); assert.equal(m.isBetween(m, 'year'), false, 'same moments are not between the same year'); assert.equal(+m, +mCopy, 'isBetween year should not change moment'); }); test('is between month', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isBetween( moment(new Date(2011, 1, 6, 7, 8, 9, 10)), moment(new Date(2011, 1, 6, 7, 8, 9, 10)), 'month'), false, 'month match'); assert.equal(m.isBetween( moment(new Date(2011, 0, 6, 7, 8, 9, 10)), moment(new Date(2011, 2, 6, 7, 8, 9, 10)), 'months'), true, 'plural should work'); assert.equal(m.isBetween( moment(new Date(2011, 0, 31, 23, 59, 59, 999)), moment(new Date(2011, 2, 1, 0, 0, 0, 0)), 'month'), true, 'month is between'); assert.equal(m.isBetween( moment(new Date(2011, 1, 6, 7, 8, 9, 10)), moment(new Date(2011, 2, 6, 7, 8, 9, 10)), 'month'), false, 'month is earlier'); assert.equal(m.isBetween( moment(new Date(2011, 11, 6, 7, 8, 9, 10)), moment(new Date(2011, 1, 6, 7, 8, 9, 10)), 'month'), false, 'month is later'); assert.equal(m.isBetween(m, 'month'), false, 'same moments are not between the same month'); assert.equal(+m, +mCopy, 'isBetween month should not change moment'); }); test('is between day', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 7, 8, 9, 10)), moment(new Date(2011, 1, 2, 7, 8, 9, 10)), 'day'), false, 'day match'); assert.equal(m.isBetween( moment(new Date(2011, 1, 1, 7, 8, 9, 10)), moment(new Date(2011, 1, 3, 7, 8, 9, 10)), 'days'), true, 'plural should work'); assert.equal(m.isBetween( moment(new Date(2011, 1, 1, 7, 8, 9, 10)), moment(new Date(2011, 1, 3, 7, 8, 9, 10)), 'day'), true, 'day is between'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 7, 8, 9, 10)), moment(new Date(2011, 1, 4, 7, 8, 9, 10)), 'day'), false, 'day is earlier'); assert.equal(m.isBetween( moment(new Date(2011, 1, 1, 7, 8, 9, 10)), moment(new Date(2011, 1, 2, 7, 8, 9, 10)), 'day'), false, 'day is later'); assert.equal(m.isBetween(m, 'day'), false, 'same moments are not between the same day'); assert.equal(+m, +mCopy, 'isBetween day should not change moment'); }); test('is between hour', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 3, 5, 9, 10)), moment(new Date(2011, 1, 2, 3, 9, 9, 10)), 'hour'), false, 'hour match'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 1, 59, 59, 999)), moment(new Date(2011, 1, 2, 4, 0, 0, 0)), 'hours'), true, 'plural should work'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 2, 59, 59, 999)), moment(new Date(2011, 1, 2, 4, 0, 0, 0)), 'hour'), true, 'hour is between'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 7, 8, 9, 10)), moment(new Date(2011, 1, 2, 7, 8, 9, 10)), 'hour'), false, 'hour is earlier'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 7, 8, 9, 10)), moment(new Date(2011, 1, 2, 7, 8, 9, 10)), 'hour'), false, 'hour is later'); assert.equal(m.isBetween(m, 'hour'), false, 'same moments are not between the same hour'); assert.equal(+m, +mCopy, 'isBetween hour should not change moment'); }); test('is between minute', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 3, 4, 9, 10)), moment(new Date(2011, 1, 2, 3, 4, 9, 10)), 'minute'), false, 'minute match'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 3, 3, 9, 10)), moment(new Date(2011, 1, 2, 3, 5, 9, 10)), 'minutes'), true, 'plural should work'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 3, 3, 59, 999)), moment(new Date(2011, 1, 2, 3, 5, 0, 0)), 'minute'), true, 'minute is between'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 3, 5, 0, 0)), moment(new Date(2011, 1, 2, 3, 8, 9, 10)), 'minute'), false, 'minute is earlier'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 3, 2, 9, 10)), moment(new Date(2011, 1, 2, 3, 3, 59, 999)), 'minute'), false, 'minute is later'); assert.equal(m.isBetween(m, 'minute'), false, 'same moments are not between the same minute'); assert.equal(+m, +mCopy, 'isBetween minute should not change moment'); }); test('is between second', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 3, 4, 5, 10)), moment(new Date(2011, 1, 2, 3, 4, 5, 10)), 'second'), false, 'second match'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 3, 4, 4, 10)), moment(new Date(2011, 1, 2, 3, 4, 6, 10)), 'seconds'), true, 'plural should work'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 3, 4, 4, 999)), moment(new Date(2011, 1, 2, 3, 4, 6, 0)), 'second'), true, 'second is between'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 3, 4, 6, 0)), moment(new Date(2011, 1, 2, 3, 4, 7, 10)), 'second'), false, 'second is earlier'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 3, 4, 3, 10)), moment(new Date(2011, 1, 2, 3, 4, 4, 999)), 'second'), false, 'second is later'); assert.equal(m.isBetween(m, 'second'), false, 'same moments are not between the same second'); assert.equal(+m, +mCopy, 'isBetween second should not change moment'); }); test('is between millisecond', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 3, 4, 5, 6)), moment(new Date(2011, 1, 2, 3, 4, 5, 6)), 'millisecond'), false, 'millisecond match'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 3, 4, 5, 5)), moment(new Date(2011, 1, 2, 3, 4, 5, 7)), 'milliseconds'), true, 'plural should work'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 3, 4, 5, 5)), moment(new Date(2011, 1, 2, 3, 4, 5, 7)), 'millisecond'), true, 'millisecond is between'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 3, 4, 5, 7)), moment(new Date(2011, 1, 2, 3, 4, 5, 10)), 'millisecond'), false, 'millisecond is earlier'); assert.equal(m.isBetween( moment(new Date(2011, 1, 2, 3, 4, 5, 4)), moment(new Date(2011, 1, 2, 3, 4, 5, 6)), 'millisecond'), false, 'millisecond is later'); assert.equal(m.isBetween(m, 'millisecond'), false, 'same moments are not between the same millisecond'); assert.equal(+m, +mCopy, 'isBetween millisecond should not change moment'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('is date'); test('isDate recognizes Date objects', function (assert) { assert.ok(moment.isDate(new Date()), 'no args (now)'); assert.ok(moment.isDate(new Date([2014, 2, 15])), 'array args'); assert.ok(moment.isDate(new Date('2014-03-15')), 'string args'); assert.ok(moment.isDate(new Date('does NOT look like a date')), 'invalid date'); }); test('isDate rejects non-Date objects', function (assert) { assert.ok(!moment.isDate(), 'nothing'); assert.ok(!moment.isDate(undefined), 'undefined'); assert.ok(!moment.isDate(null), 'string args'); assert.ok(!moment.isDate(42), 'number'); assert.ok(!moment.isDate('2014-03-15'), 'string'); assert.ok(!moment.isDate([2014, 2, 15]), 'array'); assert.ok(!moment.isDate({year: 2014, month: 2, day: 15}), 'object'); assert.ok(!moment.isDate({toString: function () { return '[object Date]'; }}), 'lying object'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('is moment'); test('is moment object', function (assert) { var MyObj = function () {}, extend = function (a, b) { var i; for (i in b) { a[i] = b[i]; } return a; }; MyObj.prototype.toDate = function () { return new Date(); }; assert.ok(moment.isMoment(moment()), 'simple moment object'); assert.ok(moment.isMoment(moment(null)), 'invalid moment object'); assert.ok(moment.isMoment(extend({}, moment())), 'externally cloned moments are moments'); assert.ok(moment.isMoment(extend({}, moment.utc())), 'externally cloned utc moments are moments'); assert.ok(!moment.isMoment(new MyObj()), 'myObj is not moment object'); assert.ok(!moment.isMoment(moment), 'moment function is not moment object'); assert.ok(!moment.isMoment(new Date()), 'date object is not moment object'); assert.ok(!moment.isMoment(Object), 'Object is not moment object'); assert.ok(!moment.isMoment('foo'), 'string is not moment object'); assert.ok(!moment.isMoment(1), 'number is not moment object'); assert.ok(!moment.isMoment(NaN), 'NaN is not moment object'); assert.ok(!moment.isMoment(null), 'null is not moment object'); assert.ok(!moment.isMoment(undefined), 'undefined is not moment object'); }); test('is moment with hacked hasOwnProperty', function (assert) { var obj = {}; // HACK to suppress jshint warning about bad property name obj['hasOwnMoney'.replace('Money', 'Property')] = function () { return true; }; assert.ok(!moment.isMoment(obj), 'isMoment works even if passed object has a wrong hasOwnProperty implementation (ie8)'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('is same'); test('is same without units', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 10)), mCopy = moment(m); assert.equal(m.isSame(moment(new Date(2012, 3, 2, 3, 5, 5, 10))), false, 'year is later'); assert.equal(m.isSame(moment(new Date(2010, 3, 2, 3, 3, 5, 10))), false, 'year is earlier'); assert.equal(m.isSame(moment(new Date(2011, 4, 2, 3, 4, 5, 10))), false, 'month is later'); assert.equal(m.isSame(moment(new Date(2011, 2, 2, 3, 4, 5, 10))), false, 'month is earlier'); assert.equal(m.isSame(moment(new Date(2011, 3, 3, 3, 4, 5, 10))), false, 'day is later'); assert.equal(m.isSame(moment(new Date(2011, 3, 1, 3, 4, 5, 10))), false, 'day is earlier'); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 4, 4, 5, 10))), false, 'hour is later'); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 2, 4, 5, 10))), false, 'hour is earlier'); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 3, 5, 5, 10))), false, 'minute is later'); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 3, 3, 5, 10))), false, 'minute is earlier'); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 3, 4, 6, 10))), false, 'second is later'); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 3, 4, 4, 11))), false, 'second is earlier'); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 3, 4, 5, 10))), true, 'millisecond match'); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 3, 4, 5, 11))), false, 'millisecond is later'); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 3, 4, 5, 9))), false, 'millisecond is earlier'); assert.equal(m.isSame(m), true, 'moments are the same as themselves'); assert.equal(+m, +mCopy, 'isSame second should not change moment'); }); test('is same year', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isSame(moment(new Date(2011, 5, 6, 7, 8, 9, 10)), 'year'), true, 'year match'); assert.equal(m.isSame(moment(new Date(2011, 5, 6, 7, 8, 9, 10)), 'years'), true, 'plural should work'); assert.equal(m.isSame(moment(new Date(2012, 5, 6, 7, 8, 9, 10)), 'year'), false, 'year mismatch'); assert.equal(m.isSame(moment(new Date(2011, 0, 1, 0, 0, 0, 0)), 'year'), true, 'exact start of year'); assert.equal(m.isSame(moment(new Date(2011, 11, 31, 23, 59, 59, 999)), 'year'), true, 'exact end of year'); assert.equal(m.isSame(moment(new Date(2012, 0, 1, 0, 0, 0, 0)), 'year'), false, 'start of next year'); assert.equal(m.isSame(moment(new Date(2010, 11, 31, 23, 59, 59, 999)), 'year'), false, 'end of previous year'); assert.equal(m.isSame(m, 'year'), true, 'same moments are in the same year'); assert.equal(+m, +mCopy, 'isSame year should not change moment'); }); test('is same month', function (assert) { var m = moment(new Date(2011, 2, 3, 4, 5, 6, 7)), mCopy = moment(m); assert.equal(m.isSame(moment(new Date(2011, 2, 6, 7, 8, 9, 10)), 'month'), true, 'month match'); assert.equal(m.isSame(moment(new Date(2011, 2, 6, 7, 8, 9, 10)), 'months'), true, 'plural should work'); assert.equal(m.isSame(moment(new Date(2012, 2, 6, 7, 8, 9, 10)), 'month'), false, 'year mismatch'); assert.equal(m.isSame(moment(new Date(2011, 5, 6, 7, 8, 9, 10)), 'month'), false, 'month mismatch'); assert.equal(m.isSame(moment(new Date(2011, 2, 1, 0, 0, 0, 0)), 'month'), true, 'exact start of month'); assert.equal(m.isSame(moment(new Date(2011, 2, 31, 23, 59, 59, 999)), 'month'), true, 'exact end of month'); assert.equal(m.isSame(moment(new Date(2011, 3, 1, 0, 0, 0, 0)), 'month'), false, 'start of next month'); assert.equal(m.isSame(moment(new Date(2011, 1, 27, 23, 59, 59, 999)), 'month'), false, 'end of previous month'); assert.equal(m.isSame(m, 'month'), true, 'same moments are in the same month'); assert.equal(+m, +mCopy, 'isSame month should not change moment'); }); test('is same day', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 7, 8, 9, 10)), 'day'), true, 'day match'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 7, 8, 9, 10)), 'days'), true, 'plural should work'); assert.equal(m.isSame(moment(new Date(2012, 1, 2, 7, 8, 9, 10)), 'day'), false, 'year mismatch'); assert.equal(m.isSame(moment(new Date(2011, 2, 2, 7, 8, 9, 10)), 'day'), false, 'month mismatch'); assert.equal(m.isSame(moment(new Date(2011, 1, 3, 7, 8, 9, 10)), 'day'), false, 'day mismatch'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 0, 0, 0, 0)), 'day'), true, 'exact start of day'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 23, 59, 59, 999)), 'day'), true, 'exact end of day'); assert.equal(m.isSame(moment(new Date(2011, 1, 3, 0, 0, 0, 0)), 'day'), false, 'start of next day'); assert.equal(m.isSame(moment(new Date(2011, 1, 1, 23, 59, 59, 999)), 'day'), false, 'end of previous day'); assert.equal(m.isSame(m, 'day'), true, 'same moments are in the same day'); assert.equal(+m, +mCopy, 'isSame day should not change moment'); }); test('is same hour', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 8, 9, 10)), 'hour'), true, 'hour match'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 8, 9, 10)), 'hours'), true, 'plural should work'); assert.equal(m.isSame(moment(new Date(2012, 1, 2, 3, 8, 9, 10)), 'hour'), false, 'year mismatch'); assert.equal(m.isSame(moment(new Date(2011, 2, 2, 3, 8, 9, 10)), 'hour'), false, 'month mismatch'); assert.equal(m.isSame(moment(new Date(2011, 1, 3, 3, 8, 9, 10)), 'hour'), false, 'day mismatch'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 4, 8, 9, 10)), 'hour'), false, 'hour mismatch'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 0, 0, 0)), 'hour'), true, 'exact start of hour'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 59, 59, 999)), 'hour'), true, 'exact end of hour'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 4, 0, 0, 0)), 'hour'), false, 'start of next hour'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 2, 59, 59, 999)), 'hour'), false, 'end of previous hour'); assert.equal(m.isSame(m, 'hour'), true, 'same moments are in the same hour'); assert.equal(+m, +mCopy, 'isSame hour should not change moment'); }); test('is same minute', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 4, 9, 10)), 'minute'), true, 'minute match'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 4, 9, 10)), 'minutes'), true, 'plural should work'); assert.equal(m.isSame(moment(new Date(2012, 1, 2, 3, 4, 9, 10)), 'minute'), false, 'year mismatch'); assert.equal(m.isSame(moment(new Date(2011, 2, 2, 3, 4, 9, 10)), 'minute'), false, 'month mismatch'); assert.equal(m.isSame(moment(new Date(2011, 1, 3, 3, 4, 9, 10)), 'minute'), false, 'day mismatch'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 4, 4, 9, 10)), 'minute'), false, 'hour mismatch'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 5, 9, 10)), 'minute'), false, 'minute mismatch'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 4, 0, 0)), 'minute'), true, 'exact start of minute'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 4, 59, 999)), 'minute'), true, 'exact end of minute'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 5, 0, 0)), 'minute'), false, 'start of next minute'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 3, 59, 999)), 'minute'), false, 'end of previous minute'); assert.equal(m.isSame(m, 'minute'), true, 'same moments are in the same minute'); assert.equal(+m, +mCopy, 'isSame minute should not change moment'); }); test('is same second', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 4, 5, 10)), 'second'), true, 'second match'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 4, 5, 10)), 'seconds'), true, 'plural should work'); assert.equal(m.isSame(moment(new Date(2012, 1, 2, 3, 4, 5, 10)), 'second'), false, 'year mismatch'); assert.equal(m.isSame(moment(new Date(2011, 2, 2, 3, 4, 5, 10)), 'second'), false, 'month mismatch'); assert.equal(m.isSame(moment(new Date(2011, 1, 3, 3, 4, 5, 10)), 'second'), false, 'day mismatch'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 4, 4, 5, 10)), 'second'), false, 'hour mismatch'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 5, 5, 10)), 'second'), false, 'minute mismatch'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 4, 6, 10)), 'second'), false, 'second mismatch'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 4, 5, 0)), 'second'), true, 'exact start of second'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 4, 5, 999)), 'second'), true, 'exact end of second'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 4, 6, 0)), 'second'), false, 'start of next second'); assert.equal(m.isSame(moment(new Date(2011, 1, 2, 3, 4, 4, 999)), 'second'), false, 'end of previous second'); assert.equal(m.isSame(m, 'second'), true, 'same moments are in the same second'); assert.equal(+m, +mCopy, 'isSame second should not change moment'); }); test('is same millisecond', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 10)), mCopy = moment(m); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'millisecond'), true, 'millisecond match'); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'milliseconds'), true, 'plural should work'); assert.equal(m.isSame(moment(new Date(2012, 3, 2, 3, 4, 5, 10)), 'millisecond'), false, 'year is later'); assert.equal(m.isSame(moment(new Date(2010, 3, 2, 3, 4, 5, 10)), 'millisecond'), false, 'year is earlier'); assert.equal(m.isSame(moment(new Date(2011, 4, 2, 3, 4, 5, 10)), 'millisecond'), false, 'month is later'); assert.equal(m.isSame(moment(new Date(2011, 2, 2, 3, 4, 5, 10)), 'millisecond'), false, 'month is earlier'); assert.equal(m.isSame(moment(new Date(2011, 3, 3, 3, 4, 5, 10)), 'millisecond'), false, 'day is later'); assert.equal(m.isSame(moment(new Date(2011, 3, 1, 1, 4, 5, 10)), 'millisecond'), false, 'day is earlier'); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 4, 4, 5, 10)), 'millisecond'), false, 'hour is later'); assert.equal(m.isSame(moment(new Date(2011, 3, 1, 4, 1, 5, 10)), 'millisecond'), false, 'hour is earlier'); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 3, 5, 5, 10)), 'millisecond'), false, 'minute is later'); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 3, 3, 5, 10)), 'millisecond'), false, 'minute is earlier'); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 3, 4, 6, 10)), 'millisecond'), false, 'second is later'); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 3, 4, 4, 5)), 'millisecond'), false, 'second is earlier'); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 3, 4, 6, 11)), 'millisecond'), false, 'millisecond is later'); assert.equal(m.isSame(moment(new Date(2011, 3, 2, 3, 4, 4, 9)), 'millisecond'), false, 'millisecond is earlier'); assert.equal(m.isSame(m, 'millisecond'), true, 'same moments are in the same millisecond'); assert.equal(+m, +mCopy, 'isSame millisecond should not change moment'); }); test('is same with utc offset moments', function (assert) { assert.ok(moment.parseZone('2013-02-01T-05:00').isSame(moment('2013-02-01'), 'year'), 'zoned vs local moment'); assert.ok(moment('2013-02-01').isSame(moment('2013-02-01').utcOffset('-05:00'), 'year'), 'local vs zoned moment'); assert.ok(moment.parseZone('2013-02-01T-05:00').isSame(moment.parseZone('2013-02-01T-06:30'), 'year'), 'zoned vs (differently) zoned moment'); }); test('is same with invalid moments', function (assert) { assert.equal(moment.invalid().isSame(moment.invalid()), false, 'invalid moments are not considered equal'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('is same or after'); test('is same or after without units', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 10)), mCopy = moment(m); assert.equal(m.isSameOrAfter(moment(new Date(2012, 3, 2, 3, 5, 5, 10))), false, 'year is later'); assert.equal(m.isSameOrAfter(moment(new Date(2010, 3, 2, 3, 3, 5, 10))), true, 'year is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 4, 2, 3, 4, 5, 10))), false, 'month is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 2, 2, 3, 4, 5, 10))), true, 'month is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 3, 3, 4, 5, 10))), false, 'day is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 1, 3, 4, 5, 10))), true, 'day is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 4, 4, 5, 10))), false, 'hour is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 2, 4, 5, 10))), true, 'hour is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 3, 5, 5, 10))), false, 'minute is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 3, 3, 5, 10))), true, 'minute is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 3, 4, 6, 10))), false, 'second is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 3, 4, 4, 11))), true, 'second is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 3, 4, 5, 10))), true, 'millisecond match'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 3, 4, 5, 11))), false, 'millisecond is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 3, 4, 5, 9))), true, 'millisecond is earlier'); assert.equal(m.isSameOrAfter(m), true, 'moments are the same as themselves'); assert.equal(+m, +mCopy, 'isSameOrAfter second should not change moment'); }); test('is same or after year', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isSameOrAfter(moment(new Date(2011, 5, 6, 7, 8, 9, 10)), 'year'), true, 'year match'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 5, 6, 7, 8, 9, 10)), 'years'), true, 'plural should work'); assert.equal(m.isSameOrAfter(moment(new Date(2012, 5, 6, 7, 8, 9, 10)), 'year'), false, 'year is later'); assert.equal(m.isSameOrAfter(moment(new Date(2010, 5, 6, 7, 8, 9, 10)), 'year'), true, 'year is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 0, 1, 0, 0, 0, 0)), 'year'), true, 'exact start of year'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 11, 31, 23, 59, 59, 999)), 'year'), true, 'exact end of year'); assert.equal(m.isSameOrAfter(moment(new Date(2012, 0, 1, 0, 0, 0, 0)), 'year'), false, 'start of next year'); assert.equal(m.isSameOrAfter(moment(new Date(2010, 11, 31, 23, 59, 59, 999)), 'year'), true, 'end of previous year'); assert.equal(m.isSameOrAfter(m, 'year'), true, 'same moments are in the same year'); assert.equal(+m, +mCopy, 'isSameOrAfter year should not change moment'); }); test('is same or after month', function (assert) { var m = moment(new Date(2011, 2, 3, 4, 5, 6, 7)), mCopy = moment(m); assert.equal(m.isSameOrAfter(moment(new Date(2011, 2, 6, 7, 8, 9, 10)), 'month'), true, 'month match'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 2, 6, 7, 8, 9, 10)), 'months'), true, 'plural should work'); assert.equal(m.isSameOrAfter(moment(new Date(2012, 2, 6, 7, 8, 9, 10)), 'month'), false, 'year is later'); assert.equal(m.isSameOrAfter(moment(new Date(2010, 2, 6, 7, 8, 9, 10)), 'month'), true, 'year is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 5, 6, 7, 8, 9, 10)), 'month'), false, 'month is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 6, 7, 8, 9, 10)), 'month'), true, 'month is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 2, 1, 0, 0, 0, 0)), 'month'), true, 'exact start of month'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 2, 31, 23, 59, 59, 999)), 'month'), true, 'exact end of month'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 1, 0, 0, 0, 0)), 'month'), false, 'start of next month'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 27, 23, 59, 59, 999)), 'month'), true, 'end of previous month'); assert.equal(m.isSameOrAfter(m, 'month'), true, 'same moments are in the same month'); assert.equal(+m, +mCopy, 'isSameOrAfter month should not change moment'); }); test('is same or after day', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 7, 8, 9, 10)), 'day'), true, 'day match'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 7, 8, 9, 10)), 'days'), true, 'plural should work'); assert.equal(m.isSameOrAfter(moment(new Date(2012, 1, 2, 7, 8, 9, 10)), 'day'), false, 'year is later'); assert.equal(m.isSameOrAfter(moment(new Date(2010, 1, 2, 7, 8, 9, 10)), 'day'), true, 'year is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 2, 2, 7, 8, 9, 10)), 'day'), false, 'month is later'); assert.equal(m.isSameOrAfter(moment(new Date(2010, 12, 2, 7, 8, 9, 10)), 'day'), true, 'month is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 3, 7, 8, 9, 10)), 'day'), false, 'day is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 1, 7, 8, 9, 10)), 'day'), true, 'day is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 0, 0, 0, 0)), 'day'), true, 'exact start of day'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 23, 59, 59, 999)), 'day'), true, 'exact end of day'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 3, 0, 0, 0, 0)), 'day'), false, 'start of next day'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 1, 23, 59, 59, 999)), 'day'), true, 'end of previous day'); assert.equal(m.isSameOrAfter(m, 'day'), true, 'same moments are in the same day'); assert.equal(+m, +mCopy, 'isSameOrAfter day should not change moment'); }); test('is same or after hour', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 8, 9, 10)), 'hour'), true, 'hour match'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 8, 9, 10)), 'hours'), true, 'plural should work'); assert.equal(m.isSameOrAfter(moment(new Date(2012, 1, 2, 3, 8, 9, 10)), 'hour'), false, 'year is later'); assert.equal(m.isSameOrAfter(moment(new Date(2010, 1, 2, 3, 8, 9, 10)), 'hour'), true, 'year is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 2, 2, 3, 8, 9, 10)), 'hour'), false, 'month is later'); assert.equal(m.isSameOrAfter(moment(new Date(2010, 12, 2, 3, 8, 9, 10)), 'hour'), true, 'month is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 3, 3, 8, 9, 10)), 'hour'), false, 'day is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 1, 3, 8, 9, 10)), 'hour'), true, 'day is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 4, 8, 9, 10)), 'hour'), false, 'hour is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 2, 8, 9, 10)), 'hour'), true, 'hour is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 0, 0, 0)), 'hour'), true, 'exact start of hour'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 59, 59, 999)), 'hour'), true, 'exact end of hour'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 4, 0, 0, 0)), 'hour'), false, 'start of next hour'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 2, 59, 59, 999)), 'hour'), true, 'end of previous hour'); assert.equal(m.isSameOrAfter(m, 'hour'), true, 'same moments are in the same hour'); assert.equal(+m, +mCopy, 'isSameOrAfter hour should not change moment'); }); test('is same or after minute', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 4, 9, 10)), 'minute'), true, 'minute match'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 4, 9, 10)), 'minutes'), true, 'plural should work'); assert.equal(m.isSameOrAfter(moment(new Date(2012, 1, 2, 3, 4, 9, 10)), 'minute'), false, 'year is later'); assert.equal(m.isSameOrAfter(moment(new Date(2010, 1, 2, 3, 4, 9, 10)), 'minute'), true, 'year is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 2, 2, 3, 4, 9, 10)), 'minute'), false, 'month is later'); assert.equal(m.isSameOrAfter(moment(new Date(2010, 12, 2, 3, 4, 9, 10)), 'minute'), true, 'month is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 3, 3, 4, 9, 10)), 'minute'), false, 'day is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 1, 3, 4, 9, 10)), 'minute'), true, 'day is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 4, 4, 9, 10)), 'minute'), false, 'hour is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 2, 4, 9, 10)), 'minute'), true, 'hour is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 5, 9, 10)), 'minute'), false, 'minute is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 3, 9, 10)), 'minute'), true, 'minute is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 4, 0, 0)), 'minute'), true, 'exact start of minute'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 4, 59, 999)), 'minute'), true, 'exact end of minute'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 5, 0, 0)), 'minute'), false, 'start of next minute'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 3, 59, 999)), 'minute'), true, 'end of previous minute'); assert.equal(m.isSameOrAfter(m, 'minute'), true, 'same moments are in the same minute'); assert.equal(+m, +mCopy, 'isSameOrAfter minute should not change moment'); }); test('is same or after second', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 4, 5, 10)), 'second'), true, 'second match'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 4, 5, 10)), 'seconds'), true, 'plural should work'); assert.equal(m.isSameOrAfter(moment(new Date(2012, 1, 2, 3, 4, 5, 10)), 'second'), false, 'year is later'); assert.equal(m.isSameOrAfter(moment(new Date(2010, 1, 2, 3, 4, 5, 10)), 'second'), true, 'year is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 2, 2, 3, 4, 5, 10)), 'second'), false, 'month is later'); assert.equal(m.isSameOrAfter(moment(new Date(2010, 12, 2, 3, 4, 5, 10)), 'second'), true, 'month is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 3, 3, 4, 5, 10)), 'second'), false, 'day is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 1, 3, 4, 5, 10)), 'second'), true, 'day is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 4, 4, 5, 10)), 'second'), false, 'hour is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 2, 4, 5, 10)), 'second'), true, 'hour is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 5, 5, 10)), 'second'), false, 'minute is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 3, 5, 10)), 'second'), true, 'minute is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 4, 6, 10)), 'second'), false, 'second is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 4, 4, 10)), 'second'), true, 'second is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 4, 5, 0)), 'second'), true, 'exact start of second'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 4, 5, 999)), 'second'), true, 'exact end of second'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 4, 6, 0)), 'second'), false, 'start of next second'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 1, 2, 3, 4, 4, 999)), 'second'), true, 'end of previous second'); assert.equal(m.isSameOrAfter(m, 'second'), true, 'same moments are in the same second'); assert.equal(+m, +mCopy, 'isSameOrAfter second should not change moment'); }); test('is same or after millisecond', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 10)), mCopy = moment(m); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'millisecond'), true, 'millisecond match'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'milliseconds'), true, 'plural should work'); assert.equal(m.isSameOrAfter(moment(new Date(2012, 3, 2, 3, 4, 5, 10)), 'millisecond'), false, 'year is later'); assert.equal(m.isSameOrAfter(moment(new Date(2010, 3, 2, 3, 4, 5, 10)), 'millisecond'), true, 'year is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 4, 2, 3, 4, 5, 10)), 'millisecond'), false, 'month is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 2, 2, 3, 4, 5, 10)), 'millisecond'), true, 'month is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 3, 3, 4, 5, 10)), 'millisecond'), false, 'day is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 1, 1, 4, 5, 10)), 'millisecond'), true, 'day is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 4, 4, 5, 10)), 'millisecond'), false, 'hour is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 1, 4, 1, 5, 10)), 'millisecond'), true, 'hour is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 3, 5, 5, 10)), 'millisecond'), false, 'minute is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 3, 3, 5, 10)), 'millisecond'), true, 'minute is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 3, 4, 6, 10)), 'millisecond'), false, 'second is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 3, 4, 4, 5)), 'millisecond'), true, 'second is earlier'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 3, 4, 6, 11)), 'millisecond'), false, 'millisecond is later'); assert.equal(m.isSameOrAfter(moment(new Date(2011, 3, 2, 3, 4, 4, 9)), 'millisecond'), true, 'millisecond is earlier'); assert.equal(m.isSameOrAfter(m, 'millisecond'), true, 'same moments are in the same millisecond'); assert.equal(+m, +mCopy, 'isSameOrAfter millisecond should not change moment'); }); test('is same or after with utc offset moments', function (assert) { assert.ok(moment.parseZone('2013-02-01T-05:00').isSameOrAfter(moment('2013-02-01'), 'year'), 'zoned vs local moment'); assert.ok(moment('2013-02-01').isSameOrAfter(moment('2013-02-01').utcOffset('-05:00'), 'year'), 'local vs zoned moment'); assert.ok(moment.parseZone('2013-02-01T-05:00').isSameOrAfter(moment.parseZone('2013-02-01T-06:30'), 'year'), 'zoned vs (differently) zoned moment'); }); test('is same or after with invalid moments', function (assert) { var m = moment(), invalid = moment.invalid(); assert.equal(invalid.isSameOrAfter(invalid), false, 'invalid moments are not considered equal'); assert.equal(m.isSameOrAfter(invalid), false, 'valid moment is not after invalid moment'); assert.equal(invalid.isSameOrAfter(m), false, 'invalid moment is not after valid moment'); assert.equal(m.isSameOrAfter(invalid, 'year'), false, 'invalid moment year'); assert.equal(m.isSameOrAfter(invalid, 'month'), false, 'invalid moment month'); assert.equal(m.isSameOrAfter(invalid, 'day'), false, 'invalid moment day'); assert.equal(m.isSameOrAfter(invalid, 'hour'), false, 'invalid moment hour'); assert.equal(m.isSameOrAfter(invalid, 'minute'), false, 'invalid moment minute'); assert.equal(m.isSameOrAfter(invalid, 'second'), false, 'invalid moment second'); assert.equal(m.isSameOrAfter(invalid, 'milliseconds'), false, 'invalid moment milliseconds'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('is same or before'); test('is same or before without units', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 10)), mCopy = moment(m); assert.equal(m.isSameOrBefore(moment(new Date(2012, 3, 2, 3, 5, 5, 10))), true, 'year is later'); assert.equal(m.isSameOrBefore(moment(new Date(2010, 3, 2, 3, 3, 5, 10))), false, 'year is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 4, 2, 3, 4, 5, 10))), true, 'month is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 2, 2, 3, 4, 5, 10))), false, 'month is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 3, 3, 4, 5, 10))), true, 'day is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 1, 3, 4, 5, 10))), false, 'day is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 4, 4, 5, 10))), true, 'hour is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 2, 4, 5, 10))), false, 'hour is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 3, 5, 5, 10))), true, 'minute is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 3, 3, 5, 10))), false, 'minute is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 3, 4, 6, 10))), true, 'second is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 3, 4, 4, 11))), false, 'second is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 3, 4, 5, 10))), true, 'millisecond match'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 3, 4, 5, 11))), true, 'millisecond is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 3, 4, 5, 9))), false, 'millisecond is earlier'); assert.equal(m.isSameOrBefore(m), true, 'moments are the same as themselves'); assert.equal(+m, +mCopy, 'isSameOrBefore second should not change moment'); }); test('is same or before year', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isSameOrBefore(moment(new Date(2011, 5, 6, 7, 8, 9, 10)), 'year'), true, 'year match'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 5, 6, 7, 8, 9, 10)), 'years'), true, 'plural should work'); assert.equal(m.isSameOrBefore(moment(new Date(2012, 5, 6, 7, 8, 9, 10)), 'year'), true, 'year is later'); assert.equal(m.isSameOrBefore(moment(new Date(2010, 5, 6, 7, 8, 9, 10)), 'year'), false, 'year is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 0, 1, 0, 0, 0, 0)), 'year'), true, 'exact start of year'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 11, 31, 23, 59, 59, 999)), 'year'), true, 'exact end of year'); assert.equal(m.isSameOrBefore(moment(new Date(2012, 0, 1, 0, 0, 0, 0)), 'year'), true, 'start of next year'); assert.equal(m.isSameOrBefore(moment(new Date(2010, 11, 31, 23, 59, 59, 999)), 'year'), false, 'end of previous year'); assert.equal(m.isSameOrBefore(m, 'year'), true, 'same moments are in the same year'); assert.equal(+m, +mCopy, 'isSameOrBefore year should not change moment'); }); test('is same or before month', function (assert) { var m = moment(new Date(2011, 2, 3, 4, 5, 6, 7)), mCopy = moment(m); assert.equal(m.isSameOrBefore(moment(new Date(2011, 2, 6, 7, 8, 9, 10)), 'month'), true, 'month match'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 2, 6, 7, 8, 9, 10)), 'months'), true, 'plural should work'); assert.equal(m.isSameOrBefore(moment(new Date(2012, 2, 6, 7, 8, 9, 10)), 'month'), true, 'year is later'); assert.equal(m.isSameOrBefore(moment(new Date(2010, 2, 6, 7, 8, 9, 10)), 'month'), false, 'year is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 5, 6, 7, 8, 9, 10)), 'month'), true, 'month is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 6, 7, 8, 9, 10)), 'month'), false, 'month is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 2, 1, 0, 0, 0, 0)), 'month'), true, 'exact start of month'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 2, 31, 23, 59, 59, 999)), 'month'), true, 'exact end of month'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 1, 0, 0, 0, 0)), 'month'), true, 'start of next month'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 27, 23, 59, 59, 999)), 'month'), false, 'end of previous month'); assert.equal(m.isSameOrBefore(m, 'month'), true, 'same moments are in the same month'); assert.equal(+m, +mCopy, 'isSameOrBefore month should not change moment'); }); test('is same or before day', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 7, 8, 9, 10)), 'day'), true, 'day match'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 7, 8, 9, 10)), 'days'), true, 'plural should work'); assert.equal(m.isSameOrBefore(moment(new Date(2012, 1, 2, 7, 8, 9, 10)), 'day'), true, 'year is later'); assert.equal(m.isSameOrBefore(moment(new Date(2010, 1, 2, 7, 8, 9, 10)), 'day'), false, 'year is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 2, 2, 7, 8, 9, 10)), 'day'), true, 'month is later'); assert.equal(m.isSameOrBefore(moment(new Date(2010, 12, 2, 7, 8, 9, 10)), 'day'), false, 'month is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 3, 7, 8, 9, 10)), 'day'), true, 'day is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 1, 7, 8, 9, 10)), 'day'), false, 'day is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 0, 0, 0, 0)), 'day'), true, 'exact start of day'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 23, 59, 59, 999)), 'day'), true, 'exact end of day'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 3, 0, 0, 0, 0)), 'day'), true, 'start of next day'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 1, 23, 59, 59, 999)), 'day'), false, 'end of previous day'); assert.equal(m.isSameOrBefore(m, 'day'), true, 'same moments are in the same day'); assert.equal(+m, +mCopy, 'isSameOrBefore day should not change moment'); }); test('is same or before hour', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 8, 9, 10)), 'hour'), true, 'hour match'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 8, 9, 10)), 'hours'), true, 'plural should work'); assert.equal(m.isSameOrBefore(moment(new Date(2012, 1, 2, 3, 8, 9, 10)), 'hour'), true, 'year is later'); assert.equal(m.isSameOrBefore(moment(new Date(2010, 1, 2, 3, 8, 9, 10)), 'hour'), false, 'year is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 2, 2, 3, 8, 9, 10)), 'hour'), true, 'month is later'); assert.equal(m.isSameOrBefore(moment(new Date(2010, 12, 2, 3, 8, 9, 10)), 'hour'), false, 'month is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 3, 3, 8, 9, 10)), 'hour'), true, 'day is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 1, 3, 8, 9, 10)), 'hour'), false, 'day is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 4, 8, 9, 10)), 'hour'), true, 'hour is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 2, 8, 9, 10)), 'hour'), false, 'hour is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 0, 0, 0)), 'hour'), true, 'exact start of hour'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 59, 59, 999)), 'hour'), true, 'exact end of hour'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 4, 0, 0, 0)), 'hour'), true, 'start of next hour'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 2, 59, 59, 999)), 'hour'), false, 'end of previous hour'); assert.equal(m.isSameOrBefore(m, 'hour'), true, 'same moments are in the same hour'); assert.equal(+m, +mCopy, 'isSameOrBefore hour should not change moment'); }); test('is same or before minute', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 4, 9, 10)), 'minute'), true, 'minute match'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 4, 9, 10)), 'minutes'), true, 'plural should work'); assert.equal(m.isSameOrBefore(moment(new Date(2012, 1, 2, 3, 4, 9, 10)), 'minute'), true, 'year is later'); assert.equal(m.isSameOrBefore(moment(new Date(2010, 1, 2, 3, 4, 9, 10)), 'minute'), false, 'year is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 2, 2, 3, 4, 9, 10)), 'minute'), true, 'month is later'); assert.equal(m.isSameOrBefore(moment(new Date(2010, 12, 2, 3, 4, 9, 10)), 'minute'), false, 'month is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 3, 3, 4, 9, 10)), 'minute'), true, 'day is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 1, 3, 4, 9, 10)), 'minute'), false, 'day is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 4, 4, 9, 10)), 'minute'), true, 'hour is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 2, 4, 9, 10)), 'minute'), false, 'hour is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 5, 9, 10)), 'minute'), true, 'minute is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 3, 9, 10)), 'minute'), false, 'minute is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 4, 0, 0)), 'minute'), true, 'exact start of minute'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 4, 59, 999)), 'minute'), true, 'exact end of minute'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 5, 0, 0)), 'minute'), true, 'start of next minute'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 3, 59, 999)), 'minute'), false, 'end of previous minute'); assert.equal(m.isSameOrBefore(m, 'minute'), true, 'same moments are in the same minute'); assert.equal(+m, +mCopy, 'isSameOrBefore minute should not change moment'); }); test('is same or before second', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)), mCopy = moment(m); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 4, 5, 10)), 'second'), true, 'second match'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 4, 5, 10)), 'seconds'), true, 'plural should work'); assert.equal(m.isSameOrBefore(moment(new Date(2012, 1, 2, 3, 4, 5, 10)), 'second'), true, 'year is later'); assert.equal(m.isSameOrBefore(moment(new Date(2010, 1, 2, 3, 4, 5, 10)), 'second'), false, 'year is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 2, 2, 3, 4, 5, 10)), 'second'), true, 'month is later'); assert.equal(m.isSameOrBefore(moment(new Date(2010, 12, 2, 3, 4, 5, 10)), 'second'), false, 'month is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 3, 3, 4, 5, 10)), 'second'), true, 'day is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 1, 3, 4, 5, 10)), 'second'), false, 'day is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 4, 4, 5, 10)), 'second'), true, 'hour is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 2, 4, 5, 10)), 'second'), false, 'hour is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 5, 5, 10)), 'second'), true, 'minute is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 3, 5, 10)), 'second'), false, 'minute is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 4, 6, 10)), 'second'), true, 'second is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 4, 4, 10)), 'second'), false, 'second is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 4, 5, 0)), 'second'), true, 'exact start of second'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 4, 5, 999)), 'second'), true, 'exact end of second'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 4, 6, 0)), 'second'), true, 'start of next second'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 1, 2, 3, 4, 4, 999)), 'second'), false, 'end of previous second'); assert.equal(m.isSameOrBefore(m, 'second'), true, 'same moments are in the same second'); assert.equal(+m, +mCopy, 'isSameOrBefore second should not change moment'); }); test('is same or before millisecond', function (assert) { var m = moment(new Date(2011, 3, 2, 3, 4, 5, 10)), mCopy = moment(m); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'millisecond'), true, 'millisecond match'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 3, 4, 5, 10)), 'milliseconds'), true, 'plural should work'); assert.equal(m.isSameOrBefore(moment(new Date(2012, 3, 2, 3, 4, 5, 10)), 'millisecond'), true, 'year is later'); assert.equal(m.isSameOrBefore(moment(new Date(2010, 3, 2, 3, 4, 5, 10)), 'millisecond'), false, 'year is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 4, 2, 3, 4, 5, 10)), 'millisecond'), true, 'month is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 2, 2, 3, 4, 5, 10)), 'millisecond'), false, 'month is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 3, 3, 4, 5, 10)), 'millisecond'), true, 'day is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 1, 1, 4, 5, 10)), 'millisecond'), false, 'day is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 4, 4, 5, 10)), 'millisecond'), true, 'hour is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 1, 4, 1, 5, 10)), 'millisecond'), false, 'hour is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 3, 5, 5, 10)), 'millisecond'), true, 'minute is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 3, 3, 5, 10)), 'millisecond'), false, 'minute is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 3, 4, 6, 10)), 'millisecond'), true, 'second is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 3, 4, 4, 5)), 'millisecond'), false, 'second is earlier'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 3, 4, 6, 11)), 'millisecond'), true, 'millisecond is later'); assert.equal(m.isSameOrBefore(moment(new Date(2011, 3, 2, 3, 4, 4, 9)), 'millisecond'), false, 'millisecond is earlier'); assert.equal(m.isSameOrBefore(m, 'millisecond'), true, 'same moments are in the same millisecond'); assert.equal(+m, +mCopy, 'isSameOrBefore millisecond should not change moment'); }); test('is same with utc offset moments', function (assert) { assert.ok(moment.parseZone('2013-02-01T-05:00').isSameOrBefore(moment('2013-02-01'), 'year'), 'zoned vs local moment'); assert.ok(moment('2013-02-01').isSameOrBefore(moment('2013-02-01').utcOffset('-05:00'), 'year'), 'local vs zoned moment'); assert.ok(moment.parseZone('2013-02-01T-05:00').isSameOrBefore(moment.parseZone('2013-02-01T-06:30'), 'year'), 'zoned vs (differently) zoned moment'); }); test('is same with invalid moments', function (assert) { var m = moment(), invalid = moment.invalid(); assert.equal(invalid.isSameOrBefore(invalid), false, 'invalid moments are not considered equal'); assert.equal(m.isSameOrBefore(invalid), false, 'valid moment is not before invalid moment'); assert.equal(invalid.isSameOrBefore(m), false, 'invalid moment is not before valid moment'); assert.equal(m.isSameOrBefore(invalid, 'year'), false, 'invalid moment year'); assert.equal(m.isSameOrBefore(invalid, 'month'), false, 'invalid moment month'); assert.equal(m.isSameOrBefore(invalid, 'day'), false, 'invalid moment day'); assert.equal(m.isSameOrBefore(invalid, 'hour'), false, 'invalid moment hour'); assert.equal(m.isSameOrBefore(invalid, 'minute'), false, 'invalid moment minute'); assert.equal(m.isSameOrBefore(invalid, 'second'), false, 'invalid moment second'); assert.equal(m.isSameOrBefore(invalid, 'milliseconds'), false, 'invalid moment milliseconds'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('is valid'); test('array bad month', function (assert) { assert.equal(moment([2010, -1]).isValid(), false, 'month -1 invalid'); assert.equal(moment([2100, 12]).isValid(), false, 'month 12 invalid'); }); test('array good month', function (assert) { for (var i = 0; i < 12; i++) { assert.equal(moment([2010, i]).isValid(), true, 'month ' + i); assert.equal(moment.utc([2010, i]).isValid(), true, 'month ' + i); } }); test('array bad date', function (assert) { var tests = [ moment([2010, 0, 0]), moment([2100, 0, 32]), moment.utc([2010, 0, 0]), moment.utc([2100, 0, 32]) ], i, m; for (i in tests) { m = tests[i]; assert.equal(m.isValid(), false); } }); test('h/hh with hour > 12', function (assert) { assert.ok(moment('06/20/2014 11:51 PM', 'MM/DD/YYYY hh:mm A', true).isValid(), '11 for hh'); assert.ok(moment('06/20/2014 11:51 AM', 'MM/DD/YYYY hh:mm A', true).isValid(), '11 for hh'); assert.ok(moment('06/20/2014 23:51 PM', 'MM/DD/YYYY hh:mm A').isValid(), 'non-strict validity 23 for hh'); assert.ok(moment('06/20/2014 23:51 PM', 'MM/DD/YYYY hh:mm A').parsingFlags().bigHour, 'non-strict bigHour 23 for hh'); assert.ok(!moment('06/20/2014 23:51 PM', 'MM/DD/YYYY hh:mm A', true).isValid(), 'validity 23 for hh'); assert.ok(moment('06/20/2014 23:51 PM', 'MM/DD/YYYY hh:mm A', true).parsingFlags().bigHour, 'bigHour 23 for hh'); }); test('array bad date leap year', function (assert) { assert.equal(moment([2010, 1, 29]).isValid(), false, '2010 feb 29'); assert.equal(moment([2100, 1, 29]).isValid(), false, '2100 feb 29'); assert.equal(moment([2008, 1, 30]).isValid(), false, '2008 feb 30'); assert.equal(moment([2000, 1, 30]).isValid(), false, '2000 feb 30'); assert.equal(moment.utc([2010, 1, 29]).isValid(), false, 'utc 2010 feb 29'); assert.equal(moment.utc([2100, 1, 29]).isValid(), false, 'utc 2100 feb 29'); assert.equal(moment.utc([2008, 1, 30]).isValid(), false, 'utc 2008 feb 30'); assert.equal(moment.utc([2000, 1, 30]).isValid(), false, 'utc 2000 feb 30'); }); test('string + formats bad date', function (assert) { assert.equal(moment('2020-00-00', []).isValid(), false, 'invalid on empty array'); assert.equal(moment('2020-00-00', ['YYYY-MM-DD', 'DD-MM-YYYY']).isValid(), false, 'invalid on all in array'); assert.equal(moment('2020-00-00', ['DD-MM-YYYY', 'YYYY-MM-DD']).isValid(), false, 'invalid on all in array'); assert.equal(moment('2020-01-01', ['YYYY-MM-DD', 'DD-MM-YYYY']).isValid(), true, 'valid on first'); assert.equal(moment('2020-01-01', ['DD-MM-YYYY', 'YYYY-MM-DD']).isValid(), true, 'valid on last'); assert.equal(moment('2020-01-01', ['YYYY-MM-DD', 'YYYY-DD-MM']).isValid(), true, 'valid on both'); assert.equal(moment('2020-13-01', ['YYYY-MM-DD', 'YYYY-DD-MM']).isValid(), true, 'valid on last'); assert.equal(moment('12-13-2012', ['DD-MM-YYYY', 'YYYY-MM-DD']).isValid(), false, 'month rollover'); assert.equal(moment('12-13-2012', ['DD-MM-YYYY', 'DD-MM-YYYY']).isValid(), false, 'month rollover'); assert.equal(moment('38-12-2012', ['DD-MM-YYYY']).isValid(), false, 'day rollover'); }); test('string nonsensical with format', function (assert) { assert.equal(moment('fail', 'MM-DD-YYYY').isValid(), false, 'string \'fail\' with format \'MM-DD-YYYY\''); assert.equal(moment('xx-xx-2001', 'DD-MM-YYY').isValid(), true, 'string \'xx-xx-2001\' with format \'MM-DD-YYYY\''); }); test('string with bad month name', function (assert) { assert.equal(moment('01-Nam-2012', 'DD-MMM-YYYY').isValid(), false, '\'Nam\' is an invalid month'); assert.equal(moment('01-Aug-2012', 'DD-MMM-YYYY').isValid(), true, '\'Aug\' is a valid month'); }); test('string with spaceless format', function (assert) { assert.equal(moment('10Sep2001', 'DDMMMYYYY').isValid(), true, 'Parsing 10Sep2001 should result in a valid date'); }); test('invalid string iso 8601', function (assert) { var tests = [ '2010-00-00', '2010-01-00', '2010-01-40', '2010-01-01T24:01', // 24:00:00 is actually valid '2010-01-01T23:60', '2010-01-01T23:59:60' ], i; for (i = 0; i < tests.length; i++) { assert.equal(moment(tests[i], moment.ISO_8601).isValid(), false, tests[i] + ' should be invalid'); assert.equal(moment.utc(tests[i], moment.ISO_8601).isValid(), false, tests[i] + ' should be invalid'); } }); test('invalid string iso 8601 + timezone', function (assert) { var tests = [ '2010-00-00T+00:00', '2010-01-00T+00:00', '2010-01-40T+00:00', '2010-01-40T24:01+00:00', '2010-01-40T23:60+00:00', '2010-01-40T23:59:60+00:00', '2010-01-40T23:59:59.9999+00:00', '2010-01-40T23:59:59,9999+00:00' ], i; for (i = 0; i < tests.length; i++) { assert.equal(moment(tests[i], moment.ISO_8601).isValid(), false, tests[i] + ' should be invalid'); assert.equal(moment.utc(tests[i], moment.ISO_8601).isValid(), false, tests[i] + ' should be invalid'); } }); test('valid string iso 8601 - not strict', function (assert) { var tests = [ '2010-01-30 00:00:00,000Z', '20100101', '20100130', '20100130T23+00:00', '20100130T2359+0000', '20100130T235959+0000', '20100130T235959,999+0000', '20100130T235959,999-0700', '20100130T000000,000+0700', '20100130 000000,000Z' ]; for (var i = 0; i < tests.length; i++) { assert.equal(moment(tests[i]).isValid(), true, tests[i] + ' should be valid in normal'); assert.equal(moment.utc(tests[i]).isValid(), true, tests[i] + ' should be valid in normal'); } }); test('valid string iso 8601 + timezone', function (assert) { var tests = [ '2010-01-01', '2010-01-30', '2010-01-30T23+00:00', '2010-01-30T23:59+00:00', '2010-01-30T23:59:59+00:00', '2010-01-30T23:59:59.999+00:00', '2010-01-30T23:59:59.999-07:00', '2010-01-30T00:00:00.000+07:00', '2010-01-30T23:59:59.999-07', '2010-01-30T00:00:00.000+07', '2010-01-30 00:00:00.000Z' ], i; for (i = 0; i < tests.length; i++) { assert.equal(moment(tests[i]).isValid(), true, tests[i] + ' should be valid in normal'); assert.equal(moment.utc(tests[i]).isValid(), true, tests[i] + ' should be valid in normal'); assert.equal(moment(tests[i], moment.ISO_8601, true).isValid(), true, tests[i] + ' should be valid in strict'); assert.equal(moment.utc(tests[i], moment.ISO_8601, true).isValid(), true, tests[i] + ' should be valid in strict'); } }); test('invalidAt', function (assert) { assert.equal(moment([2000, 12]).invalidAt(), 1, 'month 12 is invalid: 0-11'); assert.equal(moment([2000, 1, 30]).invalidAt(), 2, '30 is not a valid february day'); assert.equal(moment([2000, 1, 29, 25]).invalidAt(), 3, '25 is invalid hour'); assert.equal(moment([2000, 1, 29, 24, 1]).invalidAt(), 3, '24:01 is invalid hour'); assert.equal(moment([2000, 1, 29, 23, 60]).invalidAt(), 4, '60 is invalid minute'); assert.equal(moment([2000, 1, 29, 23, 59, 60]).invalidAt(), 5, '60 is invalid second'); assert.equal(moment([2000, 1, 29, 23, 59, 59, 1000]).invalidAt(), 6, '1000 is invalid millisecond'); assert.equal(moment([2000, 1, 29, 23, 59, 59, 999]).invalidAt(), -1, '-1 if everything is fine'); }); test('valid Unix timestamp', function (assert) { assert.equal(moment(1371065286, 'X').isValid(), true, 'number integer'); assert.equal(moment(1379066897.0, 'X').isValid(), true, 'number whole 1dp'); assert.equal(moment(1379066897.7, 'X').isValid(), true, 'number 1dp'); assert.equal(moment(1379066897.00, 'X').isValid(), true, 'number whole 2dp'); assert.equal(moment(1379066897.07, 'X').isValid(), true, 'number 2dp'); assert.equal(moment(1379066897.17, 'X').isValid(), true, 'number 2dp'); assert.equal(moment(1379066897.000, 'X').isValid(), true, 'number whole 3dp'); assert.equal(moment(1379066897.007, 'X').isValid(), true, 'number 3dp'); assert.equal(moment(1379066897.017, 'X').isValid(), true, 'number 3dp'); assert.equal(moment(1379066897.157, 'X').isValid(), true, 'number 3dp'); assert.equal(moment('1371065286', 'X').isValid(), true, 'string integer'); assert.equal(moment('1379066897.', 'X').isValid(), true, 'string trailing .'); assert.equal(moment('1379066897.0', 'X').isValid(), true, 'string whole 1dp'); assert.equal(moment('1379066897.7', 'X').isValid(), true, 'string 1dp'); assert.equal(moment('1379066897.00', 'X').isValid(), true, 'string whole 2dp'); assert.equal(moment('1379066897.07', 'X').isValid(), true, 'string 2dp'); assert.equal(moment('1379066897.17', 'X').isValid(), true, 'string 2dp'); assert.equal(moment('1379066897.000', 'X').isValid(), true, 'string whole 3dp'); assert.equal(moment('1379066897.007', 'X').isValid(), true, 'string 3dp'); assert.equal(moment('1379066897.017', 'X').isValid(), true, 'string 3dp'); assert.equal(moment('1379066897.157', 'X').isValid(), true, 'string 3dp'); }); test('invalid Unix timestamp', function (assert) { assert.equal(moment(undefined, 'X').isValid(), false, 'undefined'); assert.equal(moment('undefined', 'X').isValid(), false, 'string undefined'); try { assert.equal(moment(null, 'X').isValid(), false, 'null'); } catch (e) { assert.ok(true, 'null'); } assert.equal(moment('null', 'X').isValid(), false, 'string null'); assert.equal(moment([], 'X').isValid(), false, 'array'); assert.equal(moment('{}', 'X').isValid(), false, 'object'); try { assert.equal(moment('', 'X').isValid(), false, 'string empty'); } catch (e) { assert.ok(true, 'string empty'); } assert.equal(moment(' ', 'X').isValid(), false, 'string space'); }); test('valid Unix offset milliseconds', function (assert) { assert.equal(moment(1234567890123, 'x').isValid(), true, 'number integer'); assert.equal(moment('1234567890123', 'x').isValid(), true, 'string integer'); }); test('invalid Unix offset milliseconds', function (assert) { assert.equal(moment(undefined, 'x').isValid(), false, 'undefined'); assert.equal(moment('undefined', 'x').isValid(), false, 'string undefined'); try { assert.equal(moment(null, 'x').isValid(), false, 'null'); } catch (e) { assert.ok(true, 'null'); } assert.equal(moment('null', 'x').isValid(), false, 'string null'); assert.equal(moment([], 'x').isValid(), false, 'array'); assert.equal(moment('{}', 'x').isValid(), false, 'object'); try { assert.equal(moment('', 'x').isValid(), false, 'string empty'); } catch (e) { assert.ok(true, 'string empty'); } assert.equal(moment(' ', 'x').isValid(), false, 'string space'); }); test('empty', function (assert) { assert.equal(moment(null).isValid(), false, 'null'); assert.equal(moment('').isValid(), false, 'empty string'); assert.equal(moment(null, 'YYYY').isValid(), false, 'format + null'); assert.equal(moment('', 'YYYY').isValid(), false, 'format + empty string'); assert.equal(moment(' ', 'YYYY').isValid(), false, 'format + empty when trimmed'); }); test('days of the year', function (assert) { assert.equal(moment('2010 300', 'YYYY DDDD').isValid(), true, 'day 300 of year valid'); assert.equal(moment('2010 365', 'YYYY DDDD').isValid(), true, 'day 365 of year valid'); assert.equal(moment('2010 366', 'YYYY DDDD').isValid(), false, 'day 366 of year invalid'); assert.equal(moment('2012 365', 'YYYY DDDD').isValid(), true, 'day 365 of leap year valid'); assert.equal(moment('2012 366', 'YYYY DDDD').isValid(), true, 'day 366 of leap year valid'); assert.equal(moment('2012 367', 'YYYY DDDD').isValid(), false, 'day 367 of leap year invalid'); }); test('24:00:00.000 is valid', function (assert) { assert.equal(moment('2014-01-01 24', 'YYYY-MM-DD HH').isValid(), true, '24 is valid'); assert.equal(moment('2014-01-01 24:00', 'YYYY-MM-DD HH:mm').isValid(), true, '24:00 is valid'); assert.equal(moment('2014-01-01 24:01', 'YYYY-MM-DD HH:mm').isValid(), false, '24:01 is not valid'); }); test('oddball permissiveness', function (assert) { //path_to_url assert.ok(moment('2010-10-3199', ['MM/DD/YYYY', 'MM-DD-YYYY', 'YYYY-MM-DD']).isValid()); //path_to_url assert.ok(moment('3:25', ['h:mma', 'hh:mma', 'H:mm', 'HH:mm']).isValid()); }); test('0 hour is invalid in strict', function (assert) { assert.equal(moment('00:01', 'hh:mm', true).isValid(), false, '00 hour is invalid in strict'); assert.equal(moment('00:01', 'hh:mm').isValid(), true, '00 hour is valid in normal'); assert.equal(moment('0:01', 'h:mm', true).isValid(), false, '0 hour is invalid in strict'); assert.equal(moment('0:01', 'h:mm').isValid(), true, '0 hour is valid in normal'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('leap year'); test('leap year', function (assert) { assert.equal(moment([2010, 0, 1]).isLeapYear(), false, '2010'); assert.equal(moment([2100, 0, 1]).isLeapYear(), false, '2100'); assert.equal(moment([2008, 0, 1]).isLeapYear(), true, '2008'); assert.equal(moment([2000, 0, 1]).isLeapYear(), true, '2000'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('listers'); test('default', function (assert) { assert.deepEqual(moment.months(), ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']); assert.deepEqual(moment.monthsShort(), ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']); assert.deepEqual(moment.weekdays(), ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']); assert.deepEqual(moment.weekdaysShort(), ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']); assert.deepEqual(moment.weekdaysMin(), ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']); }); test('index', function (assert) { assert.equal(moment.months(0), 'January'); assert.equal(moment.months(2), 'March'); assert.equal(moment.monthsShort(0), 'Jan'); assert.equal(moment.monthsShort(2), 'Mar'); assert.equal(moment.weekdays(0), 'Sunday'); assert.equal(moment.weekdays(2), 'Tuesday'); assert.equal(moment.weekdaysShort(0), 'Sun'); assert.equal(moment.weekdaysShort(2), 'Tue'); assert.equal(moment.weekdaysMin(0), 'Su'); assert.equal(moment.weekdaysMin(2), 'Tu'); }); test('localized', function (assert) { var months = 'one_two_three_four_five_six_seven_eight_nine_ten_eleven_twelve'.split('_'), monthsShort = 'on_tw_th_fo_fi_si_se_ei_ni_te_el_tw'.split('_'), weekdays = 'one_two_three_four_five_six_seven'.split('_'), weekdaysShort = 'on_tw_th_fo_fi_si_se'.split('_'), weekdaysMin = '1_2_3_4_5_6_7'.split('_'), weekdaysLocale = 'four_five_six_seven_one_two_three'.split('_'), weekdaysShortLocale = 'fo_fi_si_se_on_tw_th'.split('_'), weekdaysMinLocale = '4_5_6_7_1_2_3'.split('_'), week = { dow : 3, doy : 6 }; moment.locale('numerologists', { months : months, monthsShort : monthsShort, weekdays : weekdays, weekdaysShort: weekdaysShort, weekdaysMin: weekdaysMin, week : week }); assert.deepEqual(moment.months(), months); assert.deepEqual(moment.monthsShort(), monthsShort); assert.deepEqual(moment.weekdays(), weekdays); assert.deepEqual(moment.weekdaysShort(), weekdaysShort); assert.deepEqual(moment.weekdaysMin(), weekdaysMin); assert.equal(moment.months(0), 'one'); assert.equal(moment.monthsShort(0), 'on'); assert.equal(moment.weekdays(0), 'one'); assert.equal(moment.weekdaysShort(0), 'on'); assert.equal(moment.weekdaysMin(0), '1'); assert.equal(moment.months(2), 'three'); assert.equal(moment.monthsShort(2), 'th'); assert.equal(moment.weekdays(2), 'three'); assert.equal(moment.weekdaysShort(2), 'th'); assert.equal(moment.weekdaysMin(2), '3'); assert.deepEqual(moment.weekdays(true), weekdaysLocale); assert.deepEqual(moment.weekdaysShort(true), weekdaysShortLocale); assert.deepEqual(moment.weekdaysMin(true), weekdaysMinLocale); assert.equal(moment.weekdays(true, 0), 'four'); assert.equal(moment.weekdaysShort(true, 0), 'fo'); assert.equal(moment.weekdaysMin(true, 0), '4'); assert.equal(moment.weekdays(false, 2), 'three'); assert.equal(moment.weekdaysShort(false, 2), 'th'); assert.equal(moment.weekdaysMin(false, 2), '3'); }); test('with functions', function (assert) { var monthsShort = 'one_two_three_four_five_six_seven_eight_nine_ten_eleven_twelve'.split('_'), monthsShortWeird = your_sha256_hashensy_elevensy_twelvesy'.split('_'); moment.locale('difficult', { monthsShort: function (m, format) { var arr = format.match(/-MMM-/) ? monthsShortWeird : monthsShort; return arr[m.month()]; } }); assert.deepEqual(moment.monthsShort(), monthsShort); assert.deepEqual(moment.monthsShort('MMM'), monthsShort); assert.deepEqual(moment.monthsShort('-MMM-'), monthsShortWeird); assert.deepEqual(moment.monthsShort('MMM', 2), 'three'); assert.deepEqual(moment.monthsShort('-MMM-', 2), 'threesy'); assert.deepEqual(moment.monthsShort(2), 'three'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } 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; }; } module('locale', { setup : function () { // TODO: Remove once locales are switched to ES6 each([{ name: 'en-gb', data: {} }, { name: 'en-ca', data: {} }, { name: 'es', data: { relativeTime: {past: 'hace %s', s: 'unos segundos', d: 'un da'}, months: your_sha256_hashubre_noviembre_diciembre'.split('_') } }, { name: 'fr', data: {} }, { name: 'fr-ca', data: {} }, { name: 'it', data: {} }, { name: 'zh-cn', data: { months: '___________'.split('_') } }], function (locale) { if (moment.locale(locale.name) !== locale.name) { moment.defineLocale(locale.name, locale.data); } }); moment.locale('en'); } }); test('library getters and setters', function (assert) { var r = moment.locale('en'); assert.equal(r, 'en', 'locale should return en by default'); assert.equal(moment.locale(), 'en', 'locale should return en by default'); moment.locale('fr'); assert.equal(moment.locale(), 'fr', 'locale should return the changed locale'); moment.locale('en-gb'); assert.equal(moment.locale(), 'en-gb', 'locale should return the changed locale'); moment.locale('en'); assert.equal(moment.locale(), 'en', 'locale should reset'); moment.locale('does-not-exist'); assert.equal(moment.locale(), 'en', 'locale should reset'); moment.locale('EN'); assert.equal(moment.locale(), 'en', 'Normalize locale key case'); moment.locale('EN_gb'); assert.equal(moment.locale(), 'en-gb', 'Normalize locale key underscore'); }); test('library setter array of locales', function (assert) { assert.equal(moment.locale(['non-existent', 'fr', 'also-non-existent']), 'fr', 'passing an array uses the first valid locale'); assert.equal(moment.locale(['es', 'fr', 'also-non-existent']), 'es', 'passing an array uses the first valid locale'); }); test('library setter locale substrings', function (assert) { assert.equal(moment.locale('fr-crap'), 'fr', 'use substrings'); assert.equal(moment.locale('fr-does-not-exist'), 'fr', 'uses deep substrings'); assert.equal(moment.locale('fr-CA-does-not-exist'), 'fr-ca', 'uses deepest substring'); }); test('library getter locale array and substrings', function (assert) { assert.equal(moment.locale(['en-CH', 'fr']), 'en', 'prefer root locale to shallower ones'); assert.equal(moment.locale(['en-gb-leeds', 'en-CA']), 'en-gb', 'prefer root locale to shallower ones'); assert.equal(moment.locale(['en-fake', 'en-CA']), 'en-ca', 'prefer alternatives with shared roots'); assert.equal(moment.locale(['en-fake', 'en-fake2', 'en-ca']), 'en-ca', 'prefer alternatives with shared roots'); assert.equal(moment.locale(['fake-CA', 'fake-MX', 'fr']), 'fr', 'always find something if possible'); assert.equal(moment.locale(['fake-CA', 'fake-MX', 'fr']), 'fr', 'always find something if possible'); assert.equal(moment.locale(['fake-CA', 'fake-MX', 'fr-fake-fake-fake']), 'fr', 'always find something if possible'); assert.equal(moment.locale(['en', 'en-CA']), 'en', 'prefer earlier if it works'); }); test('library ensure inheritance', function (assert) { moment.locale('made-up', { // I put them out of order months : your_sha256_hashmber_December_January'.split('_') // the rest of the properties should be inherited. }); assert.equal(moment([2012, 5, 6]).format('MMMM'), 'July', 'Override some of the configs'); assert.equal(moment([2012, 5, 6]).format('MMM'), 'Jun', 'But not all of them'); }); test('library ensure inheritance LT L LL LLL LLLL', function (assert) { var locale = 'test-inherit-lt'; moment.defineLocale(locale, { longDateFormat : { LT : '-[LT]-', L : '-[L]-', LL : '-[LL]-', LLL : '-[LLL]-', LLLL : '-[LLLL]-' }, calendar : { sameDay : '[sameDay] LT', nextDay : '[nextDay] L', nextWeek : '[nextWeek] LL', lastDay : '[lastDay] LLL', lastWeek : '[lastWeek] LLLL', sameElse : 'L' } }); moment.locale('es'); assert.equal(moment().locale(locale).calendar(), 'sameDay -LT-', 'Should use instance locale in LT formatting'); assert.equal(moment().add(1, 'days').locale(locale).calendar(), 'nextDay -L-', 'Should use instance locale in L formatting'); assert.equal(moment().add(-1, 'days').locale(locale).calendar(), 'lastDay -LLL-', 'Should use instance locale in LL formatting'); assert.equal(moment().add(4, 'days').locale(locale).calendar(), 'nextWeek -LL-', 'Should use instance locale in LLL formatting'); assert.equal(moment().add(-4, 'days').locale(locale).calendar(), 'lastWeek -LLLL-', 'Should use instance locale in LLLL formatting'); }); test('library localeData', function (assert) { moment.locale('en'); var jan = moment([2000, 0]); assert.equal(moment.localeData().months(jan), 'January', 'no arguments returns global'); assert.equal(moment.localeData('zh-cn').months(jan), '', 'a string returns the locale based on key'); assert.equal(moment.localeData(moment().locale('es')).months(jan), 'enero', 'if you pass in a moment it uses the moment\'s locale'); }); test('library deprecations', function (assert) { test.expectedDeprecations('moment.lang'); moment.lang('dude', {months: ['Movember']}); assert.equal(moment.locale(), 'dude', 'setting the lang sets the locale'); assert.equal(moment.lang(), moment.locale()); assert.equal(moment.langData(), moment.localeData(), 'langData is localeData'); moment.defineLocale('dude', null); }); test('defineLocale', function (assert) { moment.locale('en'); moment.defineLocale('dude', {months: ['Movember']}); assert.equal(moment().locale(), 'dude', 'defineLocale also sets it'); assert.equal(moment().locale('dude').locale(), 'dude', 'defineLocale defines a locale'); moment.defineLocale('dude', null); }); test('locales', function (assert) { moment.defineLocale('dude', {months: ['Movember']}); assert.equal(true, !!~indexOf.call(moment.locales(), 'dude'), 'locales returns an array of defined locales'); assert.equal(true, !!~indexOf.call(moment.locales(), 'en'), 'locales should always include english'); moment.defineLocale('dude', null); }); test('library convenience', function (assert) { moment.locale('something', {week: {dow: 3}}); moment.locale('something'); assert.equal(moment.locale(), 'something', 'locale can be used to create the locale too'); moment.defineLocale('something', null); }); test('firstDayOfWeek firstDayOfYear locale getters', function (assert) { moment.locale('something', {week: {dow: 3, doy: 4}}); moment.locale('something'); assert.equal(moment.localeData().firstDayOfWeek(), 3, 'firstDayOfWeek'); assert.equal(moment.localeData().firstDayOfYear(), 4, 'firstDayOfYear'); moment.defineLocale('something', null); }); test('instance locale method', function (assert) { moment.locale('en'); assert.equal(moment([2012, 5, 6]).format('MMMM'), 'June', 'Normally default to global'); assert.equal(moment([2012, 5, 6]).locale('es').format('MMMM'), 'junio', 'Use the instance specific locale'); assert.equal(moment([2012, 5, 6]).format('MMMM'), 'June', 'Using an instance specific locale does not affect other moments'); }); test('instance locale method with array', function (assert) { var m = moment().locale(['non-existent', 'fr', 'also-non-existent']); assert.equal(m.locale(), 'fr', 'passing an array uses the first valid locale'); m = moment().locale(['es', 'fr', 'also-non-existent']); assert.equal(m.locale(), 'es', 'passing an array uses the first valid locale'); }); test('instance getter locale substrings', function (assert) { var m = moment(); m.locale('fr-crap'); assert.equal(m.locale(), 'fr', 'use substrings'); m.locale('fr-does-not-exist'); assert.equal(m.locale(), 'fr', 'uses deep substrings'); }); test('instance locale persists with manipulation', function (assert) { moment.locale('en'); assert.equal(moment([2012, 5, 6]).locale('es').add({days: 1}).format('MMMM'), 'junio', 'With addition'); assert.equal(moment([2012, 5, 6]).locale('es').day(0).format('MMMM'), 'junio', 'With day getter'); assert.equal(moment([2012, 5, 6]).locale('es').endOf('day').format('MMMM'), 'junio', 'With endOf'); }); test('instance locale persists with cloning', function (assert) { moment.locale('en'); var a = moment([2012, 5, 6]).locale('es'), b = a.clone(), c = moment(a); assert.equal(b.format('MMMM'), 'junio', 'using moment.fn.clone()'); assert.equal(b.format('MMMM'), 'junio', 'using moment()'); }); test('duration locale method', function (assert) { moment.locale('en'); assert.equal(moment.duration({seconds: 44}).humanize(), 'a few seconds', 'Normally default to global'); assert.equal(moment.duration({seconds: 44}).locale('es').humanize(), 'unos segundos', 'Use the instance specific locale'); assert.equal(moment.duration({seconds: 44}).humanize(), 'a few seconds', 'Using an instance specific locale does not affect other durations'); }); test('duration locale persists with cloning', function (assert) { moment.locale('en'); var a = moment.duration({seconds: 44}).locale('es'), b = moment.duration(a); assert.equal(b.humanize(), 'unos segundos', 'using moment.duration()'); }); test('changing the global locale doesn\'t affect existing duration instances', function (assert) { var mom = moment.duration(); moment.locale('fr'); assert.equal('en', mom.locale()); }); test('duration deprecations', function (assert) { test.expectedDeprecations('moment().lang()'); assert.equal(moment.duration().lang(), moment.duration().localeData(), 'duration.lang is the same as duration.localeData'); }); test('from and fromNow with invalid date', function (assert) { assert.equal(moment(NaN).from(), 'Invalid date', 'moment.from with invalid moment'); assert.equal(moment(NaN).fromNow(), 'Invalid date', 'moment.fromNow with invalid moment'); }); test('from relative time future', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).subtract({s: 44})), 'in a few seconds', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).subtract({s: 45})), 'in a minute', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).subtract({s: 89})), 'in a minute', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).subtract({s: 90})), 'in 2 minutes', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).subtract({m: 44})), 'in 44 minutes', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).subtract({m: 45})), 'in an hour', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).subtract({m: 89})), 'in an hour', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).subtract({m: 90})), 'in 2 hours', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).subtract({h: 5})), 'in 5 hours', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).subtract({h: 21})), 'in 21 hours', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).subtract({h: 22})), 'in a day', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).subtract({h: 35})), 'in a day', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).subtract({h: 36})), 'in 2 days', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).subtract({d: 1})), 'in a day', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).subtract({d: 5})), 'in 5 days', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).subtract({d: 25})), 'in 25 days', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).subtract({d: 26})), 'in a month', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).subtract({d: 30})), 'in a month', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).subtract({d: 45})), 'in a month', '45 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).subtract({d: 47})), 'in 2 months', '47 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).subtract({d: 74})), 'in 2 months', '74 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).subtract({d: 78})), 'in 3 months', '78 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).subtract({M: 1})), 'in a month', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).subtract({M: 5})), 'in 5 months', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).subtract({d: 315})), 'in 10 months', '315 days = 10 months'); assert.equal(start.from(moment([2007, 1, 28]).subtract({d: 344})), 'in a year', '344 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).subtract({d: 345})), 'in a year', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).subtract({d: 548})), 'in 2 years', '548 days = in 2 years'); assert.equal(start.from(moment([2007, 1, 28]).subtract({y: 1})), 'in a year', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).subtract({y: 5})), 'in 5 years', '5 years = 5 years'); }); test('from relative time past', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 44})), 'a few seconds ago', '44 seconds = a few seconds'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 45})), 'a minute ago', '45 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 89})), 'a minute ago', '89 seconds = a minute'); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90})), '2 minutes ago', '90 seconds = 2 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 44})), '44 minutes ago', '44 minutes = 44 minutes'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 45})), 'an hour ago', '45 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 89})), 'an hour ago', '89 minutes = an hour'); assert.equal(start.from(moment([2007, 1, 28]).add({m: 90})), '2 hours ago', '90 minutes = 2 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 5})), '5 hours ago', '5 hours = 5 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 21})), '21 hours ago', '21 hours = 21 hours'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 22})), 'a day ago', '22 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 35})), 'a day ago', '35 hours = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({h: 36})), '2 days ago', '36 hours = 2 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 1})), 'a day ago', '1 day = a day'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 5})), '5 days ago', '5 days = 5 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 25})), '25 days ago', '25 days = 25 days'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 26})), 'a month ago', '26 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 30})), 'a month ago', '30 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 43})), 'a month ago', '43 days = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 46})), '2 months ago', '46 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 74})), '2 months ago', '75 days = 2 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 76})), '3 months ago', '76 days = 3 months'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 1})), 'a month ago', '1 month = a month'); assert.equal(start.from(moment([2007, 1, 28]).add({M: 5})), '5 months ago', '5 months = 5 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 315})), '10 months ago', '315 days = 10 months'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 344})), 'a year ago', '344 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 345})), 'a year ago', '345 days = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({d: 548})), '2 years ago', '548 days = 2 years'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 1})), 'a year ago', '1 year = a year'); assert.equal(start.from(moment([2007, 1, 28]).add({y: 5})), '5 years ago', '5 years = 5 years'); }); test('instance locale used with from', function (assert) { moment.locale('en'); var a = moment([2012, 5, 6]).locale('es'), b = moment([2012, 5, 7]); assert.equal(a.from(b), 'hace un da', 'preserve locale of first moment'); assert.equal(b.from(a), 'in a day', 'do not preserve locale of second moment'); }); test('instance localeData', function (assert) { moment.defineLocale('dude', {week: {dow: 3}}); assert.equal(moment().locale('dude').localeData()._week.dow, 3); moment.defineLocale('dude', null); }); test('month name callback function', function (assert) { function fakeReplace(m, format) { if (/test/.test(format)) { return 'test'; } if (m.date() === 1) { return 'date'; } return 'default'; } moment.locale('made-up-2', { months : fakeReplace, monthsShort : fakeReplace, weekdays : fakeReplace, weekdaysShort : fakeReplace, weekdaysMin : fakeReplace }); assert.equal(moment().format('[test] dd ddd dddd MMM MMMM'), 'test test test test test test', 'format month name function should be able to access the format string'); assert.equal(moment([2011, 0, 1]).format('dd ddd dddd MMM MMMM'), 'date date date date date', 'format month name function should be able to access the moment object'); assert.equal(moment([2011, 0, 2]).format('dd ddd dddd MMM MMMM'), 'default default default default default', 'format month name function should be able to access the moment object'); }); test('changing parts of a locale config', function (assert) { test.expectedDeprecations('defineLocaleOverride'); moment.locale('partial-lang', { months : 'a b c d e f g h i j k l'.split(' ') }); assert.equal(moment([2011, 0, 1]).format('MMMM'), 'a', 'should be able to set locale values when creating the localeuage'); moment.locale('partial-lang', { monthsShort : 'A B C D E F G H I J K L'.split(' ') }); assert.equal(moment([2011, 0, 1]).format('MMMM MMM'), 'a A', 'should be able to set locale values after creating the localeuage'); moment.defineLocale('partial-lang', null); }); test('start/endOf week feature for first-day-is-monday locales', function (assert) { moment.locale('monday-lang', { week : { dow : 1 // Monday is the first day of the week } }); moment.locale('monday-lang'); assert.equal(moment([2013, 0, 1]).startOf('week').day(), 1, 'for locale monday-lang first day of the week should be monday'); assert.equal(moment([2013, 0, 1]).endOf('week').day(), 0, 'for locale monday-lang last day of the week should be sunday'); moment.defineLocale('monday-lang', null); }); test('meridiem parsing', function (assert) { moment.locale('meridiem-parsing', { meridiemParse : /[bd]/i, isPM : function (input) { return input === 'b'; } }); moment.locale('meridiem-parsing'); assert.equal(moment('2012-01-01 3b', 'YYYY-MM-DD ha').hour(), 15, 'Custom parsing of meridiem should work'); assert.equal(moment('2012-01-01 3d', 'YYYY-MM-DD ha').hour(), 3, 'Custom parsing of meridiem should work'); moment.defineLocale('meridiem-parsing', null); }); test('invalid date formatting', function (assert) { moment.locale('has-invalid', { invalidDate: 'KHAAAAAAAAAAAN!' }); assert.equal(moment.invalid().format(), 'KHAAAAAAAAAAAN!'); assert.equal(moment.invalid().format('YYYY-MM-DD'), 'KHAAAAAAAAAAAN!'); moment.defineLocale('has-invalid', null); }); test('return locale name', function (assert) { var registered = moment.locale('return-this', {}); assert.equal(registered, 'return-this', 'returns the locale configured'); moment.locale('return-this', null); }); test('changing the global locale doesn\'t affect existing instances', function (assert) { var mom = moment(); moment.locale('fr'); assert.equal('en', mom.locale()); }); test('setting a language on instance returns the original moment for chaining', function (assert) { test.expectedDeprecations('moment().lang()'); var mom = moment(); assert.equal(mom.lang('fr'), mom, 'setting the language (lang) returns the original moment for chaining'); assert.equal(mom.locale('it'), mom, 'setting the language (locale) returns the original moment for chaining'); }); test('lang(key) changes the language of the instance', function (assert) { test.expectedDeprecations('moment().lang()'); var m = moment().month(0); m.lang('fr'); assert.equal(m.locale(), 'fr', 'm.lang(key) changes instance locale'); }); test('moment#locale(false) resets to global locale', function (assert) { var m = moment(); moment.locale('fr'); m.locale('it'); assert.equal(moment.locale(), 'fr', 'global locale is it'); assert.equal(m.locale(), 'it', 'instance locale is it'); m.locale(false); assert.equal(m.locale(), 'fr', 'instance locale reset to global locale'); }); test('moment().locale with missing key doesn\'t change locale', function (assert) { assert.equal(moment().locale('boo').localeData(), moment.localeData(), 'preserve global locale in case of bad locale id'); }); test('moment().lang with missing key doesn\'t change locale', function (assert) { test.expectedDeprecations('moment().lang()'); assert.equal(moment().lang('boo').localeData(), moment.localeData(), 'preserve global locale in case of bad locale id'); }); // TODO: Enable this after fixing pl months parse hack hack // test('monthsParseExact', function (assert) { // var locale = 'test-months-parse-exact'; // moment.defineLocale(locale, { // monthsParseExact: true, // months: 'A_AA_AAA_B_B B_BB B_C_C-C_C,C2C_D_D+D_D`D*D'.split('_'), // monthsShort: 'E_EE_EEE_F_FF_FFF_G_GG_GGG_H_HH_HHH'.split('_') // }); // assert.equal(moment('A', 'MMMM', true).month(), 0, 'parse long month 0 with MMMM'); // assert.equal(moment('AA', 'MMMM', true).month(), 1, 'parse long month 1 with MMMM'); // assert.equal(moment('AAA', 'MMMM', true).month(), 2, 'parse long month 2 with MMMM'); // assert.equal(moment('B B', 'MMMM', true).month(), 4, 'parse long month 4 with MMMM'); // assert.equal(moment('BB B', 'MMMM', true).month(), 5, 'parse long month 5 with MMMM'); // assert.equal(moment('C-C', 'MMMM', true).month(), 7, 'parse long month 7 with MMMM'); // assert.equal(moment('C,C2C', 'MMMM', true).month(), 8, 'parse long month 8 with MMMM'); // assert.equal(moment('D+D', 'MMMM', true).month(), 10, 'parse long month 10 with MMMM'); // assert.equal(moment('D`D*D', 'MMMM', true).month(), 11, 'parse long month 11 with MMMM'); // assert.equal(moment('E', 'MMM', true).month(), 0, 'parse long month 0 with MMM'); // assert.equal(moment('EE', 'MMM', true).month(), 1, 'parse long month 1 with MMM'); // assert.equal(moment('EEE', 'MMM', true).month(), 2, 'parse long month 2 with MMM'); // assert.equal(moment('A', 'MMM').month(), 0, 'non-strict parse long month 0 with MMM'); // assert.equal(moment('AA', 'MMM').month(), 1, 'non-strict parse long month 1 with MMM'); // assert.equal(moment('AAA', 'MMM').month(), 2, 'non-strict parse long month 2 with MMM'); // assert.equal(moment('E', 'MMMM').month(), 0, 'non-strict parse short month 0 with MMMM'); // assert.equal(moment('EE', 'MMMM').month(), 1, 'non-strict parse short month 1 with MMMM'); // assert.equal(moment('EEE', 'MMMM').month(), 2, 'non-strict parse short month 2 with MMMM'); // }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('locale inheritance'); test('calendar', function (assert) { moment.defineLocale('base-cal', { calendar : { sameDay: '[Today at] HH:mm', nextDay: '[Tomorrow at] HH:mm', nextWeek: '[Next week at] HH:mm', lastDay: '[Yesterday at] HH:mm', lastWeek: '[Last week at] HH:mm', sameElse: '[whatever]' } }); moment.defineLocale('child-cal', { parentLocale: 'base-cal', calendar: { sameDay: '[Today] HH:mm', nextDay: '[Tomorrow] HH:mm', nextWeek: '[Next week] HH:mm' } }); moment.locale('child-cal'); var anchor = moment.utc('2015-05-05T12:00:00', moment.ISO_8601); assert.equal(anchor.clone().add(3, 'hours').calendar(anchor), 'Today 15:00', 'today uses child version'); assert.equal(anchor.clone().add(1, 'day').calendar(anchor), 'Tomorrow 12:00', 'tomorrow uses child version'); assert.equal(anchor.clone().add(3, 'days').calendar(anchor), 'Next week 12:00', 'next week uses child version'); assert.equal(anchor.clone().subtract(1, 'day').calendar(anchor), 'Yesterday at 12:00', 'yesterday uses parent version'); assert.equal(anchor.clone().subtract(3, 'days').calendar(anchor), 'Last week at 12:00', 'last week uses parent version'); assert.equal(anchor.clone().subtract(7, 'days').calendar(anchor), 'whatever', 'sameElse uses parent version -'); assert.equal(anchor.clone().add(7, 'days').calendar(anchor), 'whatever', 'sameElse uses parent version +'); }); test('missing', function (assert) { moment.defineLocale('base-cal-2', { calendar: { sameDay: '[Today at] HH:mm', nextDay: '[Tomorrow at] HH:mm', nextWeek: '[Next week at] HH:mm', lastDay: '[Yesterday at] HH:mm', lastWeek: '[Last week at] HH:mm', sameElse: '[whatever]' } }); moment.defineLocale('child-cal-2', { parentLocale: 'base-cal-2' }); moment.locale('child-cal-2'); var anchor = moment.utc('2015-05-05T12:00:00', moment.ISO_8601); assert.equal(anchor.clone().add(3, 'hours').calendar(anchor), 'Today at 15:00', 'today uses parent version'); assert.equal(anchor.clone().add(1, 'day').calendar(anchor), 'Tomorrow at 12:00', 'tomorrow uses parent version'); assert.equal(anchor.clone().add(3, 'days').calendar(anchor), 'Next week at 12:00', 'next week uses parent version'); assert.equal(anchor.clone().subtract(1, 'day').calendar(anchor), 'Yesterday at 12:00', 'yesterday uses parent version'); assert.equal(anchor.clone().subtract(3, 'days').calendar(anchor), 'Last week at 12:00', 'last week uses parent version'); assert.equal(anchor.clone().subtract(7, 'days').calendar(anchor), 'whatever', 'sameElse uses parent version -'); assert.equal(anchor.clone().add(7, 'days').calendar(anchor), 'whatever', 'sameElse uses parent version +'); }); // Test function vs obj both directions test('long date format', function (assert) { moment.defineLocale('base-ldf', { longDateFormat : { 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' } }); moment.defineLocale('child-ldf', { parentLocale: 'base-ldf', longDateFormat: { LLL : '[child] MMMM D, YYYY h:mm A', LLLL : '[child] dddd, MMMM D, YYYY h:mm A' } }); moment.locale('child-ldf'); var anchor = moment.utc('2015-09-06T12:34:56', moment.ISO_8601); assert.equal(anchor.format('LTS'), '12:34:56 PM', 'LTS uses base'); assert.equal(anchor.format('LT'), '12:34 PM', 'LT uses base'); assert.equal(anchor.format('L'), '09/06/2015', 'L uses base'); assert.equal(anchor.format('l'), '9/6/2015', 'l uses base'); assert.equal(anchor.format('LL'), 'September 6, 2015', 'LL uses base'); assert.equal(anchor.format('ll'), 'Sep 6, 2015', 'll uses base'); assert.equal(anchor.format('LLL'), 'child September 6, 2015 12:34 PM', 'LLL uses child'); assert.equal(anchor.format('lll'), 'child Sep 6, 2015 12:34 PM', 'lll uses child'); assert.equal(anchor.format('LLLL'), 'child Sunday, September 6, 2015 12:34 PM', 'LLLL uses child'); assert.equal(anchor.format('llll'), 'child Sun, Sep 6, 2015 12:34 PM', 'llll uses child'); }); test('ordinal', function (assert) { moment.defineLocale('base-ordinal-1', { ordinal : '%dx' }); moment.defineLocale('child-ordinal-1', { parentLocale: 'base-ordinal-1', ordinal : '%dy' }); assert.equal(moment.utc('2015-02-03', moment.ISO_8601).format('Do'), '3y', 'ordinal uses child string'); moment.defineLocale('base-ordinal-2', { ordinal : '%dx' }); moment.defineLocale('child-ordinal-2', { parentLocale: 'base-ordinal-2', ordinal : function (num) { return num + 'y'; } }); assert.equal(moment.utc('2015-02-03', moment.ISO_8601).format('Do'), '3y', 'ordinal uses child function'); moment.defineLocale('base-ordinal-3', { ordinal : function (num) { return num + 'x'; } }); moment.defineLocale('child-ordinal-3', { parentLocale: 'base-ordinal-3', ordinal : '%dy' }); assert.equal(moment.utc('2015-02-03', moment.ISO_8601).format('Do'), '3y', 'ordinal uses child string (overwrite parent function)'); }); test('ordinal parse', function (assert) { moment.defineLocale('base-ordinal-parse-1', { ordinalParse : /\d{1,2}x/ }); moment.defineLocale('child-ordinal-parse-1', { parentLocale: 'base-ordinal-parse-1', ordinalParse : /\d{1,2}y/ }); assert.ok(moment.utc('2015-01-1y', 'YYYY-MM-Do', true).isValid(), 'ordinal parse uses child'); moment.defineLocale('base-ordinal-parse-2', { ordinalParse : /\d{1,2}x/ }); moment.defineLocale('child-ordinal-parse-2', { parentLocale: 'base-ordinal-parse-2', ordinalParse : null }); assert.ok(moment.utc('2015-01-1', 'YYYY-MM-Do', true).isValid(), 'ordinal parse uses child (default)'); }); test('months', function (assert) { moment.defineLocale('base-months', { months : 'One_Two_Three_Four_Five_Six_Seven_Eight_Nine_Ten_Eleven_Twelve'.split('_') }); moment.defineLocale('child-months', { parentLocale: 'base-months', months : your_sha256_hash_Eleventh_Twelveth '.split('_') }); assert.ok(moment.utc('2015-01-01', 'YYYY-MM-DD').format('MMMM'), 'First', 'months uses child'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('locale update'); test('calendar', function (assert) { moment.defineLocale('cal', null); moment.defineLocale('cal', { calendar : { sameDay: '[Today at] HH:mm', nextDay: '[Tomorrow at] HH:mm', nextWeek: '[Next week at] HH:mm', lastDay: '[Yesterday at] HH:mm', lastWeek: '[Last week at] HH:mm', sameElse: '[whatever]' } }); moment.updateLocale('cal', { calendar: { sameDay: '[Today] HH:mm', nextDay: '[Tomorrow] HH:mm', nextWeek: '[Next week] HH:mm' } }); moment.locale('cal'); var anchor = moment.utc('2015-05-05T12:00:00', moment.ISO_8601); assert.equal(anchor.clone().add(3, 'hours').calendar(anchor), 'Today 15:00', 'today uses child version'); assert.equal(anchor.clone().add(1, 'day').calendar(anchor), 'Tomorrow 12:00', 'tomorrow uses child version'); assert.equal(anchor.clone().add(3, 'days').calendar(anchor), 'Next week 12:00', 'next week uses child version'); assert.equal(anchor.clone().subtract(1, 'day').calendar(anchor), 'Yesterday at 12:00', 'yesterday uses parent version'); assert.equal(anchor.clone().subtract(3, 'days').calendar(anchor), 'Last week at 12:00', 'last week uses parent version'); assert.equal(anchor.clone().subtract(7, 'days').calendar(anchor), 'whatever', 'sameElse uses parent version -'); assert.equal(anchor.clone().add(7, 'days').calendar(anchor), 'whatever', 'sameElse uses parent version +'); }); test('missing', function (assert) { moment.defineLocale('cal-2', null); moment.defineLocale('cal-2', { calendar: { sameDay: '[Today at] HH:mm', nextDay: '[Tomorrow at] HH:mm', nextWeek: '[Next week at] HH:mm', lastDay: '[Yesterday at] HH:mm', lastWeek: '[Last week at] HH:mm', sameElse: '[whatever]' } }); moment.updateLocale('cal-2', { }); moment.locale('cal-2'); var anchor = moment.utc('2015-05-05T12:00:00', moment.ISO_8601); assert.equal(anchor.clone().add(3, 'hours').calendar(anchor), 'Today at 15:00', 'today uses parent version'); assert.equal(anchor.clone().add(1, 'day').calendar(anchor), 'Tomorrow at 12:00', 'tomorrow uses parent version'); assert.equal(anchor.clone().add(3, 'days').calendar(anchor), 'Next week at 12:00', 'next week uses parent version'); assert.equal(anchor.clone().subtract(1, 'day').calendar(anchor), 'Yesterday at 12:00', 'yesterday uses parent version'); assert.equal(anchor.clone().subtract(3, 'days').calendar(anchor), 'Last week at 12:00', 'last week uses parent version'); assert.equal(anchor.clone().subtract(7, 'days').calendar(anchor), 'whatever', 'sameElse uses parent version -'); assert.equal(anchor.clone().add(7, 'days').calendar(anchor), 'whatever', 'sameElse uses parent version +'); }); // Test function vs obj both directions test('long date format', function (assert) { moment.defineLocale('ldf', null); moment.defineLocale('ldf', { longDateFormat : { 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' } }); moment.updateLocale('ldf', { longDateFormat: { LLL : '[child] MMMM D, YYYY h:mm A', LLLL : '[child] dddd, MMMM D, YYYY h:mm A' } }); moment.locale('ldf'); var anchor = moment.utc('2015-09-06T12:34:56', moment.ISO_8601); assert.equal(anchor.format('LTS'), '12:34:56 PM', 'LTS uses base'); assert.equal(anchor.format('LT'), '12:34 PM', 'LT uses base'); assert.equal(anchor.format('L'), '09/06/2015', 'L uses base'); assert.equal(anchor.format('l'), '9/6/2015', 'l uses base'); assert.equal(anchor.format('LL'), 'September 6, 2015', 'LL uses base'); assert.equal(anchor.format('ll'), 'Sep 6, 2015', 'll uses base'); assert.equal(anchor.format('LLL'), 'child September 6, 2015 12:34 PM', 'LLL uses child'); assert.equal(anchor.format('lll'), 'child Sep 6, 2015 12:34 PM', 'lll uses child'); assert.equal(anchor.format('LLLL'), 'child Sunday, September 6, 2015 12:34 PM', 'LLLL uses child'); assert.equal(anchor.format('llll'), 'child Sun, Sep 6, 2015 12:34 PM', 'llll uses child'); }); test('ordinal', function (assert) { moment.defineLocale('ordinal-1', null); moment.defineLocale('ordinal-1', { ordinal : '%dx' }); moment.updateLocale('ordinal-1', { ordinal : '%dy' }); assert.equal(moment.utc('2015-02-03', moment.ISO_8601).format('Do'), '3y', 'ordinal uses child string'); moment.defineLocale('ordinal-2', null); moment.defineLocale('ordinal-2', { ordinal : '%dx' }); moment.updateLocale('ordinal-2', { ordinal : function (num) { return num + 'y'; } }); assert.equal(moment.utc('2015-02-03', moment.ISO_8601).format('Do'), '3y', 'ordinal uses child function'); moment.defineLocale('ordinal-3', null); moment.defineLocale('ordinal-3', { ordinal : function (num) { return num + 'x'; } }); moment.updateLocale('ordinal-3', { ordinal : '%dy' }); assert.equal(moment.utc('2015-02-03', moment.ISO_8601).format('Do'), '3y', 'ordinal uses child string (overwrite parent function)'); }); test('ordinal parse', function (assert) { moment.defineLocale('ordinal-parse-1', null); moment.defineLocale('ordinal-parse-1', { ordinalParse : /\d{1,2}x/ }); moment.updateLocale('ordinal-parse-1', { ordinalParse : /\d{1,2}y/ }); assert.ok(moment.utc('2015-01-1y', 'YYYY-MM-Do', true).isValid(), 'ordinal parse uses child'); moment.defineLocale('ordinal-parse-2', null); moment.defineLocale('ordinal-parse-2', { ordinalParse : /\d{1,2}x/ }); moment.updateLocale('ordinal-parse-2', { ordinalParse : null }); assert.ok(moment.utc('2015-01-1', 'YYYY-MM-Do', true).isValid(), 'ordinal parse uses child (default)'); }); test('months', function (assert) { moment.defineLocale('months', null); moment.defineLocale('months', { months : 'One_Two_Three_Four_Five_Six_Seven_Eight_Nine_Ten_Eleven_Twelve'.split('_') }); moment.updateLocale('months', { parentLocale: 'base-months', months : your_sha256_hash_Eleventh_Twelveth '.split('_') }); assert.ok(moment.utc('2015-01-01', 'YYYY-MM-DD').format('MMMM'), 'First', 'months uses child'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('min max'); test('min', function (assert) { var now = moment(), future = now.clone().add(1, 'month'), past = now.clone().subtract(1, 'month'), invalid = moment.invalid(); assert.equal(moment.min(now, future, past), past, 'min(now, future, past)'); assert.equal(moment.min(future, now, past), past, 'min(future, now, past)'); assert.equal(moment.min(future, past, now), past, 'min(future, past, now)'); assert.equal(moment.min(past, future, now), past, 'min(past, future, now)'); assert.equal(moment.min(now, past), past, 'min(now, past)'); assert.equal(moment.min(past, now), past, 'min(past, now)'); assert.equal(moment.min(now), now, 'min(now, past)'); assert.equal(moment.min([now, future, past]), past, 'min([now, future, past])'); assert.equal(moment.min([now, past]), past, 'min(now, past)'); assert.equal(moment.min([now]), now, 'min(now)'); assert.equal(moment.min([now, invalid]), invalid, 'min(now, invalid)'); assert.equal(moment.min([invalid, now]), invalid, 'min(invalid, now)'); }); test('max', function (assert) { var now = moment(), future = now.clone().add(1, 'month'), past = now.clone().subtract(1, 'month'), invalid = moment.invalid(); assert.equal(moment.max(now, future, past), future, 'max(now, future, past)'); assert.equal(moment.max(future, now, past), future, 'max(future, now, past)'); assert.equal(moment.max(future, past, now), future, 'max(future, past, now)'); assert.equal(moment.max(past, future, now), future, 'max(past, future, now)'); assert.equal(moment.max(now, past), now, 'max(now, past)'); assert.equal(moment.max(past, now), now, 'max(past, now)'); assert.equal(moment.max(now), now, 'max(now, past)'); assert.equal(moment.max([now, future, past]), future, 'max([now, future, past])'); assert.equal(moment.max([now, past]), now, 'max(now, past)'); assert.equal(moment.max([now]), now, 'max(now)'); assert.equal(moment.max([now, invalid]), invalid, 'max(now, invalid)'); assert.equal(moment.max([invalid, now]), invalid, 'max(invalid, now)'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('mutable'); test('manipulation methods', function (assert) { var m = moment(); assert.equal(m, m.year(2011), 'year() should be mutable'); assert.equal(m, m.month(1), 'month() should be mutable'); assert.equal(m, m.hours(7), 'hours() should be mutable'); assert.equal(m, m.minutes(33), 'minutes() should be mutable'); assert.equal(m, m.seconds(44), 'seconds() should be mutable'); assert.equal(m, m.milliseconds(55), 'milliseconds() should be mutable'); assert.equal(m, m.day(2), 'day() should be mutable'); assert.equal(m, m.startOf('week'), 'startOf() should be mutable'); assert.equal(m, m.add(1, 'days'), 'add() should be mutable'); assert.equal(m, m.subtract(2, 'years'), 'subtract() should be mutable'); assert.equal(m, m.local(), 'local() should be mutable'); assert.equal(m, m.utc(), 'utc() should be mutable'); }); test('non mutable methods', function (assert) { var m = moment(); assert.notEqual(m, m.clone(), 'clone() should not be mutable'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('normalize units'); test('normalize units', function (assert) { var fullKeys = ['year', 'quarter', 'month', 'isoWeek', 'week', 'day', 'hour', 'minute', 'second', 'millisecond', 'date', 'dayOfYear', 'weekday', 'isoWeekday', 'weekYear', 'isoWeekYear'], aliases = ['y', 'Q', 'M', 'W', 'w', 'd', 'h', 'm', 's', 'ms', 'D', 'DDD', 'e', 'E', 'gg', 'GG'], length = fullKeys.length, fullKey, fullKeyCaps, fullKeyPlural, fullKeyCapsPlural, fullKeyLower, alias, index; for (index = 0; index < length; index += 1) { fullKey = fullKeys[index]; fullKeyCaps = fullKey.toUpperCase(); fullKeyLower = fullKey.toLowerCase(); fullKeyPlural = fullKey + 's'; fullKeyCapsPlural = fullKeyCaps + 's'; alias = aliases[index]; assert.equal(moment.normalizeUnits(fullKey), fullKey, 'Testing full key ' + fullKey); assert.equal(moment.normalizeUnits(fullKeyCaps), fullKey, 'Testing full key capitalised ' + fullKey); assert.equal(moment.normalizeUnits(fullKeyPlural), fullKey, 'Testing full key plural ' + fullKey); assert.equal(moment.normalizeUnits(fullKeyCapsPlural), fullKey, 'Testing full key capitalised and plural ' + fullKey); assert.equal(moment.normalizeUnits(alias), fullKey, 'Testing alias ' + fullKey); } }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('now'); test('now', function (assert) { var startOfTest = new Date().valueOf(), momentNowTime = moment.now(), afterMomentCreationTime = new Date().valueOf(); assert.ok(startOfTest <= momentNowTime, 'moment now() time should be now, not in the past'); assert.ok(momentNowTime <= afterMomentCreationTime, 'moment now() time should be now, not in the future'); }); test('now - Date mocked', function (assert) { // We need to test mocking the global Date object, so disable 'Read Only' jshint check /* jshint -W020 */ var RealDate = Date, customTimeMs = moment('2015-01-01T01:30:00.000Z').valueOf(); function MockDate() { return new RealDate(customTimeMs); } MockDate.now = function () { return new MockDate().valueOf(); }; MockDate.prototype = RealDate.prototype; Date = MockDate; try { assert.equal(moment().valueOf(), customTimeMs, 'moment now() time should use the global Date object'); } finally { Date = RealDate; } }); test('now - custom value', function (assert) { var customTimeStr = '2015-01-01T01:30:00.000Z', customTime = moment(customTimeStr, moment.ISO_8601).valueOf(), oldFn = moment.now; moment.now = function () { return customTime; }; try { assert.ok(moment().toISOString() === customTimeStr, 'moment() constructor should use the function defined by moment.now, but it did not'); assert.ok(moment.utc().toISOString() === customTimeStr, 'moment() constructor should use the function defined by moment.now, but it did not'); assert.ok(moment.utc([]).toISOString() === '2015-01-01T00:00:00.000Z', 'moment() constructor should fall back to the date defined by moment.now when an empty array is given, but it did not'); } finally { moment.now = oldFn; } }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('parsing flags'); function flags () { return moment.apply(null, arguments).parsingFlags(); } test('overflow with array', function (assert) { //months assert.equal(flags([2010, 0]).overflow, -1, 'month 0 valid'); assert.equal(flags([2010, 1]).overflow, -1, 'month 1 valid'); assert.equal(flags([2010, -1]).overflow, 1, 'month -1 invalid'); assert.equal(flags([2100, 12]).overflow, 1, 'month 12 invalid'); //days assert.equal(flags([2010, 1, 16]).overflow, -1, 'date valid'); assert.equal(flags([2010, 1, -1]).overflow, 2, 'date -1 invalid'); assert.equal(flags([2010, 1, 0]).overflow, 2, 'date 0 invalid'); assert.equal(flags([2010, 1, 32]).overflow, 2, 'date 32 invalid'); assert.equal(flags([2012, 1, 29]).overflow, -1, 'date leap year valid'); assert.equal(flags([2010, 1, 29]).overflow, 2, 'date leap year invalid'); //hours assert.equal(flags([2010, 1, 1, 8]).overflow, -1, 'hour valid'); assert.equal(flags([2010, 1, 1, 0]).overflow, -1, 'hour 0 valid'); assert.equal(flags([2010, 1, 1, -1]).overflow, 3, 'hour -1 invalid'); assert.equal(flags([2010, 1, 1, 25]).overflow, 3, 'hour 25 invalid'); assert.equal(flags([2010, 1, 1, 24, 1]).overflow, 3, 'hour 24:01 invalid'); //minutes assert.equal(flags([2010, 1, 1, 8, 15]).overflow, -1, 'minute valid'); assert.equal(flags([2010, 1, 1, 8, 0]).overflow, -1, 'minute 0 valid'); assert.equal(flags([2010, 1, 1, 8, -1]).overflow, 4, 'minute -1 invalid'); assert.equal(flags([2010, 1, 1, 8, 60]).overflow, 4, 'minute 60 invalid'); //seconds assert.equal(flags([2010, 1, 1, 8, 15, 12]).overflow, -1, 'second valid'); assert.equal(flags([2010, 1, 1, 8, 15, 0]).overflow, -1, 'second 0 valid'); assert.equal(flags([2010, 1, 1, 8, 15, -1]).overflow, 5, 'second -1 invalid'); assert.equal(flags([2010, 1, 1, 8, 15, 60]).overflow, 5, 'second 60 invalid'); //milliseconds assert.equal(flags([2010, 1, 1, 8, 15, 12, 345]).overflow, -1, 'millisecond valid'); assert.equal(flags([2010, 1, 1, 8, 15, 12, 0]).overflow, -1, 'millisecond 0 valid'); assert.equal(flags([2010, 1, 1, 8, 15, 12, -1]).overflow, 6, 'millisecond -1 invalid'); assert.equal(flags([2010, 1, 1, 8, 15, 12, 1000]).overflow, 6, 'millisecond 1000 invalid'); // 24 hrs assert.equal(flags([2010, 1, 1, 24, 0, 0, 0]).overflow, -1, '24:00:00.000 is fine'); assert.equal(flags([2010, 1, 1, 24, 1, 0, 0]).overflow, 3, '24:01:00.000 is wrong hour'); assert.equal(flags([2010, 1, 1, 24, 0, 1, 0]).overflow, 3, '24:00:01.000 is wrong hour'); assert.equal(flags([2010, 1, 1, 24, 0, 0, 1]).overflow, 3, '24:00:00.001 is wrong hour'); }); test('overflow without format', function (assert) { //months assert.equal(flags('2001-01', 'YYYY-MM').overflow, -1, 'month 1 valid'); assert.equal(flags('2001-12', 'YYYY-MM').overflow, -1, 'month 12 valid'); assert.equal(flags('2001-13', 'YYYY-MM').overflow, 1, 'month 13 invalid'); //days assert.equal(flags('2010-01-16', 'YYYY-MM-DD').overflow, -1, 'date 16 valid'); assert.equal(flags('2010-01-0', 'YYYY-MM-DD').overflow, 2, 'date 0 invalid'); assert.equal(flags('2010-01-32', 'YYYY-MM-DD').overflow, 2, 'date 32 invalid'); assert.equal(flags('2012-02-29', 'YYYY-MM-DD').overflow, -1, 'date leap year valid'); assert.equal(flags('2010-02-29', 'YYYY-MM-DD').overflow, 2, 'date leap year invalid'); //days of the year assert.equal(flags('2010 300', 'YYYY DDDD').overflow, -1, 'day 300 of year valid'); assert.equal(flags('2010 365', 'YYYY DDDD').overflow, -1, 'day 365 of year valid'); assert.equal(flags('2010 366', 'YYYY DDDD').overflow, 2, 'day 366 of year invalid'); assert.equal(flags('2012 366', 'YYYY DDDD').overflow, -1, 'day 366 of leap year valid'); assert.equal(flags('2012 367', 'YYYY DDDD').overflow, 2, 'day 367 of leap year invalid'); //hours assert.equal(flags('08', 'HH').overflow, -1, 'hour valid'); assert.equal(flags('00', 'HH').overflow, -1, 'hour 0 valid'); assert.equal(flags('25', 'HH').overflow, 3, 'hour 25 invalid'); assert.equal(flags('24:01', 'HH:mm').overflow, 3, 'hour 24:01 invalid'); //minutes assert.equal(flags('08:15', 'HH:mm').overflow, -1, 'minute valid'); assert.equal(flags('08:00', 'HH:mm').overflow, -1, 'minute 0 valid'); assert.equal(flags('08:60', 'HH:mm').overflow, 4, 'minute 60 invalid'); //seconds assert.equal(flags('08:15:12', 'HH:mm:ss').overflow, -1, 'second valid'); assert.equal(flags('08:15:00', 'HH:mm:ss').overflow, -1, 'second 0 valid'); assert.equal(flags('08:15:60', 'HH:mm:ss').overflow, 5, 'second 60 invalid'); //milliseconds assert.equal(flags('08:15:12:345', 'HH:mm:ss:SSSS').overflow, -1, 'millisecond valid'); assert.equal(flags('08:15:12:000', 'HH:mm:ss:SSSS').overflow, -1, 'millisecond 0 valid'); //this is OK because we don't match the last digit, so it's 100 ms assert.equal(flags('08:15:12:1000', 'HH:mm:ss:SSSS').overflow, -1, 'millisecond 1000 actually valid'); }); test('extra tokens', function (assert) { assert.deepEqual(flags('1982-05-25', 'YYYY-MM-DD').unusedTokens, [], 'nothing extra'); assert.deepEqual(flags('1982-05', 'YYYY-MM-DD').unusedTokens, ['DD'], 'extra formatting token'); assert.deepEqual(flags('1982', 'YYYY-MM-DD').unusedTokens, ['MM', 'DD'], 'multiple extra formatting tokens'); assert.deepEqual(flags('1982-05', 'YYYY-MM-').unusedTokens, [], 'extra non-formatting token'); assert.deepEqual(flags('1982-05-', 'YYYY-MM-DD').unusedTokens, ['DD'], 'non-extra non-formatting token'); assert.deepEqual(flags('1982 05 1982', 'YYYY-MM-DD').unusedTokens, [], 'different non-formatting token'); }); test('extra tokens strict', function (assert) { assert.deepEqual(flags('1982-05-25', 'YYYY-MM-DD', true).unusedTokens, [], 'nothing extra'); assert.deepEqual(flags('1982-05', 'YYYY-MM-DD', true).unusedTokens, ['-', 'DD'], 'extra formatting token'); assert.deepEqual(flags('1982', 'YYYY-MM-DD', true).unusedTokens, ['-', 'MM', '-', 'DD'], 'multiple extra formatting tokens'); assert.deepEqual(flags('1982-05', 'YYYY-MM-', true).unusedTokens, ['-'], 'extra non-formatting token'); assert.deepEqual(flags('1982-05-', 'YYYY-MM-DD', true).unusedTokens, ['DD'], 'non-extra non-formatting token'); assert.deepEqual(flags('1982 05 1982', 'YYYY-MM-DD', true).unusedTokens, ['-', '-'], 'different non-formatting token'); }); test('unused input', function (assert) { assert.deepEqual(flags('1982-05-25', 'YYYY-MM-DD').unusedInput, [], 'normal input'); assert.deepEqual(flags('1982-05-25 this is more stuff', 'YYYY-MM-DD').unusedInput, [' this is more stuff'], 'trailing nonsense'); assert.deepEqual(flags('1982-05-25 09:30', 'YYYY-MM-DD').unusedInput, [' 09:30'], ['trailing legit-looking input']); assert.deepEqual(flags('1982-05-25 some junk', 'YYYY-MM-DD [some junk]').unusedInput, [], 'junk that actually gets matched'); assert.deepEqual(flags('stuff at beginning 1982-05-25', 'YYYY-MM-DD').unusedInput, ['stuff at beginning '], 'leading junk'); assert.deepEqual(flags('junk 1982 more junk 05 yet more junk25', 'YYYY-MM-DD').unusedInput, ['junk ', ' more junk ', ' yet more junk'], 'interstitial junk'); }); test('unused input strict', function (assert) { assert.deepEqual(flags('1982-05-25', 'YYYY-MM-DD', true).unusedInput, [], 'normal input'); assert.deepEqual(flags('1982-05-25 this is more stuff', 'YYYY-MM-DD', true).unusedInput, [' this is more stuff'], 'trailing nonsense'); assert.deepEqual(flags('1982-05-25 09:30', 'YYYY-MM-DD', true).unusedInput, [' 09:30'], ['trailing legit-looking input']); assert.deepEqual(flags('1982-05-25 some junk', 'YYYY-MM-DD [some junk]', true).unusedInput, [], 'junk that actually gets matched'); assert.deepEqual(flags('stuff at beginning 1982-05-25', 'YYYY-MM-DD', true).unusedInput, ['stuff at beginning '], 'leading junk'); assert.deepEqual(flags('junk 1982 more junk 05 yet more junk25', 'YYYY-MM-DD', true).unusedInput, ['junk ', ' more junk ', ' yet more junk'], 'interstitial junk'); }); test('chars left over', function (assert) { assert.equal(flags('1982-05-25', 'YYYY-MM-DD').charsLeftOver, 0, 'normal input'); assert.equal(flags('1982-05-25 this is more stuff', 'YYYY-MM-DD').charsLeftOver, ' this is more stuff'.length, 'trailing nonsense'); assert.equal(flags('1982-05-25 09:30', 'YYYY-MM-DD').charsLeftOver, ' 09:30'.length, 'trailing legit-looking input'); assert.equal(flags('stuff at beginning 1982-05-25', 'YYYY-MM-DD').charsLeftOver, 'stuff at beginning '.length, 'leading junk'); assert.equal(flags('1982 junk 05 more junk25', 'YYYY-MM-DD').charsLeftOver, [' junk ', ' more junk'].join('').length, 'interstitial junk'); assert.equal(flags('stuff at beginning 1982 junk 05 more junk25', 'YYYY-MM-DD').charsLeftOver, ['stuff at beginning ', ' junk ', ' more junk'].join('').length, 'leading and interstitial junk'); }); test('empty', function (assert) { assert.equal(flags('1982-05-25', 'YYYY-MM-DD').empty, false, 'normal input'); assert.equal(flags('nothing here', 'YYYY-MM-DD').empty, true, 'pure garbage'); assert.equal(flags('junk but has the number 2000 in it', 'YYYY-MM-DD').empty, false, 'only mostly garbage'); assert.equal(flags('', 'YYYY-MM-DD').empty, true, 'empty string'); assert.equal(flags('', 'YYYY-MM-DD').empty, true, 'blank string'); }); test('null', function (assert) { assert.equal(flags('1982-05-25', 'YYYY-MM-DD').nullInput, false, 'normal input'); assert.equal(flags(null).nullInput, true, 'just null'); assert.equal(flags(null, 'YYYY-MM-DD').nullInput, true, 'null with format'); }); test('invalid month', function (assert) { assert.equal(flags('1982 May', 'YYYY MMMM').invalidMonth, null, 'normal input'); assert.equal(flags('1982 Laser', 'YYYY MMMM').invalidMonth, 'Laser', 'bad month name'); }); test('empty format array', function (assert) { assert.equal(flags('1982 May', ['YYYY MMM']).invalidFormat, false, 'empty format array'); assert.equal(flags('1982 May', []).invalidFormat, true, 'empty format array'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } var symbolMap = { '1': '!', '2': '@', '3': '#', '4': '$', '5': '%', '6': '^', '7': '&', '8': '*', '9': '(', '0': ')' }, numberMap = { '!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7', '*': '8', '(': '9', ')': '0' }; module('preparse and postformat', { setup: function () { moment.locale('symbol', { preparse: function (string) { return string.replace(/[!@#$%\^&*()]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); } }); }, teardown: function () { moment.defineLocale('symbol', null); } }); test('transform', function (assert) { assert.equal(moment.utc('@)!@-)*-@&', 'YYYY-MM-DD').unix(), 1346025600, 'preparse string + format'); assert.equal(moment.utc('@)!@-)*-@&').unix(), 1346025600, 'preparse ISO8601 string'); assert.equal(moment.unix(1346025600).utc().format('YYYY-MM-DD'), '@)!@-)*-@&', 'postformat'); }); test('transform from', function (assert) { var start = moment([2007, 1, 28]); assert.equal(start.from(moment([2007, 1, 28]).add({s: 90}), true), '@ minutes', 'postformat should work on moment.fn.from'); assert.equal(moment().add(6, 'd').fromNow(true), '^ days', 'postformat should work on moment.fn.fromNow'); assert.equal(moment.duration(10, 'h').humanize(), '!) hours', 'postformat should work on moment.duration.fn.humanize'); }); test('calendar day', function (assert) { var a = moment().hours(12).minutes(0).seconds(0); assert.equal(moment(a).calendar(), 'Today at !@:)) PM', 'today at the same time'); assert.equal(moment(a).add({m: 25}).calendar(), 'Today at !@:@% PM', 'Now plus 25 min'); assert.equal(moment(a).add({h: 1}).calendar(), 'Today at !:)) PM', 'Now plus 1 hour'); assert.equal(moment(a).add({d: 1}).calendar(), 'Tomorrow at !@:)) PM', 'tomorrow at the same time'); assert.equal(moment(a).subtract({h: 1}).calendar(), 'Today at !!:)) AM', 'Now minus 1 hour'); assert.equal(moment(a).subtract({d: 1}).calendar(), 'Yesterday at !@:)) PM', 'yesterday at the same time'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('quarter'); test('library quarter getter', function (assert) { assert.equal(moment([1985, 1, 4]).quarter(), 1, 'Feb 4 1985 is Q1'); assert.equal(moment([2029, 8, 18]).quarter(), 3, 'Sep 18 2029 is Q3'); assert.equal(moment([2013, 3, 24]).quarter(), 2, 'Apr 24 2013 is Q2'); assert.equal(moment([2015, 2, 5]).quarter(), 1, 'Mar 5 2015 is Q1'); assert.equal(moment([1970, 0, 2]).quarter(), 1, 'Jan 2 1970 is Q1'); assert.equal(moment([2001, 11, 12]).quarter(), 4, 'Dec 12 2001 is Q4'); assert.equal(moment([2000, 0, 2]).quarter(), 1, 'Jan 2 2000 is Q1'); }); test('quarter setter singular', function (assert) { var m = moment([2014, 4, 11]); assert.equal(m.quarter(2).month(), 4, 'set same quarter'); assert.equal(m.quarter(3).month(), 7, 'set 3rd quarter'); assert.equal(m.quarter(1).month(), 1, 'set 1st quarter'); assert.equal(m.quarter(4).month(), 10, 'set 4th quarter'); }); test('quarter setter plural', function (assert) { var m = moment([2014, 4, 11]); assert.equal(m.quarters(2).month(), 4, 'set same quarter'); assert.equal(m.quarters(3).month(), 7, 'set 3rd quarter'); assert.equal(m.quarters(1).month(), 1, 'set 1st quarter'); assert.equal(m.quarters(4).month(), 10, 'set 4th quarter'); }); test('quarter setter programmatic', function (assert) { var m = moment([2014, 4, 11]); assert.equal(m.set('quarter', 2).month(), 4, 'set same quarter'); assert.equal(m.set('quarter', 3).month(), 7, 'set 3rd quarter'); assert.equal(m.set('quarter', 1).month(), 1, 'set 1st quarter'); assert.equal(m.set('quarter', 4).month(), 10, 'set 4th quarter'); }); test('quarter setter programmatic plural', function (assert) { var m = moment([2014, 4, 11]); assert.equal(m.set('quarters', 2).month(), 4, 'set same quarter'); assert.equal(m.set('quarters', 3).month(), 7, 'set 3rd quarter'); assert.equal(m.set('quarters', 1).month(), 1, 'set 1st quarter'); assert.equal(m.set('quarters', 4).month(), 10, 'set 4th quarter'); }); test('quarter setter programmatic abbr', function (assert) { var m = moment([2014, 4, 11]); assert.equal(m.set('Q', 2).month(), 4, 'set same quarter'); assert.equal(m.set('Q', 3).month(), 7, 'set 3rd quarter'); assert.equal(m.set('Q', 1).month(), 1, 'set 1st quarter'); assert.equal(m.set('Q', 4).month(), 10, 'set 4th quarter'); }); test('quarter setter only month changes', function (assert) { var m = moment([2014, 4, 11, 1, 2, 3, 4]).quarter(4); assert.equal(m.year(), 2014, 'keep year'); assert.equal(m.month(), 10, 'set month'); assert.equal(m.date(), 11, 'keep date'); assert.equal(m.hour(), 1, 'keep hour'); assert.equal(m.minute(), 2, 'keep minutes'); assert.equal(m.second(), 3, 'keep seconds'); assert.equal(m.millisecond(), 4, 'keep milliseconds'); }); test('quarter setter bubble to next year', function (assert) { var m = moment([2014, 4, 11, 1, 2, 3, 4]).quarter(7); assert.equal(m.year(), 2015, 'year bubbled'); assert.equal(m.month(), 7, 'set month'); assert.equal(m.date(), 11, 'keep date'); assert.equal(m.hour(), 1, 'keep hour'); assert.equal(m.minute(), 2, 'keep minutes'); assert.equal(m.second(), 3, 'keep seconds'); assert.equal(m.millisecond(), 4, 'keep milliseconds'); }); test('quarter diff', function (assert) { assert.equal(moment('2014-01-01').diff(moment('2014-04-01'), 'quarter'), -1, 'diff -1 quarter'); assert.equal(moment('2014-04-01').diff(moment('2014-01-01'), 'quarter'), 1, 'diff 1 quarter'); assert.equal(moment('2014-05-01').diff(moment('2014-01-01'), 'quarter'), 1, 'diff 1 quarter'); assert.ok(Math.abs((4 / 3) - moment('2014-05-01').diff( moment('2014-01-01'), 'quarter', true)) < 0.00001, 'diff 1 1/3 quarter'); assert.equal(moment('2015-01-01').diff(moment('2014-01-01'), 'quarter'), 4, 'diff 4 quarters'); }); test('quarter setter bubble to previous year', function (assert) { var m = moment([2014, 4, 11, 1, 2, 3, 4]).quarter(-3); assert.equal(m.year(), 2013, 'year bubbled'); assert.equal(m.month(), 1, 'set month'); assert.equal(m.date(), 11, 'keep date'); assert.equal(m.hour(), 1, 'keep hour'); assert.equal(m.minute(), 2, 'keep minutes'); assert.equal(m.second(), 3, 'keep seconds'); assert.equal(m.millisecond(), 4, 'keep milliseconds'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('relative time'); test('default thresholds fromNow', function (assert) { var a = moment(); // Seconds to minutes threshold a.subtract(44, 'seconds'); assert.equal(a.fromNow(), 'a few seconds ago', 'Below default seconds to minutes threshold'); a.subtract(1, 'seconds'); assert.equal(a.fromNow(), 'a minute ago', 'Above default seconds to minutes threshold'); // Minutes to hours threshold a = moment(); a.subtract(44, 'minutes'); assert.equal(a.fromNow(), '44 minutes ago', 'Below default minute to hour threshold'); a.subtract(1, 'minutes'); assert.equal(a.fromNow(), 'an hour ago', 'Above default minute to hour threshold'); // Hours to days threshold a = moment(); a.subtract(21, 'hours'); assert.equal(a.fromNow(), '21 hours ago', 'Below default hours to day threshold'); a.subtract(1, 'hours'); assert.equal(a.fromNow(), 'a day ago', 'Above default hours to day threshold'); // Days to month threshold a = moment(); a.subtract(25, 'days'); assert.equal(a.fromNow(), '25 days ago', 'Below default days to month (singular) threshold'); a.subtract(1, 'days'); assert.equal(a.fromNow(), 'a month ago', 'Above default days to month (singular) threshold'); // months to year threshold a = moment(); a.subtract(10, 'months'); assert.equal(a.fromNow(), '10 months ago', 'Below default days to years threshold'); a.subtract(1, 'month'); assert.equal(a.fromNow(), 'a year ago', 'Above default days to years threshold'); }); test('default thresholds toNow', function (assert) { var a = moment(); // Seconds to minutes threshold a.subtract(44, 'seconds'); assert.equal(a.toNow(), 'in a few seconds', 'Below default seconds to minutes threshold'); a.subtract(1, 'seconds'); assert.equal(a.toNow(), 'in a minute', 'Above default seconds to minutes threshold'); // Minutes to hours threshold a = moment(); a.subtract(44, 'minutes'); assert.equal(a.toNow(), 'in 44 minutes', 'Below default minute to hour threshold'); a.subtract(1, 'minutes'); assert.equal(a.toNow(), 'in an hour', 'Above default minute to hour threshold'); // Hours to days threshold a = moment(); a.subtract(21, 'hours'); assert.equal(a.toNow(), 'in 21 hours', 'Below default hours to day threshold'); a.subtract(1, 'hours'); assert.equal(a.toNow(), 'in a day', 'Above default hours to day threshold'); // Days to month threshold a = moment(); a.subtract(25, 'days'); assert.equal(a.toNow(), 'in 25 days', 'Below default days to month (singular) threshold'); a.subtract(1, 'days'); assert.equal(a.toNow(), 'in a month', 'Above default days to month (singular) threshold'); // months to year threshold a = moment(); a.subtract(10, 'months'); assert.equal(a.toNow(), 'in 10 months', 'Below default days to years threshold'); a.subtract(1, 'month'); assert.equal(a.toNow(), 'in a year', 'Above default days to years threshold'); }); test('custom thresholds', function (assert) { var a; // Seconds to minute threshold, under 30 moment.relativeTimeThreshold('s', 25); a = moment(); a.subtract(24, 'seconds'); assert.equal(a.fromNow(), 'a few seconds ago', 'Below custom seconds to minute threshold, s < 30'); a.subtract(1, 'seconds'); assert.equal(a.fromNow(), 'a minute ago', 'Above custom seconds to minute threshold, s < 30'); // Seconds to minutes threshold moment.relativeTimeThreshold('s', 55); a = moment(); a.subtract(54, 'seconds'); assert.equal(a.fromNow(), 'a few seconds ago', 'Below custom seconds to minutes threshold'); a.subtract(1, 'seconds'); assert.equal(a.fromNow(), 'a minute ago', 'Above custom seconds to minutes threshold'); moment.relativeTimeThreshold('s', 45); // Minutes to hours threshold moment.relativeTimeThreshold('m', 55); a = moment(); a.subtract(54, 'minutes'); assert.equal(a.fromNow(), '54 minutes ago', 'Below custom minutes to hours threshold'); a.subtract(1, 'minutes'); assert.equal(a.fromNow(), 'an hour ago', 'Above custom minutes to hours threshold'); moment.relativeTimeThreshold('m', 45); // Hours to days threshold moment.relativeTimeThreshold('h', 24); a = moment(); a.subtract(23, 'hours'); assert.equal(a.fromNow(), '23 hours ago', 'Below custom hours to days threshold'); a.subtract(1, 'hours'); assert.equal(a.fromNow(), 'a day ago', 'Above custom hours to days threshold'); moment.relativeTimeThreshold('h', 22); // Days to month threshold moment.relativeTimeThreshold('d', 28); a = moment(); a.subtract(27, 'days'); assert.equal(a.fromNow(), '27 days ago', 'Below custom days to month (singular) threshold'); a.subtract(1, 'days'); assert.equal(a.fromNow(), 'a month ago', 'Above custom days to month (singular) threshold'); moment.relativeTimeThreshold('d', 26); // months to years threshold moment.relativeTimeThreshold('M', 9); a = moment(); a.subtract(8, 'months'); assert.equal(a.fromNow(), '8 months ago', 'Below custom days to years threshold'); a.subtract(1, 'months'); assert.equal(a.fromNow(), 'a year ago', 'Above custom days to years threshold'); moment.relativeTimeThreshold('M', 11); }); test('retrive threshold settings', function (assert) { moment.relativeTimeThreshold('m', 45); var minuteThreshold = moment.relativeTimeThreshold('m'); assert.equal(minuteThreshold, 45, 'Can retrieve minute setting'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('start and end of units'); test('start of year', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('year'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('years'), ma = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('y'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 0, 'strip out the month'); assert.equal(m.date(), 1, 'strip out the day'); assert.equal(m.hours(), 0, 'strip out the hours'); assert.equal(m.minutes(), 0, 'strip out the minutes'); assert.equal(m.seconds(), 0, 'strip out the seconds'); assert.equal(m.milliseconds(), 0, 'strip out the milliseconds'); }); test('end of year', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('year'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('years'), ma = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('y'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 11, 'set the month'); assert.equal(m.date(), 31, 'set the day'); assert.equal(m.hours(), 23, 'set the hours'); assert.equal(m.minutes(), 59, 'set the minutes'); assert.equal(m.seconds(), 59, 'set the seconds'); assert.equal(m.milliseconds(), 999, 'set the seconds'); }); test('start of quarter', function (assert) { var m = moment(new Date(2011, 4, 2, 3, 4, 5, 6)).startOf('quarter'), ms = moment(new Date(2011, 4, 2, 3, 4, 5, 6)).startOf('quarters'), ma = moment(new Date(2011, 4, 2, 3, 4, 5, 6)).startOf('Q'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.quarter(), 2, 'keep the quarter'); assert.equal(m.month(), 3, 'strip out the month'); assert.equal(m.date(), 1, 'strip out the day'); assert.equal(m.hours(), 0, 'strip out the hours'); assert.equal(m.minutes(), 0, 'strip out the minutes'); assert.equal(m.seconds(), 0, 'strip out the seconds'); assert.equal(m.milliseconds(), 0, 'strip out the milliseconds'); }); test('end of quarter', function (assert) { var m = moment(new Date(2011, 4, 2, 3, 4, 5, 6)).endOf('quarter'), ms = moment(new Date(2011, 4, 2, 3, 4, 5, 6)).endOf('quarters'), ma = moment(new Date(2011, 4, 2, 3, 4, 5, 6)).endOf('Q'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.quarter(), 2, 'keep the quarter'); assert.equal(m.month(), 5, 'set the month'); assert.equal(m.date(), 30, 'set the day'); assert.equal(m.hours(), 23, 'set the hours'); assert.equal(m.minutes(), 59, 'set the minutes'); assert.equal(m.seconds(), 59, 'set the seconds'); assert.equal(m.milliseconds(), 999, 'set the seconds'); }); test('start of month', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('month'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('months'), ma = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('M'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 1, 'keep the month'); assert.equal(m.date(), 1, 'strip out the day'); assert.equal(m.hours(), 0, 'strip out the hours'); assert.equal(m.minutes(), 0, 'strip out the minutes'); assert.equal(m.seconds(), 0, 'strip out the seconds'); assert.equal(m.milliseconds(), 0, 'strip out the milliseconds'); }); test('end of month', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('month'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('months'), ma = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('M'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 1, 'keep the month'); assert.equal(m.date(), 28, 'set the day'); assert.equal(m.hours(), 23, 'set the hours'); assert.equal(m.minutes(), 59, 'set the minutes'); assert.equal(m.seconds(), 59, 'set the seconds'); assert.equal(m.milliseconds(), 999, 'set the seconds'); }); test('start of week', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('week'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('weeks'), ma = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('w'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 0, 'rolls back to January'); assert.equal(m.day(), 0, 'set day of week'); assert.equal(m.date(), 30, 'set correct date'); assert.equal(m.hours(), 0, 'strip out the hours'); assert.equal(m.minutes(), 0, 'strip out the minutes'); assert.equal(m.seconds(), 0, 'strip out the seconds'); assert.equal(m.milliseconds(), 0, 'strip out the milliseconds'); }); test('end of week', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('week'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('weeks'), ma = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('weeks'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 1, 'keep the month'); assert.equal(m.day(), 6, 'set the day of the week'); assert.equal(m.date(), 5, 'set the day'); assert.equal(m.hours(), 23, 'set the hours'); assert.equal(m.minutes(), 59, 'set the minutes'); assert.equal(m.seconds(), 59, 'set the seconds'); assert.equal(m.milliseconds(), 999, 'set the seconds'); }); test('start of iso-week', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('isoWeek'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('isoWeeks'), ma = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('W'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 0, 'rollback to January'); assert.equal(m.isoWeekday(), 1, 'set day of iso-week'); assert.equal(m.date(), 31, 'set correct date'); assert.equal(m.hours(), 0, 'strip out the hours'); assert.equal(m.minutes(), 0, 'strip out the minutes'); assert.equal(m.seconds(), 0, 'strip out the seconds'); assert.equal(m.milliseconds(), 0, 'strip out the milliseconds'); }); test('end of iso-week', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('isoWeek'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('isoWeeks'), ma = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('W'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 1, 'keep the month'); assert.equal(m.isoWeekday(), 7, 'set the day of the week'); assert.equal(m.date(), 6, 'set the day'); assert.equal(m.hours(), 23, 'set the hours'); assert.equal(m.minutes(), 59, 'set the minutes'); assert.equal(m.seconds(), 59, 'set the seconds'); assert.equal(m.milliseconds(), 999, 'set the seconds'); }); test('start of day', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('day'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('days'), ma = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('d'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 1, 'keep the month'); assert.equal(m.date(), 2, 'keep the day'); assert.equal(m.hours(), 0, 'strip out the hours'); assert.equal(m.minutes(), 0, 'strip out the minutes'); assert.equal(m.seconds(), 0, 'strip out the seconds'); assert.equal(m.milliseconds(), 0, 'strip out the milliseconds'); }); test('end of day', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('day'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('days'), ma = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('d'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 1, 'keep the month'); assert.equal(m.date(), 2, 'keep the day'); assert.equal(m.hours(), 23, 'set the hours'); assert.equal(m.minutes(), 59, 'set the minutes'); assert.equal(m.seconds(), 59, 'set the seconds'); assert.equal(m.milliseconds(), 999, 'set the seconds'); }); test('start of date', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('date'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('dates'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 1, 'keep the month'); assert.equal(m.date(), 2, 'keep the day'); assert.equal(m.hours(), 0, 'strip out the hours'); assert.equal(m.minutes(), 0, 'strip out the minutes'); assert.equal(m.seconds(), 0, 'strip out the seconds'); assert.equal(m.milliseconds(), 0, 'strip out the milliseconds'); }); test('end of date', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('date'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('dates'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 1, 'keep the month'); assert.equal(m.date(), 2, 'keep the day'); assert.equal(m.hours(), 23, 'set the hours'); assert.equal(m.minutes(), 59, 'set the minutes'); assert.equal(m.seconds(), 59, 'set the seconds'); assert.equal(m.milliseconds(), 999, 'set the seconds'); }); test('start of hour', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('hour'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('hours'), ma = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('h'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 1, 'keep the month'); assert.equal(m.date(), 2, 'keep the day'); assert.equal(m.hours(), 3, 'keep the hours'); assert.equal(m.minutes(), 0, 'strip out the minutes'); assert.equal(m.seconds(), 0, 'strip out the seconds'); assert.equal(m.milliseconds(), 0, 'strip out the milliseconds'); }); test('end of hour', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('hour'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('hours'), ma = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('h'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 1, 'keep the month'); assert.equal(m.date(), 2, 'keep the day'); assert.equal(m.hours(), 3, 'keep the hours'); assert.equal(m.minutes(), 59, 'set the minutes'); assert.equal(m.seconds(), 59, 'set the seconds'); assert.equal(m.milliseconds(), 999, 'set the seconds'); }); test('start of minute', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('minute'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('minutes'), ma = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('m'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 1, 'keep the month'); assert.equal(m.date(), 2, 'keep the day'); assert.equal(m.hours(), 3, 'keep the hours'); assert.equal(m.minutes(), 4, 'keep the minutes'); assert.equal(m.seconds(), 0, 'strip out the seconds'); assert.equal(m.milliseconds(), 0, 'strip out the milliseconds'); }); test('end of minute', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('minute'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('minutes'), ma = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('m'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 1, 'keep the month'); assert.equal(m.date(), 2, 'keep the day'); assert.equal(m.hours(), 3, 'keep the hours'); assert.equal(m.minutes(), 4, 'keep the minutes'); assert.equal(m.seconds(), 59, 'set the seconds'); assert.equal(m.milliseconds(), 999, 'set the seconds'); }); test('start of second', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('second'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('seconds'), ma = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).startOf('s'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 1, 'keep the month'); assert.equal(m.date(), 2, 'keep the day'); assert.equal(m.hours(), 3, 'keep the hours'); assert.equal(m.minutes(), 4, 'keep the minutes'); assert.equal(m.seconds(), 5, 'keep the the seconds'); assert.equal(m.milliseconds(), 0, 'strip out the milliseconds'); }); test('end of second', function (assert) { var m = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('second'), ms = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('seconds'), ma = moment(new Date(2011, 1, 2, 3, 4, 5, 6)).endOf('s'); assert.equal(+m, +ms, 'Plural or singular should work'); assert.equal(+m, +ma, 'Full or abbreviated should work'); assert.equal(m.year(), 2011, 'keep the year'); assert.equal(m.month(), 1, 'keep the month'); assert.equal(m.date(), 2, 'keep the day'); assert.equal(m.hours(), 3, 'keep the hours'); assert.equal(m.minutes(), 4, 'keep the minutes'); assert.equal(m.seconds(), 5, 'keep the seconds'); assert.equal(m.milliseconds(), 999, 'set the seconds'); }); test('startOf across DST +1', function (assert) { var oldUpdateOffset = moment.updateOffset, // Based on a real story somewhere in America/Los_Angeles dstAt = moment('2014-03-09T02:00:00-08:00').parseZone(), m; moment.updateOffset = function (mom, keepTime) { if (mom.isBefore(dstAt)) { mom.utcOffset(-8, keepTime); } else { mom.utcOffset(-7, keepTime); } }; m = moment('2014-03-15T00:00:00-07:00').parseZone(); m.startOf('y'); assert.equal(m.format(), '2014-01-01T00:00:00-08:00', 'startOf(\'year\') across +1'); m = moment('2014-03-15T00:00:00-07:00').parseZone(); m.startOf('M'); assert.equal(m.format(), '2014-03-01T00:00:00-08:00', 'startOf(\'month\') across +1'); m = moment('2014-03-09T09:00:00-07:00').parseZone(); m.startOf('d'); assert.equal(m.format(), '2014-03-09T00:00:00-08:00', 'startOf(\'day\') across +1'); m = moment('2014-03-09T03:05:00-07:00').parseZone(); m.startOf('h'); assert.equal(m.format(), '2014-03-09T03:00:00-07:00', 'startOf(\'hour\') after +1'); m = moment('2014-03-09T01:35:00-08:00').parseZone(); m.startOf('h'); assert.equal(m.format(), '2014-03-09T01:00:00-08:00', 'startOf(\'hour\') before +1'); // There is no such time as 2:30-7 to try startOf('hour') across that moment.updateOffset = oldUpdateOffset; }); test('startOf across DST -1', function (assert) { var oldUpdateOffset = moment.updateOffset, // Based on a real story somewhere in America/Los_Angeles dstAt = moment('2014-11-02T02:00:00-07:00').parseZone(), m; moment.updateOffset = function (mom, keepTime) { if (mom.isBefore(dstAt)) { mom.utcOffset(-7, keepTime); } else { mom.utcOffset(-8, keepTime); } }; m = moment('2014-11-15T00:00:00-08:00').parseZone(); m.startOf('y'); assert.equal(m.format(), '2014-01-01T00:00:00-07:00', 'startOf(\'year\') across -1'); m = moment('2014-11-15T00:00:00-08:00').parseZone(); m.startOf('M'); assert.equal(m.format(), '2014-11-01T00:00:00-07:00', 'startOf(\'month\') across -1'); m = moment('2014-11-02T09:00:00-08:00').parseZone(); m.startOf('d'); assert.equal(m.format(), '2014-11-02T00:00:00-07:00', 'startOf(\'day\') across -1'); // note that utc offset is -8 m = moment('2014-11-02T01:30:00-08:00').parseZone(); m.startOf('h'); assert.equal(m.format(), '2014-11-02T01:00:00-08:00', 'startOf(\'hour\') after +1'); // note that utc offset is -7 m = moment('2014-11-02T01:30:00-07:00').parseZone(); m.startOf('h'); assert.equal(m.format(), '2014-11-02T01:00:00-07:00', 'startOf(\'hour\') before +1'); moment.updateOffset = oldUpdateOffset; }); test('endOf millisecond and no-arg', function (assert) { var m = moment(); assert.equal(+m, +m.clone().endOf(), 'endOf without argument should change time'); assert.equal(+m, +m.clone().endOf('ms'), 'endOf with ms argument should change time'); assert.equal(+m, +m.clone().endOf('millisecond'), 'endOf with millisecond argument should change time'); assert.equal(+m, +m.clone().endOf('milliseconds'), 'endOf with milliseconds argument should change time'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('string prototype'); test('string prototype overrides call', function (assert) { var prior = String.prototype.call, b; String.prototype.call = function () { return null; }; b = moment(new Date(2011, 7, 28, 15, 25, 50, 125)); assert.equal(b.format('MMMM Do YYYY, h:mm a'), 'August 28th 2011, 3:25 pm'); String.prototype.call = prior; }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('to type'); test('toObject', function (assert) { var expected = { years:2010, months:3, date:5, hours:15, minutes:10, seconds:3, milliseconds:123 }; assert.deepEqual(moment(expected).toObject(), expected, 'toObject invalid'); }); test('toArray', function (assert) { var expected = [2014, 11, 26, 11, 46, 58, 17]; assert.deepEqual(moment(expected).toArray(), expected, 'toArray invalid'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('utc'); test('utc and local', function (assert) { var m = moment(Date.UTC(2011, 1, 2, 3, 4, 5, 6)), offset, expected; m.utc(); // utc assert.equal(m.date(), 2, 'the day should be correct for utc'); assert.equal(m.day(), 3, 'the date should be correct for utc'); assert.equal(m.hours(), 3, 'the hours should be correct for utc'); // local m.local(); if (m.utcOffset() < -180) { assert.equal(m.date(), 1, 'the date should be correct for local'); assert.equal(m.day(), 2, 'the day should be correct for local'); } else { assert.equal(m.date(), 2, 'the date should be correct for local'); assert.equal(m.day(), 3, 'the day should be correct for local'); } offset = Math.floor(m.utcOffset() / 60); expected = (24 + 3 + offset) % 24; assert.equal(m.hours(), expected, 'the hours (' + m.hours() + ') should be correct for local'); assert.equal(moment().utc().utcOffset(), 0, 'timezone in utc should always be zero'); }); test('creating with utc and no arguments', function (assert) { var startOfTest = new Date().valueOf(), momentDefaultUtcTime = moment.utc().valueOf(), afterMomentCreationTime = new Date().valueOf(); assert.ok(startOfTest <= momentDefaultUtcTime, 'moment UTC default time should be now, not in the past'); assert.ok(momentDefaultUtcTime <= afterMomentCreationTime, 'moment UTC default time should be now, not in the future'); }); test('creating with utc and a date parameter array', function (assert) { var m = moment.utc([2011, 1, 2, 3, 4, 5, 6]); assert.equal(m.date(), 2, 'the day should be correct for utc array'); assert.equal(m.hours(), 3, 'the hours should be correct for utc array'); m = moment.utc('2011-02-02 3:04:05', 'YYYY-MM-DD HH:mm:ss'); assert.equal(m.date(), 2, 'the day should be correct for utc parsing format'); assert.equal(m.hours(), 3, 'the hours should be correct for utc parsing format'); m = moment.utc('2011-02-02T03:04:05+00:00'); assert.equal(m.date(), 2, 'the day should be correct for utc parsing iso'); assert.equal(m.hours(), 3, 'the hours should be correct for utc parsing iso'); }); test('creating with utc without timezone', function (assert) { var m = moment.utc('2012-01-02T08:20:00'); assert.equal(m.date(), 2, 'the day should be correct for utc parse without timezone'); assert.equal(m.hours(), 8, 'the hours should be correct for utc parse without timezone'); m = moment.utc('2012-01-02T08:20:00+09:00'); assert.equal(m.date(), 1, 'the day should be correct for utc parse with timezone'); assert.equal(m.hours(), 23, 'the hours should be correct for utc parse with timezone'); }); test('cloning with utc offset', function (assert) { var m = moment.utc('2012-01-02T08:20:00'); assert.equal(moment.utc(m)._isUTC, true, 'the local offset should be converted to UTC'); assert.equal(moment.utc(m.clone().utc())._isUTC, true, 'the local offset should stay in UTC'); m.utcOffset(120); assert.equal(moment.utc(m)._isUTC, true, 'the explicit utc offset should stay in UTC'); assert.equal(moment.utc(m).utcOffset(), 0, 'the explicit utc offset should have an offset of 0'); }); test('weekday with utc', function (assert) { assert.equal( moment('2013-09-15T00:00:00Z').utc().weekday(), // first minute of the day moment('2013-09-15T23:59:00Z').utc().weekday(), // last minute of the day 'a UTC-moment\'s .weekday() should not be affected by the local timezone' ); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('utc offset'); test('setter / getter blackbox', function (assert) { var m = moment([2010]); assert.equal(m.clone().utcOffset(0).utcOffset(), 0, 'utcOffset 0'); assert.equal(m.clone().utcOffset(1).utcOffset(), 60, 'utcOffset 1 is 60'); assert.equal(m.clone().utcOffset(60).utcOffset(), 60, 'utcOffset 60'); assert.equal(m.clone().utcOffset('+01:00').utcOffset(), 60, 'utcOffset +01:00 is 60'); assert.equal(m.clone().utcOffset('+0100').utcOffset(), 60, 'utcOffset +0100 is 60'); assert.equal(m.clone().utcOffset(-1).utcOffset(), -60, 'utcOffset -1 is -60'); assert.equal(m.clone().utcOffset(-60).utcOffset(), -60, 'utcOffset -60'); assert.equal(m.clone().utcOffset('-01:00').utcOffset(), -60, 'utcOffset -01:00 is -60'); assert.equal(m.clone().utcOffset('-0100').utcOffset(), -60, 'utcOffset -0100 is -60'); assert.equal(m.clone().utcOffset(1.5).utcOffset(), 90, 'utcOffset 1.5 is 90'); assert.equal(m.clone().utcOffset(90).utcOffset(), 90, 'utcOffset 1.5 is 90'); assert.equal(m.clone().utcOffset('+01:30').utcOffset(), 90, 'utcOffset +01:30 is 90'); assert.equal(m.clone().utcOffset('+0130').utcOffset(), 90, 'utcOffset +0130 is 90'); assert.equal(m.clone().utcOffset(-1.5).utcOffset(), -90, 'utcOffset -1.5'); assert.equal(m.clone().utcOffset(-90).utcOffset(), -90, 'utcOffset -90'); assert.equal(m.clone().utcOffset('-01:30').utcOffset(), -90, 'utcOffset +01:30 is 90'); assert.equal(m.clone().utcOffset('-0130').utcOffset(), -90, 'utcOffset +0130 is 90'); assert.equal(m.clone().utcOffset('+00:10').utcOffset(), 10, 'utcOffset +00:10 is 10'); assert.equal(m.clone().utcOffset('-00:10').utcOffset(), -10, 'utcOffset +00:10 is 10'); assert.equal(m.clone().utcOffset('+0010').utcOffset(), 10, 'utcOffset +0010 is 10'); assert.equal(m.clone().utcOffset('-0010').utcOffset(), -10, 'utcOffset +0010 is 10'); }); test('utcOffset shorthand hours -> minutes', function (assert) { var i; for (i = -15; i <= 15; ++i) { assert.equal(moment().utcOffset(i).utcOffset(), i * 60, '' + i + ' -> ' + i * 60); } assert.equal(moment().utcOffset(-16).utcOffset(), -16, '-16 -> -16'); assert.equal(moment().utcOffset(16).utcOffset(), 16, '16 -> 16'); }); test('isLocal, isUtc, isUtcOffset', function (assert) { assert.ok(moment().isLocal(), 'moment() creates objects in local time'); assert.ok(!moment.utc().isLocal(), 'moment.utc creates objects NOT in local time'); assert.ok(moment.utc().local().isLocal(), 'moment.fn.local() converts to local time'); assert.ok(!moment().utcOffset(5).isLocal(), 'moment.fn.utcOffset(N) puts objects NOT in local time'); assert.ok(moment().utcOffset(5).local().isLocal(), 'moment.fn.local() converts to local time'); assert.ok(moment.utc().isUtc(), 'moment.utc() creates objects in utc time'); assert.ok(moment().utcOffset(0).isUtc(), 'utcOffset(0) is equivalent to utc mode'); assert.ok(!moment().utcOffset(1).isUtc(), 'utcOffset(1) is NOT equivalent to utc mode'); assert.ok(!moment().isUtcOffset(), 'moment() creates objects NOT in utc-offset mode'); assert.ok(moment.utc().isUtcOffset(), 'moment.utc() creates objects in utc-offset mode'); assert.ok(moment().utcOffset(3).isUtcOffset(), 'utcOffset(N != 0) creates objects in utc-offset mode'); assert.ok(moment().utcOffset(0).isUtcOffset(), 'utcOffset(0) creates objects in utc-offset mode'); }); test('isUTC', function (assert) { assert.ok(moment.utc().isUTC(), 'moment.utc() creates objects in utc time'); assert.ok(moment().utcOffset(0).isUTC(), 'utcOffset(0) is equivalent to utc mode'); assert.ok(!moment().utcOffset(1).isUTC(), 'utcOffset(1) is NOT equivalent to utc mode'); }); test('change hours when changing the utc offset', function (assert) { var m = moment.utc([2000, 0, 1, 6]); assert.equal(m.hour(), 6, 'UTC 6AM should be 6AM at +0000'); // sanity check m.utcOffset(0); assert.equal(m.hour(), 6, 'UTC 6AM should be 6AM at +0000'); m.utcOffset(-60); assert.equal(m.hour(), 5, 'UTC 6AM should be 5AM at -0100'); m.utcOffset(60); assert.equal(m.hour(), 7, 'UTC 6AM should be 7AM at +0100'); }); test('change minutes when changing the utc offset', function (assert) { var m = moment.utc([2000, 0, 1, 6, 31]); m.utcOffset(0); assert.equal(m.format('HH:mm'), '06:31', 'UTC 6:31AM should be 6:31AM at +0000'); m.utcOffset(-30); assert.equal(m.format('HH:mm'), '06:01', 'UTC 6:31AM should be 6:01AM at -0030'); m.utcOffset(30); assert.equal(m.format('HH:mm'), '07:01', 'UTC 6:31AM should be 7:01AM at +0030'); m.utcOffset(-1380); assert.equal(m.format('HH:mm'), '07:31', 'UTC 6:31AM should be 7:31AM at +1380'); }); test('distance from the unix epoch', function (assert) { var zoneA = moment(), zoneB = moment(zoneA), zoneC = moment(zoneA), zoneD = moment(zoneA), zoneE = moment(zoneA); zoneB.utc(); assert.equal(+zoneA, +zoneB, 'moment should equal moment.utc'); zoneC.utcOffset(60); assert.equal(+zoneA, +zoneC, 'moment should equal moment.utcOffset(60)'); zoneD.utcOffset(-480); assert.equal(+zoneA, +zoneD, 'moment should equal moment.utcOffset(-480)'); zoneE.utcOffset(-1000); assert.equal(+zoneA, +zoneE, 'moment should equal moment.utcOffset(-1000)'); }); test('update offset after changing any values', function (assert) { var oldOffset = moment.updateOffset, m = moment.utc([2000, 6, 1]); moment.updateOffset = function (mom, keepTime) { if (mom.__doChange) { if (+mom > 962409600000) { mom.utcOffset(-120, keepTime); } else { mom.utcOffset(-60, keepTime); } } }; assert.equal(m.format('ZZ'), '+0000', 'should be at +0000'); assert.equal(m.format('HH:mm'), '00:00', 'should start 12AM at +0000 timezone'); m.__doChange = true; m.add(1, 'h'); assert.equal(m.format('ZZ'), '-0200', 'should be at -0200'); assert.equal(m.format('HH:mm'), '23:00', '1AM at +0000 should be 11PM at -0200 timezone'); m.subtract(1, 'h'); assert.equal(m.format('ZZ'), '-0100', 'should be at -0100'); assert.equal(m.format('HH:mm'), '23:00', '12AM at +0000 should be 11PM at -0100 timezone'); moment.updateOffset = oldOffset; }); ////////////////// test('getters and setters', function (assert) { var a = moment([2011, 5, 20]); assert.equal(a.clone().utcOffset(-120).year(2012).year(), 2012, 'should get and set year correctly'); assert.equal(a.clone().utcOffset(-120).month(1).month(), 1, 'should get and set month correctly'); assert.equal(a.clone().utcOffset(-120).date(2).date(), 2, 'should get and set date correctly'); assert.equal(a.clone().utcOffset(-120).day(1).day(), 1, 'should get and set day correctly'); assert.equal(a.clone().utcOffset(-120).hour(1).hour(), 1, 'should get and set hour correctly'); assert.equal(a.clone().utcOffset(-120).minute(1).minute(), 1, 'should get and set minute correctly'); }); test('getters', function (assert) { var a = moment.utc([2012, 0, 1, 0, 0, 0]); assert.equal(a.clone().utcOffset(-120).year(), 2011, 'should get year correctly'); assert.equal(a.clone().utcOffset(-120).month(), 11, 'should get month correctly'); assert.equal(a.clone().utcOffset(-120).date(), 31, 'should get date correctly'); assert.equal(a.clone().utcOffset(-120).hour(), 22, 'should get hour correctly'); assert.equal(a.clone().utcOffset(-120).minute(), 0, 'should get minute correctly'); assert.equal(a.clone().utcOffset(120).year(), 2012, 'should get year correctly'); assert.equal(a.clone().utcOffset(120).month(), 0, 'should get month correctly'); assert.equal(a.clone().utcOffset(120).date(), 1, 'should get date correctly'); assert.equal(a.clone().utcOffset(120).hour(), 2, 'should get hour correctly'); assert.equal(a.clone().utcOffset(120).minute(), 0, 'should get minute correctly'); assert.equal(a.clone().utcOffset(90).year(), 2012, 'should get year correctly'); assert.equal(a.clone().utcOffset(90).month(), 0, 'should get month correctly'); assert.equal(a.clone().utcOffset(90).date(), 1, 'should get date correctly'); assert.equal(a.clone().utcOffset(90).hour(), 1, 'should get hour correctly'); assert.equal(a.clone().utcOffset(90).minute(), 30, 'should get minute correctly'); }); test('from', function (assert) { var zoneA = moment(), zoneB = moment(zoneA).utcOffset(-720), zoneC = moment(zoneA).utcOffset(-360), zoneD = moment(zoneA).utcOffset(690), other = moment(zoneA).add(35, 'm'); assert.equal(zoneA.from(other), zoneB.from(other), 'moment#from should be the same in all zones'); assert.equal(zoneA.from(other), zoneC.from(other), 'moment#from should be the same in all zones'); assert.equal(zoneA.from(other), zoneD.from(other), 'moment#from should be the same in all zones'); }); test('diff', function (assert) { var zoneA = moment(), zoneB = moment(zoneA).utcOffset(-720), zoneC = moment(zoneA).utcOffset(-360), zoneD = moment(zoneA).utcOffset(690), other = moment(zoneA).add(35, 'm'); assert.equal(zoneA.diff(other), zoneB.diff(other), 'moment#diff should be the same in all zones'); assert.equal(zoneA.diff(other), zoneC.diff(other), 'moment#diff should be the same in all zones'); assert.equal(zoneA.diff(other), zoneD.diff(other), 'moment#diff should be the same in all zones'); assert.equal(zoneA.diff(other, 'minute', true), zoneB.diff(other, 'minute', true), 'moment#diff should be the same in all zones'); assert.equal(zoneA.diff(other, 'minute', true), zoneC.diff(other, 'minute', true), 'moment#diff should be the same in all zones'); assert.equal(zoneA.diff(other, 'minute', true), zoneD.diff(other, 'minute', true), 'moment#diff should be the same in all zones'); assert.equal(zoneA.diff(other, 'hour', true), zoneB.diff(other, 'hour', true), 'moment#diff should be the same in all zones'); assert.equal(zoneA.diff(other, 'hour', true), zoneC.diff(other, 'hour', true), 'moment#diff should be the same in all zones'); assert.equal(zoneA.diff(other, 'hour', true), zoneD.diff(other, 'hour', true), 'moment#diff should be the same in all zones'); }); test('unix offset and timestamp', function (assert) { var zoneA = moment(), zoneB = moment(zoneA).utcOffset(-720), zoneC = moment(zoneA).utcOffset(-360), zoneD = moment(zoneA).utcOffset(690); assert.equal(zoneA.unix(), zoneB.unix(), 'moment#unix should be the same in all zones'); assert.equal(zoneA.unix(), zoneC.unix(), 'moment#unix should be the same in all zones'); assert.equal(zoneA.unix(), zoneD.unix(), 'moment#unix should be the same in all zones'); assert.equal(+zoneA, +zoneB, 'moment#valueOf should be the same in all zones'); assert.equal(+zoneA, +zoneC, 'moment#valueOf should be the same in all zones'); assert.equal(+zoneA, +zoneD, 'moment#valueOf should be the same in all zones'); }); test('cloning', function (assert) { assert.equal(moment().utcOffset(-120).clone().utcOffset(), -120, 'explicit cloning should retain the offset'); assert.equal(moment().utcOffset(120).clone().utcOffset(), 120, 'explicit cloning should retain the offset'); assert.equal(moment(moment().utcOffset(-120)).utcOffset(), -120, 'implicit cloning should retain the offset'); assert.equal(moment(moment().utcOffset(120)).utcOffset(), 120, 'implicit cloning should retain the offset'); }); test('start of / end of', function (assert) { var a = moment.utc([2010, 1, 2, 0, 0, 0]).utcOffset(-450); assert.equal(a.clone().startOf('day').hour(), 0, 'start of day should work on moments with utc offset'); assert.equal(a.clone().startOf('day').minute(), 0, 'start of day should work on moments with utc offset'); assert.equal(a.clone().startOf('hour').minute(), 0, 'start of hour should work on moments with utc offset'); assert.equal(a.clone().endOf('day').hour(), 23, 'end of day should work on moments with utc offset'); assert.equal(a.clone().endOf('day').minute(), 59, 'end of day should work on moments with utc offset'); assert.equal(a.clone().endOf('hour').minute(), 59, 'end of hour should work on moments with utc offset'); }); test('reset offset with moment#utc', function (assert) { var a = moment.utc([2012]).utcOffset(-480); assert.equal(a.clone().hour(), 16, 'different utc offset should have different hour'); assert.equal(a.clone().utc().hour(), 0, 'calling moment#utc should reset the offset'); }); test('reset offset with moment#local', function (assert) { var a = moment([2012]).utcOffset(-480); assert.equal(a.clone().local().hour(), 0, 'calling moment#local should reset the offset'); }); test('toDate', function (assert) { var zoneA = new Date(), zoneB = moment(zoneA).utcOffset(-720).toDate(), zoneC = moment(zoneA).utcOffset(-360).toDate(), zoneD = moment(zoneA).utcOffset(690).toDate(); assert.equal(+zoneA, +zoneB, 'moment#toDate should output a date with the right unix timestamp'); assert.equal(+zoneA, +zoneC, 'moment#toDate should output a date with the right unix timestamp'); assert.equal(+zoneA, +zoneD, 'moment#toDate should output a date with the right unix timestamp'); }); test('same / before / after', function (assert) { var zoneA = moment().utc(), zoneB = moment(zoneA).utcOffset(-120), zoneC = moment(zoneA).utcOffset(120); assert.ok(zoneA.isSame(zoneB), 'two moments with different offsets should be the same'); assert.ok(zoneA.isSame(zoneC), 'two moments with different offsets should be the same'); assert.ok(zoneA.isSame(zoneB, 'hour'), 'two moments with different offsets should be the same hour'); assert.ok(zoneA.isSame(zoneC, 'hour'), 'two moments with different offsets should be the same hour'); zoneA.add(1, 'hour'); assert.ok(zoneA.isAfter(zoneB), 'isAfter should work with two moments with different offsets'); assert.ok(zoneA.isAfter(zoneC), 'isAfter should work with two moments with different offsets'); assert.ok(zoneA.isAfter(zoneB, 'hour'), 'isAfter:hour should work with two moments with different offsets'); assert.ok(zoneA.isAfter(zoneC, 'hour'), 'isAfter:hour should work with two moments with different offsets'); zoneA.subtract(2, 'hour'); assert.ok(zoneA.isBefore(zoneB), 'isBefore should work with two moments with different offsets'); assert.ok(zoneA.isBefore(zoneC), 'isBefore should work with two moments with different offsets'); assert.ok(zoneA.isBefore(zoneB, 'hour'), 'isBefore:hour should work with two moments with different offsets'); assert.ok(zoneA.isBefore(zoneC, 'hour'), 'isBefore:hour should work with two moments with different offsets'); }); test('add / subtract over dst', function (assert) { var oldOffset = moment.updateOffset, m = moment.utc([2000, 2, 31, 3]); moment.updateOffset = function (mom, keepTime) { if (mom.clone().utc().month() > 2) { mom.utcOffset(60, keepTime); } else { mom.utcOffset(0, keepTime); } }; assert.equal(m.hour(), 3, 'should start at 00:00'); m.add(24, 'hour'); assert.equal(m.hour(), 4, 'adding 24 hours should disregard dst'); m.subtract(24, 'hour'); assert.equal(m.hour(), 3, 'subtracting 24 hours should disregard dst'); m.add(1, 'day'); assert.equal(m.hour(), 3, 'adding 1 day should have the same hour'); m.subtract(1, 'day'); assert.equal(m.hour(), 3, 'subtracting 1 day should have the same hour'); m.add(1, 'month'); assert.equal(m.hour(), 3, 'adding 1 month should have the same hour'); m.subtract(1, 'month'); assert.equal(m.hour(), 3, 'subtracting 1 month should have the same hour'); moment.updateOffset = oldOffset; }); test('isDST', function (assert) { var oldOffset = moment.updateOffset; moment.updateOffset = function (mom, keepTime) { if (mom.month() > 2 && mom.month() < 9) { mom.utcOffset(60, keepTime); } else { mom.utcOffset(0, keepTime); } }; assert.ok(!moment().month(0).isDST(), 'Jan should not be summer dst'); assert.ok(moment().month(6).isDST(), 'Jul should be summer dst'); assert.ok(!moment().month(11).isDST(), 'Dec should not be summer dst'); moment.updateOffset = function (mom) { if (mom.month() > 2 && mom.month() < 9) { mom.utcOffset(0); } else { mom.utcOffset(60); } }; assert.ok(moment().month(0).isDST(), 'Jan should be winter dst'); assert.ok(!moment().month(6).isDST(), 'Jul should not be winter dst'); assert.ok(moment().month(11).isDST(), 'Dec should be winter dst'); moment.updateOffset = oldOffset; }); test('zone names', function (assert) { assert.equal(moment().zoneAbbr(), '', 'Local zone abbr should be empty'); assert.equal(moment().format('z'), '', 'Local zone formatted abbr should be empty'); assert.equal(moment().zoneName(), '', 'Local zone name should be empty'); assert.equal(moment().format('zz'), '', 'Local zone formatted name should be empty'); assert.equal(moment.utc().zoneAbbr(), 'UTC', 'UTC zone abbr should be UTC'); assert.equal(moment.utc().format('z'), 'UTC', 'UTC zone formatted abbr should be UTC'); assert.equal(moment.utc().zoneName(), 'Coordinated Universal Time', 'UTC zone abbr should be Coordinated Universal Time'); assert.equal(moment.utc().format('zz'), 'Coordinated Universal Time', 'UTC zone formatted abbr should be Coordinated Universal Time'); }); test('hours alignment with UTC', function (assert) { assert.equal(moment().utcOffset(-120).hasAlignedHourOffset(), true); assert.equal(moment().utcOffset(180).hasAlignedHourOffset(), true); assert.equal(moment().utcOffset(-90).hasAlignedHourOffset(), false); assert.equal(moment().utcOffset(90).hasAlignedHourOffset(), false); }); test('hours alignment with other zone', function (assert) { var m = moment().utcOffset(-120); assert.equal(m.hasAlignedHourOffset(moment().utcOffset(-180)), true); assert.equal(m.hasAlignedHourOffset(moment().utcOffset(180)), true); assert.equal(m.hasAlignedHourOffset(moment().utcOffset(-90)), false); assert.equal(m.hasAlignedHourOffset(moment().utcOffset(90)), false); m = moment().utcOffset(-90); assert.equal(m.hasAlignedHourOffset(moment().utcOffset(-180)), false); assert.equal(m.hasAlignedHourOffset(moment().utcOffset(180)), false); assert.equal(m.hasAlignedHourOffset(moment().utcOffset(-30)), true); assert.equal(m.hasAlignedHourOffset(moment().utcOffset(30)), true); m = moment().utcOffset(60); assert.equal(m.hasAlignedHourOffset(moment().utcOffset(-180)), true); assert.equal(m.hasAlignedHourOffset(moment().utcOffset(180)), true); assert.equal(m.hasAlignedHourOffset(moment().utcOffset(-90)), false); assert.equal(m.hasAlignedHourOffset(moment().utcOffset(90)), false); m = moment().utcOffset(-25); assert.equal(m.hasAlignedHourOffset(moment().utcOffset(35)), true); assert.equal(m.hasAlignedHourOffset(moment().utcOffset(-85)), true); assert.equal(m.hasAlignedHourOffset(moment().utcOffset(-35)), false); assert.equal(m.hasAlignedHourOffset(moment().utcOffset(85)), false); }); test('parse zone', function (assert) { var m = moment('2013-01-01T00:00:00-13:00').parseZone(); assert.equal(m.utcOffset(), -13 * 60); assert.equal(m.hours(), 0); }); test('parse zone static', function (assert) { var m = moment.parseZone('2013-01-01T00:00:00-13:00'); assert.equal(m.utcOffset(), -13 * 60); assert.equal(m.hours(), 0); }); test('parse zone with more arguments', function (assert) { var m; m = moment.parseZone('2013 01 01 05 -13:00', 'YYYY MM DD HH ZZ'); assert.equal(m.format(), '2013-01-01T05:00:00-13:00', 'accept input and format'); m = moment.parseZone('2013-01-01-13:00', 'YYYY MM DD ZZ', true); assert.equal(m.isValid(), false, 'accept input, format and strict flag'); m = moment.parseZone('2013-01-01-13:00', ['DD MM YYYY ZZ', 'YYYY MM DD ZZ']); assert.equal(m.format(), '2013-01-01T00:00:00-13:00', 'accept input and array of formats'); }); test('parse zone with a timezone from the format string', function (assert) { var m = moment('11-12-2013 -0400 +1100', 'DD-MM-YYYY ZZ #####').parseZone(); assert.equal(m.utcOffset(), -4 * 60); }); test('parse zone without a timezone included in the format string', function (assert) { var m = moment('11-12-2013 -0400 +1100', 'DD-MM-YYYY').parseZone(); assert.equal(m.utcOffset(), 11 * 60); }); test('timezone format', function (assert) { assert.equal(moment().utcOffset(60).format('ZZ'), '+0100', '-60 -> +0100'); assert.equal(moment().utcOffset(90).format('ZZ'), '+0130', '-90 -> +0130'); assert.equal(moment().utcOffset(120).format('ZZ'), '+0200', '-120 -> +0200'); assert.equal(moment().utcOffset(-60).format('ZZ'), '-0100', '+60 -> -0100'); assert.equal(moment().utcOffset(-90).format('ZZ'), '-0130', '+90 -> -0130'); assert.equal(moment().utcOffset(-120).format('ZZ'), '-0200', '+120 -> -0200'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('week year'); test('iso week year', function (assert) { // Some examples taken from path_to_url assert.equal(moment([2005, 0, 1]).isoWeekYear(), 2004); assert.equal(moment([2005, 0, 2]).isoWeekYear(), 2004); assert.equal(moment([2005, 0, 3]).isoWeekYear(), 2005); assert.equal(moment([2005, 11, 31]).isoWeekYear(), 2005); assert.equal(moment([2006, 0, 1]).isoWeekYear(), 2005); assert.equal(moment([2006, 0, 2]).isoWeekYear(), 2006); assert.equal(moment([2007, 0, 1]).isoWeekYear(), 2007); assert.equal(moment([2007, 11, 30]).isoWeekYear(), 2007); assert.equal(moment([2007, 11, 31]).isoWeekYear(), 2008); assert.equal(moment([2008, 0, 1]).isoWeekYear(), 2008); assert.equal(moment([2008, 11, 28]).isoWeekYear(), 2008); assert.equal(moment([2008, 11, 29]).isoWeekYear(), 2009); assert.equal(moment([2008, 11, 30]).isoWeekYear(), 2009); assert.equal(moment([2008, 11, 31]).isoWeekYear(), 2009); assert.equal(moment([2009, 0, 1]).isoWeekYear(), 2009); assert.equal(moment([2010, 0, 1]).isoWeekYear(), 2009); assert.equal(moment([2010, 0, 2]).isoWeekYear(), 2009); assert.equal(moment([2010, 0, 3]).isoWeekYear(), 2009); assert.equal(moment([2010, 0, 4]).isoWeekYear(), 2010); }); test('week year', function (assert) { // Some examples taken from path_to_url moment.locale('dow: 1,doy: 4', {week: {dow: 1, doy: 4}}); // like iso assert.equal(moment([2005, 0, 1]).weekYear(), 2004); assert.equal(moment([2005, 0, 2]).weekYear(), 2004); assert.equal(moment([2005, 0, 3]).weekYear(), 2005); assert.equal(moment([2005, 11, 31]).weekYear(), 2005); assert.equal(moment([2006, 0, 1]).weekYear(), 2005); assert.equal(moment([2006, 0, 2]).weekYear(), 2006); assert.equal(moment([2007, 0, 1]).weekYear(), 2007); assert.equal(moment([2007, 11, 30]).weekYear(), 2007); assert.equal(moment([2007, 11, 31]).weekYear(), 2008); assert.equal(moment([2008, 0, 1]).weekYear(), 2008); assert.equal(moment([2008, 11, 28]).weekYear(), 2008); assert.equal(moment([2008, 11, 29]).weekYear(), 2009); assert.equal(moment([2008, 11, 30]).weekYear(), 2009); assert.equal(moment([2008, 11, 31]).weekYear(), 2009); assert.equal(moment([2009, 0, 1]).weekYear(), 2009); assert.equal(moment([2010, 0, 1]).weekYear(), 2009); assert.equal(moment([2010, 0, 2]).weekYear(), 2009); assert.equal(moment([2010, 0, 3]).weekYear(), 2009); assert.equal(moment([2010, 0, 4]).weekYear(), 2010); moment.locale('dow: 1,doy: 7', {week: {dow: 1, doy: 7}}); assert.equal(moment([2004, 11, 26]).weekYear(), 2004); assert.equal(moment([2004, 11, 27]).weekYear(), 2005); assert.equal(moment([2005, 11, 25]).weekYear(), 2005); assert.equal(moment([2005, 11, 26]).weekYear(), 2006); assert.equal(moment([2006, 11, 31]).weekYear(), 2006); assert.equal(moment([2007, 0, 1]).weekYear(), 2007); assert.equal(moment([2007, 11, 30]).weekYear(), 2007); assert.equal(moment([2007, 11, 31]).weekYear(), 2008); assert.equal(moment([2008, 11, 28]).weekYear(), 2008); assert.equal(moment([2008, 11, 29]).weekYear(), 2009); assert.equal(moment([2009, 11, 27]).weekYear(), 2009); assert.equal(moment([2009, 11, 28]).weekYear(), 2010); }); // Verifies that the week number, week day computation is correct for all dow, doy combinations test('week year roundtrip', function (assert) { var dow, doy, wd, m, localeName; for (dow = 0; dow < 7; ++dow) { for (doy = dow; doy < dow + 7; ++doy) { for (wd = 0; wd < 7; ++wd) { localeName = 'dow: ' + dow + ', doy: ' + doy; moment.locale(localeName, {week: {dow: dow, doy: doy}}); // We use the 10th week as the 1st one can spill to the previous year m = moment('2015 10 ' + wd, 'gggg w d', true); assert.equal(m.format('gggg w d'), '2015 10 ' + wd, 'dow: ' + dow + ' doy: ' + doy + ' wd: ' + wd); m = moment('2015 10 ' + wd, 'gggg w e', true); assert.equal(m.format('gggg w e'), '2015 10 ' + wd, 'dow: ' + dow + ' doy: ' + doy + ' wd: ' + wd); moment.defineLocale(localeName, null); } } } }); test('week numbers 2012/2013', function (assert) { moment.locale('dow: 6, doy: 12', {week: {dow: 6, doy: 12}}); assert.equal(52, moment('2012-12-28', 'YYYY-MM-DD').week(), '2012-12-28 is week 52'); // 51 -- should be 52? assert.equal(1, moment('2012-12-29', 'YYYY-MM-DD').week(), '2012-12-29 is week 1'); // 52 -- should be 1 assert.equal(1, moment('2013-01-01', 'YYYY-MM-DD').week(), '2013-01-01 is week 1'); // 52 -- should be 1 assert.equal(2, moment('2013-01-08', 'YYYY-MM-DD').week(), '2013-01-08 is week 2'); // 53 -- should be 2 assert.equal(2, moment('2013-01-11', 'YYYY-MM-DD').week(), '2013-01-11 is week 2'); // 53 -- should be 2 assert.equal(3, moment('2013-01-12', 'YYYY-MM-DD').week(), '2013-01-12 is week 3'); // 1 -- should be 3 assert.equal(52, moment('2012-01-01', 'YYYY-MM-DD').weeksInYear(), 'weeks in 2012 are 52'); // 52 moment.defineLocale('dow: 6, doy: 12', null); }); test('weeks numbers dow:1 doy:4', function (assert) { moment.locale('dow: 1, doy: 4', {week: {dow: 1, doy: 4}}); assert.equal(moment([2012, 0, 1]).week(), 52, 'Jan 1 2012 should be week 52'); assert.equal(moment([2012, 0, 2]).week(), 1, 'Jan 2 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).week(), 1, 'Jan 8 2012 should be week 1'); assert.equal(moment([2012, 0, 9]).week(), 2, 'Jan 9 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).week(), 2, 'Jan 15 2012 should be week 2'); assert.equal(moment([2007, 0, 1]).week(), 1, 'Jan 1 2007 should be week 1'); assert.equal(moment([2007, 0, 7]).week(), 1, 'Jan 7 2007 should be week 1'); assert.equal(moment([2007, 0, 8]).week(), 2, 'Jan 8 2007 should be week 2'); assert.equal(moment([2007, 0, 14]).week(), 2, 'Jan 14 2007 should be week 2'); assert.equal(moment([2007, 0, 15]).week(), 3, 'Jan 15 2007 should be week 3'); assert.equal(moment([2007, 11, 31]).week(), 1, 'Dec 31 2007 should be week 1'); assert.equal(moment([2008, 0, 1]).week(), 1, 'Jan 1 2008 should be week 1'); assert.equal(moment([2008, 0, 6]).week(), 1, 'Jan 6 2008 should be week 1'); assert.equal(moment([2008, 0, 7]).week(), 2, 'Jan 7 2008 should be week 2'); assert.equal(moment([2008, 0, 13]).week(), 2, 'Jan 13 2008 should be week 2'); assert.equal(moment([2008, 0, 14]).week(), 3, 'Jan 14 2008 should be week 3'); assert.equal(moment([2002, 11, 30]).week(), 1, 'Dec 30 2002 should be week 1'); assert.equal(moment([2003, 0, 1]).week(), 1, 'Jan 1 2003 should be week 1'); assert.equal(moment([2003, 0, 5]).week(), 1, 'Jan 5 2003 should be week 1'); assert.equal(moment([2003, 0, 6]).week(), 2, 'Jan 6 2003 should be week 2'); assert.equal(moment([2003, 0, 12]).week(), 2, 'Jan 12 2003 should be week 2'); assert.equal(moment([2003, 0, 13]).week(), 3, 'Jan 13 2003 should be week 3'); assert.equal(moment([2008, 11, 29]).week(), 1, 'Dec 29 2008 should be week 1'); assert.equal(moment([2009, 0, 1]).week(), 1, 'Jan 1 2009 should be week 1'); assert.equal(moment([2009, 0, 4]).week(), 1, 'Jan 4 2009 should be week 1'); assert.equal(moment([2009, 0, 5]).week(), 2, 'Jan 5 2009 should be week 2'); assert.equal(moment([2009, 0, 11]).week(), 2, 'Jan 11 2009 should be week 2'); assert.equal(moment([2009, 0, 13]).week(), 3, 'Jan 12 2009 should be week 3'); assert.equal(moment([2009, 11, 28]).week(), 53, 'Dec 28 2009 should be week 53'); assert.equal(moment([2010, 0, 1]).week(), 53, 'Jan 1 2010 should be week 53'); assert.equal(moment([2010, 0, 3]).week(), 53, 'Jan 3 2010 should be week 53'); assert.equal(moment([2010, 0, 4]).week(), 1, 'Jan 4 2010 should be week 1'); assert.equal(moment([2010, 0, 10]).week(), 1, 'Jan 10 2010 should be week 1'); assert.equal(moment([2010, 0, 11]).week(), 2, 'Jan 11 2010 should be week 2'); assert.equal(moment([2010, 11, 27]).week(), 52, 'Dec 27 2010 should be week 52'); assert.equal(moment([2011, 0, 1]).week(), 52, 'Jan 1 2011 should be week 52'); assert.equal(moment([2011, 0, 2]).week(), 52, 'Jan 2 2011 should be week 52'); assert.equal(moment([2011, 0, 3]).week(), 1, 'Jan 3 2011 should be week 1'); assert.equal(moment([2011, 0, 9]).week(), 1, 'Jan 9 2011 should be week 1'); assert.equal(moment([2011, 0, 10]).week(), 2, 'Jan 10 2011 should be week 2'); moment.defineLocale('dow: 1, doy: 4', null); }); test('weeks numbers dow:6 doy:12', function (assert) { moment.locale('dow: 6, doy: 12', {week: {dow: 6, doy: 12}}); assert.equal(moment([2011, 11, 31]).week(), 1, 'Dec 31 2011 should be week 1'); assert.equal(moment([2012, 0, 6]).week(), 1, 'Jan 6 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).week(), 2, 'Jan 7 2012 should be week 2'); assert.equal(moment([2012, 0, 13]).week(), 2, 'Jan 13 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).week(), 3, 'Jan 14 2012 should be week 3'); assert.equal(moment([2006, 11, 30]).week(), 1, 'Dec 30 2006 should be week 1'); assert.equal(moment([2007, 0, 5]).week(), 1, 'Jan 5 2007 should be week 1'); assert.equal(moment([2007, 0, 6]).week(), 2, 'Jan 6 2007 should be week 2'); assert.equal(moment([2007, 0, 12]).week(), 2, 'Jan 12 2007 should be week 2'); assert.equal(moment([2007, 0, 13]).week(), 3, 'Jan 13 2007 should be week 3'); assert.equal(moment([2007, 11, 29]).week(), 1, 'Dec 29 2007 should be week 1'); assert.equal(moment([2008, 0, 1]).week(), 1, 'Jan 1 2008 should be week 1'); assert.equal(moment([2008, 0, 4]).week(), 1, 'Jan 4 2008 should be week 1'); assert.equal(moment([2008, 0, 5]).week(), 2, 'Jan 5 2008 should be week 2'); assert.equal(moment([2008, 0, 11]).week(), 2, 'Jan 11 2008 should be week 2'); assert.equal(moment([2008, 0, 12]).week(), 3, 'Jan 12 2008 should be week 3'); assert.equal(moment([2002, 11, 28]).week(), 1, 'Dec 28 2002 should be week 1'); assert.equal(moment([2003, 0, 1]).week(), 1, 'Jan 1 2003 should be week 1'); assert.equal(moment([2003, 0, 3]).week(), 1, 'Jan 3 2003 should be week 1'); assert.equal(moment([2003, 0, 4]).week(), 2, 'Jan 4 2003 should be week 2'); assert.equal(moment([2003, 0, 10]).week(), 2, 'Jan 10 2003 should be week 2'); assert.equal(moment([2003, 0, 11]).week(), 3, 'Jan 11 2003 should be week 3'); assert.equal(moment([2008, 11, 27]).week(), 1, 'Dec 27 2008 should be week 1'); assert.equal(moment([2009, 0, 1]).week(), 1, 'Jan 1 2009 should be week 1'); assert.equal(moment([2009, 0, 2]).week(), 1, 'Jan 2 2009 should be week 1'); assert.equal(moment([2009, 0, 3]).week(), 2, 'Jan 3 2009 should be week 2'); assert.equal(moment([2009, 0, 9]).week(), 2, 'Jan 9 2009 should be week 2'); assert.equal(moment([2009, 0, 10]).week(), 3, 'Jan 10 2009 should be week 3'); assert.equal(moment([2009, 11, 26]).week(), 1, 'Dec 26 2009 should be week 1'); assert.equal(moment([2010, 0, 1]).week(), 1, 'Jan 1 2010 should be week 1'); assert.equal(moment([2010, 0, 2]).week(), 2, 'Jan 2 2010 should be week 2'); assert.equal(moment([2010, 0, 8]).week(), 2, 'Jan 8 2010 should be week 2'); assert.equal(moment([2010, 0, 9]).week(), 3, 'Jan 9 2010 should be week 3'); assert.equal(moment([2011, 0, 1]).week(), 1, 'Jan 1 2011 should be week 1'); assert.equal(moment([2011, 0, 7]).week(), 1, 'Jan 7 2011 should be week 1'); assert.equal(moment([2011, 0, 8]).week(), 2, 'Jan 8 2011 should be week 2'); assert.equal(moment([2011, 0, 14]).week(), 2, 'Jan 14 2011 should be week 2'); assert.equal(moment([2011, 0, 15]).week(), 3, 'Jan 15 2011 should be week 3'); moment.defineLocale('dow: 6, doy: 12', null); }); test('weeks numbers dow:1 doy:7', function (assert) { moment.locale('dow: 1, doy: 7', {week: {dow: 1, doy: 7}}); assert.equal(moment([2011, 11, 26]).week(), 1, 'Dec 26 2011 should be week 1'); assert.equal(moment([2012, 0, 1]).week(), 1, 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 2]).week(), 2, 'Jan 2 2012 should be week 2'); assert.equal(moment([2012, 0, 8]).week(), 2, 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 9]).week(), 3, 'Jan 9 2012 should be week 3'); assert.equal(moment([2007, 0, 1]).week(), 1, 'Jan 1 2007 should be week 1'); assert.equal(moment([2007, 0, 7]).week(), 1, 'Jan 7 2007 should be week 1'); assert.equal(moment([2007, 0, 8]).week(), 2, 'Jan 8 2007 should be week 2'); assert.equal(moment([2007, 0, 14]).week(), 2, 'Jan 14 2007 should be week 2'); assert.equal(moment([2007, 0, 15]).week(), 3, 'Jan 15 2007 should be week 3'); assert.equal(moment([2007, 11, 31]).week(), 1, 'Dec 31 2007 should be week 1'); assert.equal(moment([2008, 0, 1]).week(), 1, 'Jan 1 2008 should be week 1'); assert.equal(moment([2008, 0, 6]).week(), 1, 'Jan 6 2008 should be week 1'); assert.equal(moment([2008, 0, 7]).week(), 2, 'Jan 7 2008 should be week 2'); assert.equal(moment([2008, 0, 13]).week(), 2, 'Jan 13 2008 should be week 2'); assert.equal(moment([2008, 0, 14]).week(), 3, 'Jan 14 2008 should be week 3'); assert.equal(moment([2002, 11, 30]).week(), 1, 'Dec 30 2002 should be week 1'); assert.equal(moment([2003, 0, 1]).week(), 1, 'Jan 1 2003 should be week 1'); assert.equal(moment([2003, 0, 5]).week(), 1, 'Jan 5 2003 should be week 1'); assert.equal(moment([2003, 0, 6]).week(), 2, 'Jan 6 2003 should be week 2'); assert.equal(moment([2003, 0, 12]).week(), 2, 'Jan 12 2003 should be week 2'); assert.equal(moment([2003, 0, 13]).week(), 3, 'Jan 13 2003 should be week 3'); assert.equal(moment([2008, 11, 29]).week(), 1, 'Dec 29 2008 should be week 1'); assert.equal(moment([2009, 0, 1]).week(), 1, 'Jan 1 2009 should be week 1'); assert.equal(moment([2009, 0, 4]).week(), 1, 'Jan 4 2009 should be week 1'); assert.equal(moment([2009, 0, 5]).week(), 2, 'Jan 5 2009 should be week 2'); assert.equal(moment([2009, 0, 11]).week(), 2, 'Jan 11 2009 should be week 2'); assert.equal(moment([2009, 0, 12]).week(), 3, 'Jan 12 2009 should be week 3'); assert.equal(moment([2009, 11, 28]).week(), 1, 'Dec 28 2009 should be week 1'); assert.equal(moment([2010, 0, 1]).week(), 1, 'Jan 1 2010 should be week 1'); assert.equal(moment([2010, 0, 3]).week(), 1, 'Jan 3 2010 should be week 1'); assert.equal(moment([2010, 0, 4]).week(), 2, 'Jan 4 2010 should be week 2'); assert.equal(moment([2010, 0, 10]).week(), 2, 'Jan 10 2010 should be week 2'); assert.equal(moment([2010, 0, 11]).week(), 3, 'Jan 11 2010 should be week 3'); assert.equal(moment([2010, 11, 27]).week(), 1, 'Dec 27 2010 should be week 1'); assert.equal(moment([2011, 0, 1]).week(), 1, 'Jan 1 2011 should be week 1'); assert.equal(moment([2011, 0, 2]).week(), 1, 'Jan 2 2011 should be week 1'); assert.equal(moment([2011, 0, 3]).week(), 2, 'Jan 3 2011 should be week 2'); assert.equal(moment([2011, 0, 9]).week(), 2, 'Jan 9 2011 should be week 2'); assert.equal(moment([2011, 0, 10]).week(), 3, 'Jan 10 2011 should be week 3'); moment.defineLocale('dow: 1, doy: 7', null); }); test('weeks numbers dow:0 doy:6', function (assert) { moment.locale('dow: 0, doy: 6', {week: {dow: 0, doy: 6}}); assert.equal(moment([2012, 0, 1]).week(), 1, 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).week(), 1, 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).week(), 2, 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).week(), 2, 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).week(), 3, 'Jan 15 2012 should be week 3'); assert.equal(moment([2006, 11, 31]).week(), 1, 'Dec 31 2006 should be week 1'); assert.equal(moment([2007, 0, 1]).week(), 1, 'Jan 1 2007 should be week 1'); assert.equal(moment([2007, 0, 6]).week(), 1, 'Jan 6 2007 should be week 1'); assert.equal(moment([2007, 0, 7]).week(), 2, 'Jan 7 2007 should be week 2'); assert.equal(moment([2007, 0, 13]).week(), 2, 'Jan 13 2007 should be week 2'); assert.equal(moment([2007, 0, 14]).week(), 3, 'Jan 14 2007 should be week 3'); assert.equal(moment([2007, 11, 29]).week(), 52, 'Dec 29 2007 should be week 52'); assert.equal(moment([2008, 0, 1]).week(), 1, 'Jan 1 2008 should be week 1'); assert.equal(moment([2008, 0, 5]).week(), 1, 'Jan 5 2008 should be week 1'); assert.equal(moment([2008, 0, 6]).week(), 2, 'Jan 6 2008 should be week 2'); assert.equal(moment([2008, 0, 12]).week(), 2, 'Jan 12 2008 should be week 2'); assert.equal(moment([2008, 0, 13]).week(), 3, 'Jan 13 2008 should be week 3'); assert.equal(moment([2002, 11, 29]).week(), 1, 'Dec 29 2002 should be week 1'); assert.equal(moment([2003, 0, 1]).week(), 1, 'Jan 1 2003 should be week 1'); assert.equal(moment([2003, 0, 4]).week(), 1, 'Jan 4 2003 should be week 1'); assert.equal(moment([2003, 0, 5]).week(), 2, 'Jan 5 2003 should be week 2'); assert.equal(moment([2003, 0, 11]).week(), 2, 'Jan 11 2003 should be week 2'); assert.equal(moment([2003, 0, 12]).week(), 3, 'Jan 12 2003 should be week 3'); assert.equal(moment([2008, 11, 28]).week(), 1, 'Dec 28 2008 should be week 1'); assert.equal(moment([2009, 0, 1]).week(), 1, 'Jan 1 2009 should be week 1'); assert.equal(moment([2009, 0, 3]).week(), 1, 'Jan 3 2009 should be week 1'); assert.equal(moment([2009, 0, 4]).week(), 2, 'Jan 4 2009 should be week 2'); assert.equal(moment([2009, 0, 10]).week(), 2, 'Jan 10 2009 should be week 2'); assert.equal(moment([2009, 0, 11]).week(), 3, 'Jan 11 2009 should be week 3'); assert.equal(moment([2009, 11, 27]).week(), 1, 'Dec 27 2009 should be week 1'); assert.equal(moment([2010, 0, 1]).week(), 1, 'Jan 1 2010 should be week 1'); assert.equal(moment([2010, 0, 2]).week(), 1, 'Jan 2 2010 should be week 1'); assert.equal(moment([2010, 0, 3]).week(), 2, 'Jan 3 2010 should be week 2'); assert.equal(moment([2010, 0, 9]).week(), 2, 'Jan 9 2010 should be week 2'); assert.equal(moment([2010, 0, 10]).week(), 3, 'Jan 10 2010 should be week 3'); assert.equal(moment([2010, 11, 26]).week(), 1, 'Dec 26 2010 should be week 1'); assert.equal(moment([2011, 0, 1]).week(), 1, 'Jan 1 2011 should be week 1'); assert.equal(moment([2011, 0, 2]).week(), 2, 'Jan 2 2011 should be week 2'); assert.equal(moment([2011, 0, 8]).week(), 2, 'Jan 8 2011 should be week 2'); assert.equal(moment([2011, 0, 9]).week(), 3, 'Jan 9 2011 should be week 3'); moment.defineLocale('dow: 0, doy: 6', null); }); test('week year overflows', function (assert) { assert.equal('2005-01-01', moment.utc('2004-W53-6', moment.ISO_8601, true).format('YYYY-MM-DD'), '2004-W53-6 is 1st Jan 2005'); assert.equal('2007-12-31', moment.utc('2008-W01-1', moment.ISO_8601, true).format('YYYY-MM-DD'), '2008-W01-1 is 31st Dec 2007'); }); test('weeks overflow', function (assert) { assert.equal(7, moment.utc('2004-W54-1', moment.ISO_8601, true).parsingFlags().overflow, '2004 has only 53 weeks'); assert.equal(7, moment.utc('2004-W00-1', moment.ISO_8601, true).parsingFlags().overflow, 'there is no 0th week'); }); test('weekday overflow', function (assert) { assert.equal(8, moment.utc('2004-W30-0', moment.ISO_8601, true).parsingFlags().overflow, 'there is no 0 iso weekday'); assert.equal(8, moment.utc('2004-W30-8', moment.ISO_8601, true).parsingFlags().overflow, 'there is no 8 iso weekday'); assert.equal(8, moment.utc('2004-w30-7', 'gggg-[w]ww-e', true).parsingFlags().overflow, 'there is no 7 \'e\' weekday'); assert.equal(8, moment.utc('2004-w30-7', 'gggg-[w]ww-d', true).parsingFlags().overflow, 'there is no 7 \'d\' weekday'); }); test('week year setter works', function (assert) { for (var year = 2000; year <= 2020; year += 1) { assert.equal(moment.utc('2012-12-31T00:00:00.000Z').isoWeekYear(year).isoWeekYear(), year, 'setting iso-week-year to ' + year); assert.equal(moment.utc('2012-12-31T00:00:00.000Z').weekYear(year).weekYear(), year, 'setting week-year to ' + year); } assert.equal(moment.utc('2004-W53-1', moment.ISO_8601, true).isoWeekYear(2013).format('GGGG-[W]WW-E'), '2013-W52-1', '2004-W53-1 to 2013'); assert.equal(moment.utc('2004-W53-1', moment.ISO_8601, true).isoWeekYear(2020).format('GGGG-[W]WW-E'), '2020-W53-1', '2004-W53-1 to 2020'); assert.equal(moment.utc('2005-W52-1', moment.ISO_8601, true).isoWeekYear(2004).format('GGGG-[W]WW-E'), '2004-W52-1', '2005-W52-1 to 2004'); assert.equal(moment.utc('2013-W30-4', moment.ISO_8601, true).isoWeekYear(2015).format('GGGG-[W]WW-E'), '2015-W30-4', '2013-W30-4 to 2015'); assert.equal(moment.utc('2005-w53-0', 'gggg-[w]ww-e', true).weekYear(2013).format('gggg-[w]ww-e'), '2013-w52-0', '2005-w53-0 to 2013'); assert.equal(moment.utc('2005-w53-0', 'gggg-[w]ww-e', true).weekYear(2016).format('gggg-[w]ww-e'), '2016-w53-0', '2005-w53-0 to 2016'); assert.equal(moment.utc('2004-w52-0', 'gggg-[w]ww-e', true).weekYear(2005).format('gggg-[w]ww-e'), '2005-w52-0', '2004-w52-0 to 2005'); assert.equal(moment.utc('2013-w30-4', 'gggg-[w]ww-e', true).weekYear(2015).format('gggg-[w]ww-e'), '2015-w30-4', '2013-w30-4 to 2015'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('week day'); test('iso weekday', function (assert) { var i; for (i = 0; i < 7; ++i) { moment.locale('dow:' + i + ',doy: 6', {week: {dow: i, doy: 6}}); assert.equal(moment([1985, 1, 4]).isoWeekday(), 1, 'Feb 4 1985 is Monday -- 1st day'); assert.equal(moment([2029, 8, 18]).isoWeekday(), 2, 'Sep 18 2029 is Tuesday -- 2nd day'); assert.equal(moment([2013, 3, 24]).isoWeekday(), 3, 'Apr 24 2013 is Wednesday -- 3rd day'); assert.equal(moment([2015, 2, 5]).isoWeekday(), 4, 'Mar 5 2015 is Thursday -- 4th day'); assert.equal(moment([1970, 0, 2]).isoWeekday(), 5, 'Jan 2 1970 is Friday -- 5th day'); assert.equal(moment([2001, 4, 12]).isoWeekday(), 6, 'May 12 2001 is Saturday -- 6th day'); assert.equal(moment([2000, 0, 2]).isoWeekday(), 7, 'Jan 2 2000 is Sunday -- 7th day'); } }); test('iso weekday setter', function (assert) { var a = moment([2011, 0, 10]); assert.equal(moment(a).isoWeekday(1).date(), 10, 'set from mon to mon'); assert.equal(moment(a).isoWeekday(4).date(), 13, 'set from mon to thu'); assert.equal(moment(a).isoWeekday(7).date(), 16, 'set from mon to sun'); assert.equal(moment(a).isoWeekday(-6).date(), 3, 'set from mon to last mon'); assert.equal(moment(a).isoWeekday(-3).date(), 6, 'set from mon to last thu'); assert.equal(moment(a).isoWeekday(0).date(), 9, 'set from mon to last sun'); assert.equal(moment(a).isoWeekday(8).date(), 17, 'set from mon to next mon'); assert.equal(moment(a).isoWeekday(11).date(), 20, 'set from mon to next thu'); assert.equal(moment(a).isoWeekday(14).date(), 23, 'set from mon to next sun'); a = moment([2011, 0, 13]); assert.equal(moment(a).isoWeekday(1).date(), 10, 'set from thu to mon'); assert.equal(moment(a).isoWeekday(4).date(), 13, 'set from thu to thu'); assert.equal(moment(a).isoWeekday(7).date(), 16, 'set from thu to sun'); assert.equal(moment(a).isoWeekday(-6).date(), 3, 'set from thu to last mon'); assert.equal(moment(a).isoWeekday(-3).date(), 6, 'set from thu to last thu'); assert.equal(moment(a).isoWeekday(0).date(), 9, 'set from thu to last sun'); assert.equal(moment(a).isoWeekday(8).date(), 17, 'set from thu to next mon'); assert.equal(moment(a).isoWeekday(11).date(), 20, 'set from thu to next thu'); assert.equal(moment(a).isoWeekday(14).date(), 23, 'set from thu to next sun'); a = moment([2011, 0, 16]); assert.equal(moment(a).isoWeekday(1).date(), 10, 'set from sun to mon'); assert.equal(moment(a).isoWeekday(4).date(), 13, 'set from sun to thu'); assert.equal(moment(a).isoWeekday(7).date(), 16, 'set from sun to sun'); assert.equal(moment(a).isoWeekday(-6).date(), 3, 'set from sun to last mon'); assert.equal(moment(a).isoWeekday(-3).date(), 6, 'set from sun to last thu'); assert.equal(moment(a).isoWeekday(0).date(), 9, 'set from sun to last sun'); assert.equal(moment(a).isoWeekday(8).date(), 17, 'set from sun to next mon'); assert.equal(moment(a).isoWeekday(11).date(), 20, 'set from sun to next thu'); assert.equal(moment(a).isoWeekday(14).date(), 23, 'set from sun to next sun'); }); test('weekday first day of week Sunday (dow 0)', function (assert) { moment.locale('dow: 0,doy: 6', {week: {dow: 0, doy: 6}}); assert.equal(moment([1985, 1, 3]).weekday(), 0, 'Feb 3 1985 is Sunday -- 0th day'); assert.equal(moment([2029, 8, 17]).weekday(), 1, 'Sep 17 2029 is Monday -- 1st day'); assert.equal(moment([2013, 3, 23]).weekday(), 2, 'Apr 23 2013 is Tuesday -- 2nd day'); assert.equal(moment([2015, 2, 4]).weekday(), 3, 'Mar 4 2015 is Wednesday -- 3nd day'); assert.equal(moment([1970, 0, 1]).weekday(), 4, 'Jan 1 1970 is Thursday -- 4th day'); assert.equal(moment([2001, 4, 11]).weekday(), 5, 'May 11 2001 is Friday -- 5th day'); assert.equal(moment([2000, 0, 1]).weekday(), 6, 'Jan 1 2000 is Saturday -- 6th day'); }); test('weekday first day of week Monday (dow 1)', function (assert) { moment.locale('dow: 1,doy: 6', {week: {dow: 1, doy: 6}}); assert.equal(moment([1985, 1, 4]).weekday(), 0, 'Feb 4 1985 is Monday -- 0th day'); assert.equal(moment([2029, 8, 18]).weekday(), 1, 'Sep 18 2029 is Tuesday -- 1st day'); assert.equal(moment([2013, 3, 24]).weekday(), 2, 'Apr 24 2013 is Wednesday -- 2nd day'); assert.equal(moment([2015, 2, 5]).weekday(), 3, 'Mar 5 2015 is Thursday -- 3nd day'); assert.equal(moment([1970, 0, 2]).weekday(), 4, 'Jan 2 1970 is Friday -- 4th day'); assert.equal(moment([2001, 4, 12]).weekday(), 5, 'May 12 2001 is Saturday -- 5th day'); assert.equal(moment([2000, 0, 2]).weekday(), 6, 'Jan 2 2000 is Sunday -- 6th day'); }); test('weekday first day of week Tuesday (dow 2)', function (assert) { moment.locale('dow: 2,doy: 6', {week: {dow: 2, doy: 6}}); assert.equal(moment([1985, 1, 5]).weekday(), 0, 'Feb 5 1985 is Tuesday -- 0th day'); assert.equal(moment([2029, 8, 19]).weekday(), 1, 'Sep 19 2029 is Wednesday -- 1st day'); assert.equal(moment([2013, 3, 25]).weekday(), 2, 'Apr 25 2013 is Thursday -- 2nd day'); assert.equal(moment([2015, 2, 6]).weekday(), 3, 'Mar 6 2015 is Friday -- 3nd day'); assert.equal(moment([1970, 0, 3]).weekday(), 4, 'Jan 3 1970 is Staturday -- 4th day'); assert.equal(moment([2001, 4, 13]).weekday(), 5, 'May 13 2001 is Sunday -- 5th day'); assert.equal(moment([2000, 0, 3]).weekday(), 6, 'Jan 3 2000 is Monday -- 6th day'); }); test('weekday first day of week Wednesday (dow 3)', function (assert) { moment.locale('dow: 3,doy: 6', {week: {dow: 3, doy: 6}}); assert.equal(moment([1985, 1, 6]).weekday(), 0, 'Feb 6 1985 is Wednesday -- 0th day'); assert.equal(moment([2029, 8, 20]).weekday(), 1, 'Sep 20 2029 is Thursday -- 1st day'); assert.equal(moment([2013, 3, 26]).weekday(), 2, 'Apr 26 2013 is Friday -- 2nd day'); assert.equal(moment([2015, 2, 7]).weekday(), 3, 'Mar 7 2015 is Saturday -- 3nd day'); assert.equal(moment([1970, 0, 4]).weekday(), 4, 'Jan 4 1970 is Sunday -- 4th day'); assert.equal(moment([2001, 4, 14]).weekday(), 5, 'May 14 2001 is Monday -- 5th day'); assert.equal(moment([2000, 0, 4]).weekday(), 6, 'Jan 4 2000 is Tuesday -- 6th day'); moment.locale('dow:3,doy:6', null); }); test('weekday first day of week Thursday (dow 4)', function (assert) { moment.locale('dow: 4,doy: 6', {week: {dow: 4, doy: 6}}); assert.equal(moment([1985, 1, 7]).weekday(), 0, 'Feb 7 1985 is Thursday -- 0th day'); assert.equal(moment([2029, 8, 21]).weekday(), 1, 'Sep 21 2029 is Friday -- 1st day'); assert.equal(moment([2013, 3, 27]).weekday(), 2, 'Apr 27 2013 is Saturday -- 2nd day'); assert.equal(moment([2015, 2, 8]).weekday(), 3, 'Mar 8 2015 is Sunday -- 3nd day'); assert.equal(moment([1970, 0, 5]).weekday(), 4, 'Jan 5 1970 is Monday -- 4th day'); assert.equal(moment([2001, 4, 15]).weekday(), 5, 'May 15 2001 is Tuesday -- 5th day'); assert.equal(moment([2000, 0, 5]).weekday(), 6, 'Jan 5 2000 is Wednesday -- 6th day'); }); test('weekday first day of week Friday (dow 5)', function (assert) { moment.locale('dow: 5,doy: 6', {week: {dow: 5, doy: 6}}); assert.equal(moment([1985, 1, 8]).weekday(), 0, 'Feb 8 1985 is Friday -- 0th day'); assert.equal(moment([2029, 8, 22]).weekday(), 1, 'Sep 22 2029 is Staturday -- 1st day'); assert.equal(moment([2013, 3, 28]).weekday(), 2, 'Apr 28 2013 is Sunday -- 2nd day'); assert.equal(moment([2015, 2, 9]).weekday(), 3, 'Mar 9 2015 is Monday -- 3nd day'); assert.equal(moment([1970, 0, 6]).weekday(), 4, 'Jan 6 1970 is Tuesday -- 4th day'); assert.equal(moment([2001, 4, 16]).weekday(), 5, 'May 16 2001 is Wednesday -- 5th day'); assert.equal(moment([2000, 0, 6]).weekday(), 6, 'Jan 6 2000 is Thursday -- 6th day'); }); test('weekday first day of week Saturday (dow 6)', function (assert) { moment.locale('dow: 6,doy: 6', {week: {dow: 6, doy: 6}}); assert.equal(moment([1985, 1, 9]).weekday(), 0, 'Feb 9 1985 is Staturday -- 0th day'); assert.equal(moment([2029, 8, 23]).weekday(), 1, 'Sep 23 2029 is Sunday -- 1st day'); assert.equal(moment([2013, 3, 29]).weekday(), 2, 'Apr 29 2013 is Monday -- 2nd day'); assert.equal(moment([2015, 2, 10]).weekday(), 3, 'Mar 10 2015 is Tuesday -- 3nd day'); assert.equal(moment([1970, 0, 7]).weekday(), 4, 'Jan 7 1970 is Wednesday -- 4th day'); assert.equal(moment([2001, 4, 17]).weekday(), 5, 'May 17 2001 is Thursday -- 5th day'); assert.equal(moment([2000, 0, 7]).weekday(), 6, 'Jan 7 2000 is Friday -- 6th day'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('weeks'); test('day of year', function (assert) { assert.equal(moment([2000, 0, 1]).dayOfYear(), 1, 'Jan 1 2000 should be day 1 of the year'); assert.equal(moment([2000, 1, 28]).dayOfYear(), 59, 'Feb 28 2000 should be day 59 of the year'); assert.equal(moment([2000, 1, 29]).dayOfYear(), 60, 'Feb 28 2000 should be day 60 of the year'); assert.equal(moment([2000, 11, 31]).dayOfYear(), 366, 'Dec 31 2000 should be day 366 of the year'); assert.equal(moment([2001, 0, 1]).dayOfYear(), 1, 'Jan 1 2001 should be day 1 of the year'); assert.equal(moment([2001, 1, 28]).dayOfYear(), 59, 'Feb 28 2001 should be day 59 of the year'); assert.equal(moment([2001, 2, 1]).dayOfYear(), 60, 'Mar 1 2001 should be day 60 of the year'); assert.equal(moment([2001, 11, 31]).dayOfYear(), 365, 'Dec 31 2001 should be day 365 of the year'); }); test('day of year setters', function (assert) { assert.equal(moment([2000, 0, 1]).dayOfYear(200).dayOfYear(), 200, 'Setting Jan 1 2000 day of the year to 200 should work'); assert.equal(moment([2000, 1, 28]).dayOfYear(200).dayOfYear(), 200, 'Setting Feb 28 2000 day of the year to 200 should work'); assert.equal(moment([2000, 1, 29]).dayOfYear(200).dayOfYear(), 200, 'Setting Feb 28 2000 day of the year to 200 should work'); assert.equal(moment([2000, 11, 31]).dayOfYear(200).dayOfYear(), 200, 'Setting Dec 31 2000 day of the year to 200 should work'); assert.equal(moment().dayOfYear(1).dayOfYear(), 1, 'Setting day of the year to 1 should work'); assert.equal(moment().dayOfYear(59).dayOfYear(), 59, 'Setting day of the year to 59 should work'); assert.equal(moment().dayOfYear(60).dayOfYear(), 60, 'Setting day of the year to 60 should work'); assert.equal(moment().dayOfYear(365).dayOfYear(), 365, 'Setting day of the year to 365 should work'); }); test('iso weeks year starting sunday', function (assert) { assert.equal(moment([2012, 0, 1]).isoWeek(), 52, 'Jan 1 2012 should be iso week 52'); assert.equal(moment([2012, 0, 2]).isoWeek(), 1, 'Jan 2 2012 should be iso week 1'); assert.equal(moment([2012, 0, 8]).isoWeek(), 1, 'Jan 8 2012 should be iso week 1'); assert.equal(moment([2012, 0, 9]).isoWeek(), 2, 'Jan 9 2012 should be iso week 2'); assert.equal(moment([2012, 0, 15]).isoWeek(), 2, 'Jan 15 2012 should be iso week 2'); }); test('iso weeks year starting monday', function (assert) { assert.equal(moment([2007, 0, 1]).isoWeek(), 1, 'Jan 1 2007 should be iso week 1'); assert.equal(moment([2007, 0, 7]).isoWeek(), 1, 'Jan 7 2007 should be iso week 1'); assert.equal(moment([2007, 0, 8]).isoWeek(), 2, 'Jan 8 2007 should be iso week 2'); assert.equal(moment([2007, 0, 14]).isoWeek(), 2, 'Jan 14 2007 should be iso week 2'); assert.equal(moment([2007, 0, 15]).isoWeek(), 3, 'Jan 15 2007 should be iso week 3'); }); test('iso weeks year starting tuesday', function (assert) { assert.equal(moment([2007, 11, 31]).isoWeek(), 1, 'Dec 31 2007 should be iso week 1'); assert.equal(moment([2008, 0, 1]).isoWeek(), 1, 'Jan 1 2008 should be iso week 1'); assert.equal(moment([2008, 0, 6]).isoWeek(), 1, 'Jan 6 2008 should be iso week 1'); assert.equal(moment([2008, 0, 7]).isoWeek(), 2, 'Jan 7 2008 should be iso week 2'); assert.equal(moment([2008, 0, 13]).isoWeek(), 2, 'Jan 13 2008 should be iso week 2'); assert.equal(moment([2008, 0, 14]).isoWeek(), 3, 'Jan 14 2008 should be iso week 3'); }); test('iso weeks year starting wednesday', function (assert) { assert.equal(moment([2002, 11, 30]).isoWeek(), 1, 'Dec 30 2002 should be iso week 1'); assert.equal(moment([2003, 0, 1]).isoWeek(), 1, 'Jan 1 2003 should be iso week 1'); assert.equal(moment([2003, 0, 5]).isoWeek(), 1, 'Jan 5 2003 should be iso week 1'); assert.equal(moment([2003, 0, 6]).isoWeek(), 2, 'Jan 6 2003 should be iso week 2'); assert.equal(moment([2003, 0, 12]).isoWeek(), 2, 'Jan 12 2003 should be iso week 2'); assert.equal(moment([2003, 0, 13]).isoWeek(), 3, 'Jan 13 2003 should be iso week 3'); }); test('iso weeks year starting thursday', function (assert) { assert.equal(moment([2008, 11, 29]).isoWeek(), 1, 'Dec 29 2008 should be iso week 1'); assert.equal(moment([2009, 0, 1]).isoWeek(), 1, 'Jan 1 2009 should be iso week 1'); assert.equal(moment([2009, 0, 4]).isoWeek(), 1, 'Jan 4 2009 should be iso week 1'); assert.equal(moment([2009, 0, 5]).isoWeek(), 2, 'Jan 5 2009 should be iso week 2'); assert.equal(moment([2009, 0, 11]).isoWeek(), 2, 'Jan 11 2009 should be iso week 2'); assert.equal(moment([2009, 0, 13]).isoWeek(), 3, 'Jan 12 2009 should be iso week 3'); }); test('iso weeks year starting friday', function (assert) { assert.equal(moment([2009, 11, 28]).isoWeek(), 53, 'Dec 28 2009 should be iso week 53'); assert.equal(moment([2010, 0, 1]).isoWeek(), 53, 'Jan 1 2010 should be iso week 53'); assert.equal(moment([2010, 0, 3]).isoWeek(), 53, 'Jan 3 2010 should be iso week 53'); assert.equal(moment([2010, 0, 4]).isoWeek(), 1, 'Jan 4 2010 should be iso week 1'); assert.equal(moment([2010, 0, 10]).isoWeek(), 1, 'Jan 10 2010 should be iso week 1'); assert.equal(moment([2010, 0, 11]).isoWeek(), 2, 'Jan 11 2010 should be iso week 2'); }); test('iso weeks year starting saturday', function (assert) { assert.equal(moment([2010, 11, 27]).isoWeek(), 52, 'Dec 27 2010 should be iso week 52'); assert.equal(moment([2011, 0, 1]).isoWeek(), 52, 'Jan 1 2011 should be iso week 52'); assert.equal(moment([2011, 0, 2]).isoWeek(), 52, 'Jan 2 2011 should be iso week 52'); assert.equal(moment([2011, 0, 3]).isoWeek(), 1, 'Jan 3 2011 should be iso week 1'); assert.equal(moment([2011, 0, 9]).isoWeek(), 1, 'Jan 9 2011 should be iso week 1'); assert.equal(moment([2011, 0, 10]).isoWeek(), 2, 'Jan 10 2011 should be iso week 2'); }); test('iso weeks year starting sunday formatted', function (assert) { assert.equal(moment([2012, 0, 1]).format('W WW Wo'), '52 52 52nd', 'Jan 1 2012 should be iso week 52'); assert.equal(moment([2012, 0, 2]).format('W WW Wo'), '1 01 1st', 'Jan 2 2012 should be iso week 1'); assert.equal(moment([2012, 0, 8]).format('W WW Wo'), '1 01 1st', 'Jan 8 2012 should be iso week 1'); assert.equal(moment([2012, 0, 9]).format('W WW Wo'), '2 02 2nd', 'Jan 9 2012 should be iso week 2'); assert.equal(moment([2012, 0, 15]).format('W WW Wo'), '2 02 2nd', 'Jan 15 2012 should be iso week 2'); }); test('weeks plural year starting sunday', function (assert) { assert.equal(moment([2012, 0, 1]).weeks(), 1, 'Jan 1 2012 should be week 1'); assert.equal(moment([2012, 0, 7]).weeks(), 1, 'Jan 7 2012 should be week 1'); assert.equal(moment([2012, 0, 8]).weeks(), 2, 'Jan 8 2012 should be week 2'); assert.equal(moment([2012, 0, 14]).weeks(), 2, 'Jan 14 2012 should be week 2'); assert.equal(moment([2012, 0, 15]).weeks(), 3, 'Jan 15 2012 should be week 3'); }); test('iso weeks plural year starting sunday', function (assert) { assert.equal(moment([2012, 0, 1]).isoWeeks(), 52, 'Jan 1 2012 should be iso week 52'); assert.equal(moment([2012, 0, 2]).isoWeeks(), 1, 'Jan 2 2012 should be iso week 1'); assert.equal(moment([2012, 0, 8]).isoWeeks(), 1, 'Jan 8 2012 should be iso week 1'); assert.equal(moment([2012, 0, 9]).isoWeeks(), 2, 'Jan 9 2012 should be iso week 2'); assert.equal(moment([2012, 0, 15]).isoWeeks(), 2, 'Jan 15 2012 should be iso week 2'); }); test('weeks setter', function (assert) { assert.equal(moment([2012, 0, 1]).week(30).week(), 30, 'Setting Jan 1 2012 to week 30 should work'); assert.equal(moment([2012, 0, 7]).week(30).week(), 30, 'Setting Jan 7 2012 to week 30 should work'); assert.equal(moment([2012, 0, 8]).week(30).week(), 30, 'Setting Jan 8 2012 to week 30 should work'); assert.equal(moment([2012, 0, 14]).week(30).week(), 30, 'Setting Jan 14 2012 to week 30 should work'); assert.equal(moment([2012, 0, 15]).week(30).week(), 30, 'Setting Jan 15 2012 to week 30 should work'); }); test('iso weeks setter', function (assert) { assert.equal(moment([2012, 0, 1]).isoWeeks(25).isoWeeks(), 25, 'Setting Jan 1 2012 to week 25 should work'); assert.equal(moment([2012, 0, 2]).isoWeeks(24).isoWeeks(), 24, 'Setting Jan 2 2012 to week 24 should work'); assert.equal(moment([2012, 0, 8]).isoWeeks(23).isoWeeks(), 23, 'Setting Jan 8 2012 to week 23 should work'); assert.equal(moment([2012, 0, 9]).isoWeeks(22).isoWeeks(), 22, 'Setting Jan 9 2012 to week 22 should work'); assert.equal(moment([2012, 0, 15]).isoWeeks(21).isoWeeks(), 21, 'Setting Jan 15 2012 to week 21 should work'); }); test('iso weeks setter day of year', function (assert) { assert.equal(moment([2012, 0, 1]).isoWeek(1).dayOfYear(), 9, 'Setting Jan 1 2012 to week 1 should be day of year 8'); assert.equal(moment([2012, 0, 1]).isoWeek(1).year(), 2011, 'Setting Jan 1 2012 to week 1 should be year 2011'); assert.equal(moment([2012, 0, 2]).isoWeek(1).dayOfYear(), 2, 'Setting Jan 2 2012 to week 1 should be day of year 2'); assert.equal(moment([2012, 0, 8]).isoWeek(1).dayOfYear(), 8, 'Setting Jan 8 2012 to week 1 should be day of year 8'); assert.equal(moment([2012, 0, 9]).isoWeek(1).dayOfYear(), 2, 'Setting Jan 9 2012 to week 1 should be day of year 2'); assert.equal(moment([2012, 0, 15]).isoWeek(1).dayOfYear(), 8, 'Setting Jan 15 2012 to week 1 should be day of year 8'); }); test('years with iso week 53', function (assert) { // Based on a table taken from path_to_url // (as downloaded on 2014-01-06) listing the 71 years in a 400-year cycle // that have 53 weeks; in this case reflecting the 2000 based cycle assert.equal(moment([2004, 11, 31]).isoWeek(), 53, 'Dec 31 2004 should be iso week 53'); assert.equal(moment([2009, 11, 31]).isoWeek(), 53, 'Dec 31 2009 should be iso week 53'); assert.equal(moment([2015, 11, 31]).isoWeek(), 53, 'Dec 31 2015 should be iso week 53'); assert.equal(moment([2020, 11, 31]).isoWeek(), 53, 'Dec 31 2020 should be iso week 53'); assert.equal(moment([2026, 11, 31]).isoWeek(), 53, 'Dec 31 2026 should be iso week 53'); assert.equal(moment([2032, 11, 31]).isoWeek(), 53, 'Dec 31 2032 should be iso week 53'); assert.equal(moment([2037, 11, 31]).isoWeek(), 53, 'Dec 31 2037 should be iso week 53'); assert.equal(moment([2043, 11, 31]).isoWeek(), 53, 'Dec 31 2043 should be iso week 53'); assert.equal(moment([2048, 11, 31]).isoWeek(), 53, 'Dec 31 2048 should be iso week 53'); assert.equal(moment([2054, 11, 31]).isoWeek(), 53, 'Dec 31 2054 should be iso week 53'); assert.equal(moment([2060, 11, 31]).isoWeek(), 53, 'Dec 31 2060 should be iso week 53'); assert.equal(moment([2065, 11, 31]).isoWeek(), 53, 'Dec 31 2065 should be iso week 53'); assert.equal(moment([2071, 11, 31]).isoWeek(), 53, 'Dec 31 2071 should be iso week 53'); assert.equal(moment([2076, 11, 31]).isoWeek(), 53, 'Dec 31 2076 should be iso week 53'); assert.equal(moment([2082, 11, 31]).isoWeek(), 53, 'Dec 31 2082 should be iso week 53'); assert.equal(moment([2088, 11, 31]).isoWeek(), 53, 'Dec 31 2088 should be iso week 53'); assert.equal(moment([2093, 11, 31]).isoWeek(), 53, 'Dec 31 2093 should be iso week 53'); assert.equal(moment([2099, 11, 31]).isoWeek(), 53, 'Dec 31 2099 should be iso week 53'); assert.equal(moment([2105, 11, 31]).isoWeek(), 53, 'Dec 31 2105 should be iso week 53'); assert.equal(moment([2111, 11, 31]).isoWeek(), 53, 'Dec 31 2111 should be iso week 53'); assert.equal(moment([2116, 11, 31]).isoWeek(), 53, 'Dec 31 2116 should be iso week 53'); assert.equal(moment([2122, 11, 31]).isoWeek(), 53, 'Dec 31 2122 should be iso week 53'); assert.equal(moment([2128, 11, 31]).isoWeek(), 53, 'Dec 31 2128 should be iso week 53'); assert.equal(moment([2133, 11, 31]).isoWeek(), 53, 'Dec 31 2133 should be iso week 53'); assert.equal(moment([2139, 11, 31]).isoWeek(), 53, 'Dec 31 2139 should be iso week 53'); assert.equal(moment([2144, 11, 31]).isoWeek(), 53, 'Dec 31 2144 should be iso week 53'); assert.equal(moment([2150, 11, 31]).isoWeek(), 53, 'Dec 31 2150 should be iso week 53'); assert.equal(moment([2156, 11, 31]).isoWeek(), 53, 'Dec 31 2156 should be iso week 53'); assert.equal(moment([2161, 11, 31]).isoWeek(), 53, 'Dec 31 2161 should be iso week 53'); assert.equal(moment([2167, 11, 31]).isoWeek(), 53, 'Dec 31 2167 should be iso week 53'); assert.equal(moment([2172, 11, 31]).isoWeek(), 53, 'Dec 31 2172 should be iso week 53'); assert.equal(moment([2178, 11, 31]).isoWeek(), 53, 'Dec 31 2178 should be iso week 53'); assert.equal(moment([2184, 11, 31]).isoWeek(), 53, 'Dec 31 2184 should be iso week 53'); assert.equal(moment([2189, 11, 31]).isoWeek(), 53, 'Dec 31 2189 should be iso week 53'); assert.equal(moment([2195, 11, 31]).isoWeek(), 53, 'Dec 31 2195 should be iso week 53'); assert.equal(moment([2201, 11, 31]).isoWeek(), 53, 'Dec 31 2201 should be iso week 53'); assert.equal(moment([2207, 11, 31]).isoWeek(), 53, 'Dec 31 2207 should be iso week 53'); assert.equal(moment([2212, 11, 31]).isoWeek(), 53, 'Dec 31 2212 should be iso week 53'); assert.equal(moment([2218, 11, 31]).isoWeek(), 53, 'Dec 31 2218 should be iso week 53'); assert.equal(moment([2224, 11, 31]).isoWeek(), 53, 'Dec 31 2224 should be iso week 53'); assert.equal(moment([2229, 11, 31]).isoWeek(), 53, 'Dec 31 2229 should be iso week 53'); assert.equal(moment([2235, 11, 31]).isoWeek(), 53, 'Dec 31 2235 should be iso week 53'); assert.equal(moment([2240, 11, 31]).isoWeek(), 53, 'Dec 31 2240 should be iso week 53'); assert.equal(moment([2246, 11, 31]).isoWeek(), 53, 'Dec 31 2246 should be iso week 53'); assert.equal(moment([2252, 11, 31]).isoWeek(), 53, 'Dec 31 2252 should be iso week 53'); assert.equal(moment([2257, 11, 31]).isoWeek(), 53, 'Dec 31 2257 should be iso week 53'); assert.equal(moment([2263, 11, 31]).isoWeek(), 53, 'Dec 31 2263 should be iso week 53'); assert.equal(moment([2268, 11, 31]).isoWeek(), 53, 'Dec 31 2268 should be iso week 53'); assert.equal(moment([2274, 11, 31]).isoWeek(), 53, 'Dec 31 2274 should be iso week 53'); assert.equal(moment([2280, 11, 31]).isoWeek(), 53, 'Dec 31 2280 should be iso week 53'); assert.equal(moment([2285, 11, 31]).isoWeek(), 53, 'Dec 31 2285 should be iso week 53'); assert.equal(moment([2291, 11, 31]).isoWeek(), 53, 'Dec 31 2291 should be iso week 53'); assert.equal(moment([2296, 11, 31]).isoWeek(), 53, 'Dec 31 2296 should be iso week 53'); assert.equal(moment([2303, 11, 31]).isoWeek(), 53, 'Dec 31 2303 should be iso week 53'); assert.equal(moment([2308, 11, 31]).isoWeek(), 53, 'Dec 31 2308 should be iso week 53'); assert.equal(moment([2314, 11, 31]).isoWeek(), 53, 'Dec 31 2314 should be iso week 53'); assert.equal(moment([2320, 11, 31]).isoWeek(), 53, 'Dec 31 2320 should be iso week 53'); assert.equal(moment([2325, 11, 31]).isoWeek(), 53, 'Dec 31 2325 should be iso week 53'); assert.equal(moment([2331, 11, 31]).isoWeek(), 53, 'Dec 31 2331 should be iso week 53'); assert.equal(moment([2336, 11, 31]).isoWeek(), 53, 'Dec 31 2336 should be iso week 53'); assert.equal(moment([2342, 11, 31]).isoWeek(), 53, 'Dec 31 2342 should be iso week 53'); assert.equal(moment([2348, 11, 31]).isoWeek(), 53, 'Dec 31 2348 should be iso week 53'); assert.equal(moment([2353, 11, 31]).isoWeek(), 53, 'Dec 31 2353 should be iso week 53'); assert.equal(moment([2359, 11, 31]).isoWeek(), 53, 'Dec 31 2359 should be iso week 53'); assert.equal(moment([2364, 11, 31]).isoWeek(), 53, 'Dec 31 2364 should be iso week 53'); assert.equal(moment([2370, 11, 31]).isoWeek(), 53, 'Dec 31 2370 should be iso week 53'); assert.equal(moment([2376, 11, 31]).isoWeek(), 53, 'Dec 31 2376 should be iso week 53'); assert.equal(moment([2381, 11, 31]).isoWeek(), 53, 'Dec 31 2381 should be iso week 53'); assert.equal(moment([2387, 11, 31]).isoWeek(), 53, 'Dec 31 2387 should be iso week 53'); assert.equal(moment([2392, 11, 31]).isoWeek(), 53, 'Dec 31 2392 should be iso week 53'); assert.equal(moment([2398, 11, 31]).isoWeek(), 53, 'Dec 31 2398 should be iso week 53'); }); test('count years with iso week 53', function (assert) { // Based on path_to_url (as seen on 2014-01-06) // stating that there are 71 years in a 400-year cycle that have 53 weeks; // in this case reflecting the 2000 based cycle var count = 0, i; for (i = 0; i < 400; i++) { count += (moment([2000 + i, 11, 31]).isoWeek() === 53) ? 1 : 0; } assert.equal(count, 71, 'Should have 71 years in 400-year cycle with iso week 53'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('weeks in year'); test('isoWeeksInYear', function (assert) { assert.equal(moment([2004]).isoWeeksInYear(), 53, '2004 has 53 iso weeks'); assert.equal(moment([2005]).isoWeeksInYear(), 52, '2005 has 53 iso weeks'); assert.equal(moment([2006]).isoWeeksInYear(), 52, '2006 has 53 iso weeks'); assert.equal(moment([2007]).isoWeeksInYear(), 52, '2007 has 52 iso weeks'); assert.equal(moment([2008]).isoWeeksInYear(), 52, '2008 has 53 iso weeks'); assert.equal(moment([2009]).isoWeeksInYear(), 53, '2009 has 53 iso weeks'); assert.equal(moment([2010]).isoWeeksInYear(), 52, '2010 has 52 iso weeks'); assert.equal(moment([2011]).isoWeeksInYear(), 52, '2011 has 52 iso weeks'); assert.equal(moment([2012]).isoWeeksInYear(), 52, '2012 has 52 iso weeks'); assert.equal(moment([2013]).isoWeeksInYear(), 52, '2013 has 52 iso weeks'); assert.equal(moment([2014]).isoWeeksInYear(), 52, '2014 has 52 iso weeks'); assert.equal(moment([2015]).isoWeeksInYear(), 53, '2015 has 53 iso weeks'); }); test('weeksInYear doy/dow = 1/4', function (assert) { moment.locale('1/4', {week: {dow: 1, doy: 4}}); assert.equal(moment([2004]).weeksInYear(), 53, '2004 has 53 weeks'); assert.equal(moment([2005]).weeksInYear(), 52, '2005 has 53 weeks'); assert.equal(moment([2006]).weeksInYear(), 52, '2006 has 53 weeks'); assert.equal(moment([2007]).weeksInYear(), 52, '2007 has 52 weeks'); assert.equal(moment([2008]).weeksInYear(), 52, '2008 has 53 weeks'); assert.equal(moment([2009]).weeksInYear(), 53, '2009 has 53 weeks'); assert.equal(moment([2010]).weeksInYear(), 52, '2010 has 52 weeks'); assert.equal(moment([2011]).weeksInYear(), 52, '2011 has 52 weeks'); assert.equal(moment([2012]).weeksInYear(), 52, '2012 has 52 weeks'); assert.equal(moment([2013]).weeksInYear(), 52, '2013 has 52 weeks'); assert.equal(moment([2014]).weeksInYear(), 52, '2014 has 52 weeks'); assert.equal(moment([2015]).weeksInYear(), 53, '2015 has 53 weeks'); }); test('weeksInYear doy/dow = 6/12', function (assert) { moment.locale('6/12', {week: {dow: 6, doy: 12}}); assert.equal(moment([2004]).weeksInYear(), 53, '2004 has 53 weeks'); assert.equal(moment([2005]).weeksInYear(), 52, '2005 has 53 weeks'); assert.equal(moment([2006]).weeksInYear(), 52, '2006 has 53 weeks'); assert.equal(moment([2007]).weeksInYear(), 52, '2007 has 52 weeks'); assert.equal(moment([2008]).weeksInYear(), 52, '2008 has 53 weeks'); assert.equal(moment([2009]).weeksInYear(), 52, '2009 has 53 weeks'); assert.equal(moment([2010]).weeksInYear(), 53, '2010 has 52 weeks'); assert.equal(moment([2011]).weeksInYear(), 52, '2011 has 52 weeks'); assert.equal(moment([2012]).weeksInYear(), 52, '2012 has 52 weeks'); assert.equal(moment([2013]).weeksInYear(), 52, '2013 has 52 weeks'); assert.equal(moment([2014]).weeksInYear(), 52, '2014 has 52 weeks'); assert.equal(moment([2015]).weeksInYear(), 52, '2015 has 53 weeks'); }); test('weeksInYear doy/dow = 1/7', function (assert) { moment.locale('1/7', {week: {dow: 1, doy: 7}}); assert.equal(moment([2004]).weeksInYear(), 52, '2004 has 53 weeks'); assert.equal(moment([2005]).weeksInYear(), 52, '2005 has 53 weeks'); assert.equal(moment([2006]).weeksInYear(), 53, '2006 has 53 weeks'); assert.equal(moment([2007]).weeksInYear(), 52, '2007 has 52 weeks'); assert.equal(moment([2008]).weeksInYear(), 52, '2008 has 53 weeks'); assert.equal(moment([2009]).weeksInYear(), 52, '2009 has 53 weeks'); assert.equal(moment([2010]).weeksInYear(), 52, '2010 has 52 weeks'); assert.equal(moment([2011]).weeksInYear(), 52, '2011 has 52 weeks'); assert.equal(moment([2012]).weeksInYear(), 53, '2012 has 52 weeks'); assert.equal(moment([2013]).weeksInYear(), 52, '2013 has 52 weeks'); assert.equal(moment([2014]).weeksInYear(), 52, '2014 has 52 weeks'); assert.equal(moment([2015]).weeksInYear(), 52, '2015 has 53 weeks'); }); test('weeksInYear doy/dow = 0/6', function (assert) { moment.locale('0/6', {week: {dow: 0, doy: 6}}); assert.equal(moment([2004]).weeksInYear(), 52, '2004 has 53 weeks'); assert.equal(moment([2005]).weeksInYear(), 53, '2005 has 53 weeks'); assert.equal(moment([2006]).weeksInYear(), 52, '2006 has 53 weeks'); assert.equal(moment([2007]).weeksInYear(), 52, '2007 has 52 weeks'); assert.equal(moment([2008]).weeksInYear(), 52, '2008 has 53 weeks'); assert.equal(moment([2009]).weeksInYear(), 52, '2009 has 53 weeks'); assert.equal(moment([2010]).weeksInYear(), 52, '2010 has 52 weeks'); assert.equal(moment([2011]).weeksInYear(), 53, '2011 has 52 weeks'); assert.equal(moment([2012]).weeksInYear(), 52, '2012 has 52 weeks'); assert.equal(moment([2013]).weeksInYear(), 52, '2013 has 52 weeks'); assert.equal(moment([2014]).weeksInYear(), 52, '2014 has 52 weeks'); assert.equal(moment([2015]).weeksInYear(), 52, '2015 has 53 weeks'); }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } function isNearSpringDST() { return moment().subtract(1, 'day').utcOffset() !== moment().add(1, 'day').utcOffset(); } module('zone switching'); test('local to utc, keepLocalTime = true', function (assert) { var m = moment(), fmt = 'YYYY-DD-MM HH:mm:ss'; assert.equal(m.clone().utc(true).format(fmt), m.format(fmt), 'local to utc failed to keep local time'); }); test('local to utc, keepLocalTime = false', function (assert) { var m = moment(); assert.equal(m.clone().utc().valueOf(), m.valueOf(), 'local to utc failed to keep utc time (implicit)'); assert.equal(m.clone().utc(false).valueOf(), m.valueOf(), 'local to utc failed to keep utc time (explicit)'); }); test('local to zone, keepLocalTime = true', function (assert) { test.expectedDeprecations('moment().zone'); var m = moment(), fmt = 'YYYY-DD-MM HH:mm:ss', z; // Apparently there is -12:00 and +14:00 // path_to_url // path_to_url for (z = -12; z <= 14; ++z) { assert.equal(m.clone().zone(z * 60, true).format(fmt), m.format(fmt), 'local to zone(' + z + ':00) failed to keep local time'); } }); test('local to zone, keepLocalTime = false', function (assert) { test.expectedDeprecations('moment().zone'); var m = moment(), z; // Apparently there is -12:00 and +14:00 // path_to_url // path_to_url for (z = -12; z <= 14; ++z) { assert.equal(m.clone().zone(z * 60).valueOf(), m.valueOf(), 'local to zone(' + z + ':00) failed to keep utc time (implicit)'); assert.equal(m.clone().zone(z * 60, false).valueOf(), m.valueOf(), 'local to zone(' + z + ':00) failed to keep utc time (explicit)'); } }); test('utc to local, keepLocalTime = true', function (assert) { // Don't test near the spring DST transition if (isNearSpringDST()) { expect(0); return; } var um = moment.utc(), fmt = 'YYYY-DD-MM HH:mm:ss'; assert.equal(um.clone().local(true).format(fmt), um.format(fmt), 'utc to local failed to keep local time'); }); test('utc to local, keepLocalTime = false', function (assert) { var um = moment.utc(); assert.equal(um.clone().local().valueOf(), um.valueOf(), 'utc to local failed to keep utc time (implicit)'); assert.equal(um.clone().local(false).valueOf(), um.valueOf(), 'utc to local failed to keep utc time (explicit)'); }); test('zone to local, keepLocalTime = true', function (assert) { test.expectedDeprecations('moment().zone'); // Don't test near the spring DST transition if (isNearSpringDST()) { expect(0); return; } var m = moment(), fmt = 'YYYY-DD-MM HH:mm:ss', z; // Apparently there is -12:00 and +14:00 // path_to_url // path_to_url for (z = -12; z <= 14; ++z) { m.zone(z * 60); assert.equal(m.clone().local(true).format(fmt), m.format(fmt), 'zone(' + z + ':00) to local failed to keep local time'); } }); test('zone to local, keepLocalTime = false', function (assert) { test.expectedDeprecations('moment().zone'); var m = moment(), z; // Apparently there is -12:00 and +14:00 // path_to_url // path_to_url for (z = -12; z <= 14; ++z) { m.zone(z * 60); assert.equal(m.clone().local(false).valueOf(), m.valueOf(), 'zone(' + z + ':00) to local failed to keep utc time (explicit)'); assert.equal(m.clone().local().valueOf(), m.valueOf(), 'zone(' + z + ':00) to local failed to keep utc time (implicit)'); } }); })); ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../../moment')) : typeof define === 'function' && define.amd ? define(['../../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; function each(array, callback) { var i; for (i = 0; i < array.length; i++) { callback(array[i], i, array); } } function objectKeys(obj) { if (Object.keys) { return Object.keys(obj); } else { // IE8 var res = [], i; for (i in obj) { if (obj.hasOwnProperty(i)) { res.push(i); } } return res; } } // 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 defineCommonLocaleTests(locale, options) { test('lenient ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing ' + i + ' date check'); } }); test('lenient ordinal parsing of number', function (assert) { var i, testMoment; for (i = 1; i <= 31; ++i) { testMoment = moment('2014 01 ' + i, 'YYYY MM Do'); assert.equal(testMoment.year(), 2014, 'lenient ordinal parsing of number ' + i + ' year check'); assert.equal(testMoment.month(), 0, 'lenient ordinal parsing of number ' + i + ' month check'); assert.equal(testMoment.date(), i, 'lenient ordinal parsing of number ' + i + ' date check'); } }); test('strict ordinal parsing', function (assert) { var i, ordinalStr, testMoment; for (i = 1; i <= 31; ++i) { ordinalStr = moment([2014, 0, i]).format('YYYY MM Do'); testMoment = moment(ordinalStr, 'YYYY MM Do', true); assert.ok(testMoment.isValid(), 'strict ordinal parsing ' + i); } }); test('meridiem invariant', function (assert) { var h, m, t1, t2; for (h = 0; h < 24; ++h) { for (m = 0; m < 60; m += 15) { t1 = moment.utc([2000, 0, 1, h, m]); t2 = moment.utc(t1.format('A h:mm'), 'A h:mm'); assert.equal(t2.format('HH:mm'), t1.format('HH:mm'), 'meridiem at ' + t1.format('HH:mm')); } } }); test('date format correctness', function (assert) { var data, tokens; data = moment.localeData()._longDateFormat; tokens = objectKeys(data); each(tokens, function (srchToken) { // Check each format string to make sure it does not contain any // tokens that need to be expanded. each(tokens, function (baseToken) { // strip escaped sequences var format = data[baseToken].replace(/(\[[^\]]*\])/g, ''); assert.equal(false, !!~format.indexOf(srchToken), 'contains ' + srchToken + ' in ' + baseToken); }); }); }); test('month parsing correctness', function (assert) { var i, m; if (locale === 'tr') { // I can't fix it :( expect(0); return; } function tester(format) { var r; r = moment(m.format(format), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.month(), m.month(), 'month ' + i + ' fmt ' + format + ' lower strict'); } for (i = 0; i < 12; ++i) { m = moment([2015, i, 15, 18]); tester('MMM'); tester('MMM.'); tester('MMMM'); tester('MMMM.'); } }); test('weekday parsing correctness', function (assert) { var i, m; if (locale === 'tr' || locale === 'az') { // There is a lower-case letter (), that converted to upper then // lower changes to i expect(0); return; } function tester(format) { var r, baseMsg = 'weekday ' + m.weekday() + ' fmt ' + format; r = moment(m.format(format), format); assert.equal(r.weekday(), m.weekday(), baseMsg); r = moment(m.format(format).toLocaleUpperCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper'); r = moment(m.format(format).toLocaleLowerCase(), format); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower'); r = moment(m.format(format), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' strict'); r = moment(m.format(format).toLocaleUpperCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' upper strict'); r = moment(m.format(format).toLocaleLowerCase(), format, true); assert.equal(r.weekday(), m.weekday(), baseMsg + ' lower strict'); } for (i = 0; i < 7; ++i) { m = moment.utc([2015, i, 15, 18]); tester('dd'); tester('ddd'); tester('dddd'); } }); } function setupDeprecationHandler(test, moment, scope) { test._expectedDeprecations = null; test._observedDeprecations = null; test._oldSupress = moment.suppressDeprecationWarnings; moment.suppressDeprecationWarnings = true; test.expectedDeprecations = function () { test._expectedDeprecations = arguments; test._observedDeprecations = []; }; moment.deprecationHandler = function (name, msg) { var deprecationId = matchedDeprecation(name, msg, test._expectedDeprecations); if (deprecationId === -1) { throw new Error('Unexpected deprecation thrown name=' + name + ' msg=' + msg); } test._observedDeprecations[deprecationId] = 1; }; } function teardownDeprecationHandler(test, moment, scope) { moment.suppressDeprecationWarnings = test._oldSupress; if (test._expectedDeprecations != null) { var missedDeprecations = []; each(test._expectedDeprecations, function (deprecationPattern, id) { if (test._observedDeprecations[id] !== 1) { missedDeprecations.push(deprecationPattern); } }); if (missedDeprecations.length !== 0) { throw new Error('Expected deprecation warnings did not happen: ' + missedDeprecations.join(' ')); } } } function matchedDeprecation(name, msg, deprecations) { if (deprecations == null) { return -1; } for (var i = 0; i < deprecations.length; ++i) { if (name != null && name === deprecations[i]) { return i; } if (msg != null && msg.substring(0, deprecations[i].length) === deprecations[i]) { return i; } } return -1; } /*global QUnit:false*/ var test = QUnit.test; var expect = QUnit.expect; function module (name, lifecycle) { QUnit.module(name, { setup : function () { moment.locale('en'); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { teardownDeprecationHandler(test, moment, 'core'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); } function localeModule (name, lifecycle) { QUnit.module('locale:' + name, { setup : function () { moment.locale(name); moment.createFromInputFallback = function (config) { throw new Error('input not handled by moment: ' + config._i); }; setupDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.setup) { lifecycle.setup(); } }, teardown : function () { moment.locale('en'); teardownDeprecationHandler(test, moment, 'locale'); if (lifecycle && lifecycle.teardown) { lifecycle.teardown(); } } }); defineCommonLocaleTests(name, -1, -1); } module('zones', { 'setup': function () { test.expectedDeprecations('moment().zone'); } }); test('set zone', function (assert) { var zone = moment(); zone.zone(0); assert.equal(zone.zone(), 0, 'should be able to set the zone to 0'); zone.zone(60); assert.equal(zone.zone(), 60, 'should be able to set the zone to 60'); zone.zone(-60); assert.equal(zone.zone(), -60, 'should be able to set the zone to -60'); }); test('set zone shorthand', function (assert) { var zone = moment(); zone.zone(1); assert.equal(zone.zone(), 60, 'setting the zone to 1 should imply hours and convert to 60'); zone.zone(-1); assert.equal(zone.zone(), -60, 'setting the zone to -1 should imply hours and convert to -60'); zone.zone(15); assert.equal(zone.zone(), 900, 'setting the zone to 15 should imply hours and convert to 900'); zone.zone(-15); assert.equal(zone.zone(), -900, 'setting the zone to -15 should imply hours and convert to -900'); zone.zone(16); assert.equal(zone.zone(), 16, 'setting the zone to 16 should imply minutes'); zone.zone(-16); assert.equal(zone.zone(), -16, 'setting the zone to -16 should imply minutes'); }); test('set zone with string', function (assert) { var zone = moment(); zone.zone('+00:00'); assert.equal(zone.zone(), 0, 'set the zone with a timezone string'); zone.zone('2013-03-07T07:00:00-08:00'); assert.equal(zone.zone(), 480, 'set the zone with a string that does not begin with the timezone'); zone.zone('2013-03-07T07:00:00+0100'); assert.equal(zone.zone(), -60, 'set the zone with a string that uses the +0000 syntax'); zone.zone('2013-03-07T07:00:00+02'); assert.equal(zone.zone(), -120, 'set the zone with a string that uses the +00 syntax'); zone.zone('03-07-2013T07:00:00-08:00'); assert.equal(zone.zone(), 480, 'set the zone with a string with a non-ISO 8601 date'); }); test('change hours when changing the zone', function (assert) { var zone = moment.utc([2000, 0, 1, 6]); zone.zone(0); assert.equal(zone.hour(), 6, 'UTC 6AM should be 6AM at +0000'); zone.zone(60); assert.equal(zone.hour(), 5, 'UTC 6AM should be 5AM at -0100'); zone.zone(-60); assert.equal(zone.hour(), 7, 'UTC 6AM should be 7AM at +0100'); }); test('change minutes when changing the zone', function (assert) { var zone = moment.utc([2000, 0, 1, 6, 31]); zone.zone(0); assert.equal(zone.format('HH:mm'), '06:31', 'UTC 6:31AM should be 6:31AM at +0000'); zone.zone(30); assert.equal(zone.format('HH:mm'), '06:01', 'UTC 6:31AM should be 6:01AM at -0030'); zone.zone(-30); assert.equal(zone.format('HH:mm'), '07:01', 'UTC 6:31AM should be 7:01AM at +0030'); zone.zone(1380); assert.equal(zone.format('HH:mm'), '07:31', 'UTC 6:31AM should be 7:31AM at +1380'); }); test('distance from the unix epoch', function (assert) { var zoneA = moment(), zoneB = moment(zoneA), zoneC = moment(zoneA), zoneD = moment(zoneA), zoneE = moment(zoneA); zoneB.utc(); assert.equal(+zoneA, +zoneB, 'moment should equal moment.utc'); zoneC.zone(-60); assert.equal(+zoneA, +zoneC, 'moment should equal moment.zone(-60)'); zoneD.zone(480); assert.equal(+zoneA, +zoneD, 'moment should equal moment.zone(480)'); zoneE.zone(1000); assert.equal(+zoneA, +zoneE, 'moment should equal moment.zone(1000)'); }); test('update offset after changing any values', function (assert) { var oldOffset = moment.updateOffset, m = moment.utc([2000, 6, 1]); moment.updateOffset = function (mom, keepTime) { if (mom.__doChange) { if (+mom > 962409600000) { mom.zone(120, keepTime); } else { mom.zone(60, keepTime); } } }; assert.equal(m.format('ZZ'), '+0000', 'should be at +0000'); assert.equal(m.format('HH:mm'), '00:00', 'should start 12AM at +0000 timezone'); m.__doChange = true; m.add(1, 'h'); assert.equal(m.format('ZZ'), '-0200', 'should be at -0200'); assert.equal(m.format('HH:mm'), '23:00', '1AM at +0000 should be 11PM at -0200 timezone'); m.subtract(1, 'h'); assert.equal(m.format('ZZ'), '-0100', 'should be at -0100'); assert.equal(m.format('HH:mm'), '23:00', '12AM at +0000 should be 11PM at -0100 timezone'); moment.updateOffset = oldOffset; }); test('getters and setters', function (assert) { var a = moment([2011, 5, 20]); assert.equal(a.clone().zone(120).year(2012).year(), 2012, 'should get and set year correctly'); assert.equal(a.clone().zone(120).month(1).month(), 1, 'should get and set month correctly'); assert.equal(a.clone().zone(120).date(2).date(), 2, 'should get and set date correctly'); assert.equal(a.clone().zone(120).day(1).day(), 1, 'should get and set day correctly'); assert.equal(a.clone().zone(120).hour(1).hour(), 1, 'should get and set hour correctly'); assert.equal(a.clone().zone(120).minute(1).minute(), 1, 'should get and set minute correctly'); }); test('getters', function (assert) { var a = moment.utc([2012, 0, 1, 0, 0, 0]); assert.equal(a.clone().zone(120).year(), 2011, 'should get year correctly'); assert.equal(a.clone().zone(120).month(), 11, 'should get month correctly'); assert.equal(a.clone().zone(120).date(), 31, 'should get date correctly'); assert.equal(a.clone().zone(120).hour(), 22, 'should get hour correctly'); assert.equal(a.clone().zone(120).minute(), 0, 'should get minute correctly'); assert.equal(a.clone().zone(-120).year(), 2012, 'should get year correctly'); assert.equal(a.clone().zone(-120).month(), 0, 'should get month correctly'); assert.equal(a.clone().zone(-120).date(), 1, 'should get date correctly'); assert.equal(a.clone().zone(-120).hour(), 2, 'should get hour correctly'); assert.equal(a.clone().zone(-120).minute(), 0, 'should get minute correctly'); assert.equal(a.clone().zone(-90).year(), 2012, 'should get year correctly'); assert.equal(a.clone().zone(-90).month(), 0, 'should get month correctly'); assert.equal(a.clone().zone(-90).date(), 1, 'should get date correctly'); assert.equal(a.clone().zone(-90).hour(), 1, 'should get hour correctly'); assert.equal(a.clone().zone(-90).minute(), 30, 'should get minute correctly'); }); test('from', function (assert) { var zoneA = moment(), zoneB = moment(zoneA).zone(720), zoneC = moment(zoneA).zone(360), zoneD = moment(zoneA).zone(-690), other = moment(zoneA).add(35, 'm'); assert.equal(zoneA.from(other), zoneB.from(other), 'moment#from should be the same in all zones'); assert.equal(zoneA.from(other), zoneC.from(other), 'moment#from should be the same in all zones'); assert.equal(zoneA.from(other), zoneD.from(other), 'moment#from should be the same in all zones'); }); test('diff', function (assert) { var zoneA = moment(), zoneB = moment(zoneA).zone(720), zoneC = moment(zoneA).zone(360), zoneD = moment(zoneA).zone(-690), other = moment(zoneA).add(35, 'm'); assert.equal(zoneA.diff(other), zoneB.diff(other), 'moment#diff should be the same in all zones'); assert.equal(zoneA.diff(other), zoneC.diff(other), 'moment#diff should be the same in all zones'); assert.equal(zoneA.diff(other), zoneD.diff(other), 'moment#diff should be the same in all zones'); assert.equal(zoneA.diff(other, 'minute', true), zoneB.diff(other, 'minute', true), 'moment#diff should be the same in all zones'); assert.equal(zoneA.diff(other, 'minute', true), zoneC.diff(other, 'minute', true), 'moment#diff should be the same in all zones'); assert.equal(zoneA.diff(other, 'minute', true), zoneD.diff(other, 'minute', true), 'moment#diff should be the same in all zones'); assert.equal(zoneA.diff(other, 'hour', true), zoneB.diff(other, 'hour', true), 'moment#diff should be the same in all zones'); assert.equal(zoneA.diff(other, 'hour', true), zoneC.diff(other, 'hour', true), 'moment#diff should be the same in all zones'); assert.equal(zoneA.diff(other, 'hour', true), zoneD.diff(other, 'hour', true), 'moment#diff should be the same in all zones'); }); test('unix offset and timestamp', function (assert) { var zoneA = moment(), zoneB = moment(zoneA).zone(720), zoneC = moment(zoneA).zone(360), zoneD = moment(zoneA).zone(-690); assert.equal(zoneA.unix(), zoneB.unix(), 'moment#unix should be the same in all zones'); assert.equal(zoneA.unix(), zoneC.unix(), 'moment#unix should be the same in all zones'); assert.equal(zoneA.unix(), zoneD.unix(), 'moment#unix should be the same in all zones'); assert.equal(+zoneA, +zoneB, 'moment#valueOf should be the same in all zones'); assert.equal(+zoneA, +zoneC, 'moment#valueOf should be the same in all zones'); assert.equal(+zoneA, +zoneD, 'moment#valueOf should be the same in all zones'); }); test('cloning', function (assert) { assert.equal(moment().zone(120).clone().zone(), 120, 'explicit cloning should retain the zone'); assert.equal(moment().zone(-120).clone().zone(), -120, 'explicit cloning should retain the zone'); assert.equal(moment(moment().zone(120)).zone(), 120, 'implicit cloning should retain the zone'); assert.equal(moment(moment().zone(-120)).zone(), -120, 'implicit cloning should retain the zone'); }); test('start of / end of', function (assert) { var a = moment.utc([2010, 1, 2, 0, 0, 0]).zone(450); assert.equal(a.clone().startOf('day').hour(), 0, 'start of day should work on moments with a zone'); assert.equal(a.clone().startOf('day').minute(), 0, 'start of day should work on moments with a zone'); assert.equal(a.clone().startOf('hour').minute(), 0, 'start of hour should work on moments with a zone'); assert.equal(a.clone().endOf('day').hour(), 23, 'end of day should work on moments with a zone'); assert.equal(a.clone().endOf('day').minute(), 59, 'end of day should work on moments with a zone'); assert.equal(a.clone().endOf('hour').minute(), 59, 'end of hour should work on moments with a zone'); }); test('reset zone with moment#utc', function (assert) { var a = moment.utc([2012]).zone(480); assert.equal(a.clone().hour(), 16, 'different zone should have different hour'); assert.equal(a.clone().utc().hour(), 0, 'calling moment#utc should reset the offset'); }); test('reset zone with moment#local', function (assert) { var a = moment([2012]).zone(480); assert.equal(a.clone().local().hour(), 0, 'calling moment#local should reset the offset'); }); test('toDate', function (assert) { var zoneA = new Date(), zoneB = moment(zoneA).zone(720).toDate(), zoneC = moment(zoneA).zone(360).toDate(), zoneD = moment(zoneA).zone(-690).toDate(); assert.equal(+zoneA, +zoneB, 'moment#toDate should output a date with the right unix timestamp'); assert.equal(+zoneA, +zoneC, 'moment#toDate should output a date with the right unix timestamp'); assert.equal(+zoneA, +zoneD, 'moment#toDate should output a date with the right unix timestamp'); }); test('same / before / after', function (assert) { var zoneA = moment().utc(), zoneB = moment(zoneA).zone(120), zoneC = moment(zoneA).zone(-120); assert.ok(zoneA.isSame(zoneB), 'two moments with different offsets should be the same'); assert.ok(zoneA.isSame(zoneC), 'two moments with different offsets should be the same'); assert.ok(zoneA.isSame(zoneB, 'hour'), 'two moments with different offsets should be the same hour'); assert.ok(zoneA.isSame(zoneC, 'hour'), 'two moments with different offsets should be the same hour'); zoneA.add(1, 'hour'); assert.ok(zoneA.isAfter(zoneB), 'isAfter should work with two moments with different offsets'); assert.ok(zoneA.isAfter(zoneC), 'isAfter should work with two moments with different offsets'); assert.ok(zoneA.isAfter(zoneB, 'hour'), 'isAfter:hour should work with two moments with different offsets'); assert.ok(zoneA.isAfter(zoneC, 'hour'), 'isAfter:hour should work with two moments with different offsets'); zoneA.subtract(2, 'hour'); assert.ok(zoneA.isBefore(zoneB), 'isBefore should work with two moments with different offsets'); assert.ok(zoneA.isBefore(zoneC), 'isBefore should work with two moments with different offsets'); assert.ok(zoneA.isBefore(zoneB, 'hour'), 'isBefore:hour should work with two moments with different offsets'); assert.ok(zoneA.isBefore(zoneC, 'hour'), 'isBefore:hour should work with two moments with different offsets'); }); test('add / subtract over dst', function (assert) { var oldOffset = moment.updateOffset, m = moment.utc([2000, 2, 31, 3]); moment.updateOffset = function (mom, keepTime) { if (mom.clone().utc().month() > 2) { mom.zone(-60, keepTime); } else { mom.zone(0, keepTime); } }; assert.equal(m.hour(), 3, 'should start at 00:00'); m.add(24, 'hour'); assert.equal(m.hour(), 4, 'adding 24 hours should disregard dst'); m.subtract(24, 'hour'); assert.equal(m.hour(), 3, 'subtracting 24 hours should disregard dst'); m.add(1, 'day'); assert.equal(m.hour(), 3, 'adding 1 day should have the same hour'); m.subtract(1, 'day'); assert.equal(m.hour(), 3, 'subtracting 1 day should have the same hour'); m.add(1, 'month'); assert.equal(m.hour(), 3, 'adding 1 month should have the same hour'); m.subtract(1, 'month'); assert.equal(m.hour(), 3, 'subtracting 1 month should have the same hour'); moment.updateOffset = oldOffset; }); test('isDST', function (assert) { var oldOffset = moment.updateOffset; moment.updateOffset = function (mom, keepTime) { if (mom.month() > 2 && mom.month() < 9) { mom.zone(-60, keepTime); } else { mom.zone(0, keepTime); } }; assert.ok(!moment().month(0).isDST(), 'Jan should not be summer dst'); assert.ok(moment().month(6).isDST(), 'Jul should be summer dst'); assert.ok(!moment().month(11).isDST(), 'Dec should not be summer dst'); moment.updateOffset = function (mom) { if (mom.month() > 2 && mom.month() < 9) { mom.zone(0); } else { mom.zone(-60); } }; assert.ok(moment().month(0).isDST(), 'Jan should be winter dst'); assert.ok(!moment().month(6).isDST(), 'Jul should not be winter dst'); assert.ok(moment().month(11).isDST(), 'Dec should be winter dst'); moment.updateOffset = oldOffset; }); test('zone names', function (assert) { test.expectedDeprecations(); assert.equal(moment().zoneAbbr(), '', 'Local zone abbr should be empty'); assert.equal(moment().format('z'), '', 'Local zone formatted abbr should be empty'); assert.equal(moment().zoneName(), '', 'Local zone name should be empty'); assert.equal(moment().format('zz'), '', 'Local zone formatted name should be empty'); assert.equal(moment.utc().zoneAbbr(), 'UTC', 'UTC zone abbr should be UTC'); assert.equal(moment.utc().format('z'), 'UTC', 'UTC zone formatted abbr should be UTC'); assert.equal(moment.utc().zoneName(), 'Coordinated Universal Time', 'UTC zone abbr should be Coordinated Universal Time'); assert.equal(moment.utc().format('zz'), 'Coordinated Universal Time', 'UTC zone formatted abbr should be Coordinated Universal Time'); }); test('hours alignment with UTC', function (assert) { assert.equal(moment().zone(120).hasAlignedHourOffset(), true); assert.equal(moment().zone(-180).hasAlignedHourOffset(), true); assert.equal(moment().zone(90).hasAlignedHourOffset(), false); assert.equal(moment().zone(-90).hasAlignedHourOffset(), false); }); test('hours alignment with other zone', function (assert) { var m = moment().zone(120); assert.equal(m.hasAlignedHourOffset(moment().zone(180)), true); assert.equal(m.hasAlignedHourOffset(moment().zone(-180)), true); assert.equal(m.hasAlignedHourOffset(moment().zone(90)), false); assert.equal(m.hasAlignedHourOffset(moment().zone(-90)), false); m = moment().zone(90); assert.equal(m.hasAlignedHourOffset(moment().zone(180)), false); assert.equal(m.hasAlignedHourOffset(moment().zone(-180)), false); assert.equal(m.hasAlignedHourOffset(moment().zone(30)), true); assert.equal(m.hasAlignedHourOffset(moment().zone(-30)), true); m = moment().zone(-60); assert.equal(m.hasAlignedHourOffset(moment().zone(180)), true); assert.equal(m.hasAlignedHourOffset(moment().zone(-180)), true); assert.equal(m.hasAlignedHourOffset(moment().zone(90)), false); assert.equal(m.hasAlignedHourOffset(moment().zone(-90)), false); m = moment().zone(25); assert.equal(m.hasAlignedHourOffset(moment().zone(-35)), true); assert.equal(m.hasAlignedHourOffset(moment().zone(85)), true); assert.equal(m.hasAlignedHourOffset(moment().zone(35)), false); assert.equal(m.hasAlignedHourOffset(moment().zone(-85)), false); }); test('parse zone', function (assert) { var m = moment('2013-01-01T00:00:00-13:00').parseZone(); assert.equal(m.zone(), 13 * 60); assert.equal(m.hours(), 0); }); test('parse zone static', function (assert) { var m = moment.parseZone('2013-01-01T00:00:00-13:00'); assert.equal(m.zone(), 13 * 60); assert.equal(m.hours(), 0); }); test('parse zone with more arguments', function (assert) { test.expectedDeprecations(); var m; m = moment.parseZone('2013 01 01 05 -13:00', 'YYYY MM DD HH ZZ'); assert.equal(m.format(), '2013-01-01T05:00:00-13:00', 'accept input and format'); m = moment.parseZone('2013-01-01-13:00', 'YYYY MM DD ZZ', true); assert.equal(m.isValid(), false, 'accept input, format and strict flag'); m = moment.parseZone('2013-01-01-13:00', ['DD MM YYYY ZZ', 'YYYY MM DD ZZ']); assert.equal(m.format(), '2013-01-01T00:00:00-13:00', 'accept input and array of formats'); }); test('parse zone with a timezone from the format string', function (assert) { var m = moment('11-12-2013 -0400 +1100', 'DD-MM-YYYY ZZ #####').parseZone(); assert.equal(m.zone(), 4 * 60); }); test('parse zone without a timezone included in the format string', function (assert) { var m = moment('11-12-2013 -0400 +1100', 'DD-MM-YYYY').parseZone(); assert.equal(m.zone(), -11 * 60); }); test('timezone format', function (assert) { assert.equal(moment().zone(-60).format('ZZ'), '+0100', '-60 -> +0100'); assert.equal(moment().zone(-90).format('ZZ'), '+0130', '-90 -> +0130'); assert.equal(moment().zone(-120).format('ZZ'), '+0200', '-120 -> +0200'); assert.equal(moment().zone(+60).format('ZZ'), '-0100', '+60 -> -0100'); assert.equal(moment().zone(+90).format('ZZ'), '-0130', '+90 -> -0130'); assert.equal(moment().zone(+120).format('ZZ'), '-0200', '+120 -> -0200'); }); })); ```
/content/code_sandbox/public/vendor/moment/min/tests.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
919,259
```html <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <style> body { font-family: Helvetica, Arial, sans-serif; line-height: 1.3em; -webkit-font-smoothing: antialiased; } .container { width: 90%; margin: 20px auto; background-color: #FFF; padding: 20px; } pre, code { font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: #333; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } pre { border: 1px solid #CCC; background-color: #EEE; color: #333; padding: 10px; overflow: scroll; } code { padding: 2px 4px; background-color: #F7F7F9; border: 1px solid #E1E1E8; color: #D14; } </style> </head> <body> <div class="container"> <h1>Click Demo</h1> <p>This demonstrates a commonly-asked question: how do I replace Backstretch's image once it's been called? The simple answer is, you can just call Backstretch again, and the image will be replaced.</p> <p><em>Note: Any options that you previously passed in will be preserved.</em></p> <p> <input type="button" id="pot-holder" value="Show Pot Holder Background" /> <input type="button" id="coffee" value="Show Coffee Background" /> </p> <pre>&lt;script src=&quot;//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;jquery.backstretch.min.js&quot;&gt;&lt;/script&gt; &lt;script&gt; $.backstretch(&quot;pot-holder.jpg&quot;, {speed: 500}); $(&quot;#pot-holder&quot;).click(function (e) { e.preventDefault(); $.backstretch(&quot;pot-holder.jpg&quot;); }); $(&quot;#coffee&quot;).click(function (e) { e.preventDefault(); $.backstretch(&quot;coffee.jpg&quot;); }); &lt;/script&gt;</pre> </div> <script src="../libs/jquery/jquery.js"></script> <script src="../src/jquery.backstretch.js"></script> <script> $.backstretch("pot-holder.jpg", {fade: 500}); $("#pot-holder").click(function (e) { e.preventDefault(); $.backstretch("pot-holder.jpg"); }); $("#coffee").click(function (e) { e.preventDefault(); $.backstretch("coffee.jpg"); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/jquery-backstretch/examples/click.html
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
648
```html <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <style> body { font-family: Helvetica, Arial, sans-serif; line-height: 1.3em; -webkit-font-smoothing: antialiased; } .container { width: 90%; margin: 20px auto; background-color: #FFF; padding: 20px; } pre, code { font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: #333; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } pre { border: 1px solid #CCC; background-color: #EEE; color: #333; padding: 10px; overflow: scroll; } code { padding: 2px 4px; background-color: #F7F7F9; border: 1px solid #E1E1E8; color: #D14; } .other { height: 300px; color: #FFF; } .other div { position: absolute; bottom: 0; width: 100%; background: #000; background: rgba(0,0,0,0.7); } .other div p { padding: 10px; } </style> </head> <body> <div class="container"> <h1>Basic Demo</h1> <p>In its simplest form, Backstretch can be called by passing in the path to an image, and it will be applied to the page's <code>body</code>.</p> <pre>&lt;script src=&quot;//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;jquery.backstretch.min.js&quot;&gt;&lt;/script&gt; &lt;script&gt; $.backstretch(&quot;pot-holder.jpg&quot;); &lt;/script&gt;</pre> <h2>Other Elements</h2> <p>Or, if you'd like, you can also attach Backstretch to another block level element on the page.</p> <div class="other"> <div><p>The background image on this element was set using Backstretch.</p></div> </div> <pre>&lt;script src=&quot;//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;jquery.backstretch.min.js&quot;&gt;&lt;/script&gt; &lt;script&gt; $(&quot;.other&quot;).backstretch(&quot;coffee.jpg&quot;); &lt;/script&gt;</pre> </div> <script src="../libs/jquery/jquery.js"></script> <script src="../src/jquery.backstretch.js"></script> <script> $.backstretch(["pot-holder.jpg"]); $(".other").backstretch("coffee.jpg"); </script> </body> </html> ```
/content/code_sandbox/public/vendor/jquery-backstretch/examples/basic.html
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
676
```html <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <style> body { font-family: Helvetica, Arial, sans-serif; line-height: 1.3em; -webkit-font-smoothing: antialiased; } .container { width: 90%; margin: 20px auto; background-color: #FFF; padding: 20px; } pre, code { font-family: Monaco, Menlo, Consolas, "Courier New", monospace; font-size: 12px; color: #333; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } pre { border: 1px solid #CCC; background-color: #EEE; color: #333; padding: 10px; overflow: scroll; } code { padding: 2px 4px; background-color: #F7F7F9; border: 1px solid #E1E1E8; color: #D14; } </style> </head> <body> <div class="container"> <h1>Slideshow Demo</h1> <p>This demonstrates a commonly-asked question: how do I use Backstretch to create a slideshow of background images? Easy! Just pass in an array of image paths.</p> <pre>&lt;script src=&quot;//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;jquery.backstretch.min.js&quot;&gt;&lt;/script&gt; &lt;script&gt; $.backstretch([ &quot;pot-holder.jpg&quot;, &quot;coffee.jpg&quot;, &quot;dome.jpg&quot; ], { fade: 750, duration: 4000 }); &lt;/script&gt;</pre> </div> <script src="../libs/jquery/jquery.js"></script> <script src="../src/jquery.backstretch.js"></script> <script> $.backstretch([ "pot-holder.jpg", "coffee.jpg", "dome.jpg" ], { fade: 750, duration: 4000 }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/jquery-backstretch/examples/slideshow.html
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
503
```javascript module.exports = function(grunt) { var sBanner = '/* your_sha256_hash------------- ' + '\n\n jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile' + '\n Version <%= pkg.version %>' + '\n Contributors : path_to_url + '\n Repository : path_to_url + '\n Documentation : path_to_url + '\n\n your_sha256_hash------------- */\n\n' // Project configuration. grunt.initConfig( { pkg: grunt.file.readJSON('package.json'), concat: { lang: { options: { separator: '\n\n\n\n', stripBanners: true, banner: sBanner }, src: ['src/i18n/*', '!src/i18n/DateTimePicker-i18n.js'], dest: 'src/i18n/DateTimePicker-i18n.js', nonull: true } }, copy: { main: { expand: true, cwd: 'src/', src: '**', dest: 'dist' }, lang: { expand: true, cwd: 'src/i18n', src: '**', dest: 'dist/i18n' } }, uglify: { options: { banner: sBanner, compress: { drop_console: true } }, build: { files: { 'dist/<%= pkg.name %>.min.js': ['src/<%= pkg.name %>.js'], 'dist/<%= pkg.name %>-ltie9.min.js': ['src/<%= pkg.name %>-ltie9.js'] } } }, cssmin: { options: { banner: sBanner }, build: { files: { 'dist/<%= pkg.name %>.min.css': ['src/<%= pkg.name %>.css'], 'dist/<%= pkg.name %>-ltie9.min.css': ['src/<%= pkg.name %>-ltie9.css'] } } }, jshint: { dist: { src: ['src/DateTimePicker.js'] }, options: { strict: false, curly: false, eqeqeq: true, eqnull: true, browser: true, devel: true, //unused: true, //undef: true, globals: { $: false, jQuery: false, define: false, require: false, module: false, DateTimePicker: true }, force: true } }, csslint: { dist: { src: ['src/DateTimePicker.css'] }, options: { "fallback-colors": false, "universal-selector": false, "box-sizing": false, "display-property-grouping": false } } }); // Load the plugin that provides the "uglify" task. grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-csslint'); // Default task(s). // grunt.registerTask('default', ['uglify', 'cssmin', 'copy']); grunt.registerTask('lang', ['concat:lang', 'copy:lang']); grunt.registerTask('lint', ['jshint', 'csslint']); }; ```
/content/code_sandbox/public/vendor/datetimepicker/Gruntfile.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
886
```css /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ .dtpicker-cont { top: 25%; } .dtpicker-overlay { /* For IE 8 */ -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#20000000,endColorstr=#20000000)"; /* For IE 5.5 to 7 */ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#20000000, endColorstr=#20000000); zoom: 1!important; } ```
/content/code_sandbox/public/vendor/datetimepicker/src/DateTimePicker-ltie9.css
css
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
159
```javascript /*! * jQuery Form Plugin * version: 3.46.0-2013.11.21 * Requires jQuery v1.5 or later * Examples and documentation at: path_to_url * Project repository: path_to_url * Dual licensed under the MIT and GPL licenses. * path_to_url#copyright-and-license */ /*global ActiveXObject */ // AMD support (function (factory) { if (typeof define === 'function' && define.amd) { // using AMD; register as anon module define(['jquery'], factory); } else { // no AMD; invoke directly factory( (typeof(jQuery) != 'undefined') ? jQuery : window.Zepto ); } } (function($) { "use strict"; /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are mutually exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').on('submit', function(e) { e.preventDefault(); // <-- important $(this).ajaxSubmit({ target: '#output' }); }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); You can also use ajaxForm with delegation (requires jQuery v1.7+), so the form does not have to exist when you invoke ajaxForm: $('#myForm').ajaxForm({ delegation: true, target: '#output' }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * Feature detection */ var feature = {}; feature.fileapi = $("<input type='file'/>").get(0).files !== undefined; feature.formdata = window.FormData !== undefined; var hasProp = !!$.fn.prop; // attr2 uses prop when it can but checks the return type for // an expected string. this accounts for the case where a form // contains inputs with names like "action" or "method"; in those // cases "prop" returns the element $.fn.attr2 = function() { if ( ! hasProp ) return this.attr.apply(this, arguments); var val = this.prop.apply(this, arguments); if ( ( val && val.jquery ) || typeof val === 'string' ) return val; return this.attr.apply(this, arguments); }; /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { /*jshint scripturl:true */ // fast fail if nothing selected (path_to_url if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } var method, action, url, $form = this; if (typeof options == 'function') { options = { success: options }; } else if ( options === undefined ) { options = {}; } method = options.type || this.attr2('method'); action = options.url || this.attr2('action'); url = (typeof action === 'string') ? $.trim(action) : ''; url = url || window.location.href || ''; if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^#]+)/)||[])[1]; } options = $.extend(true, { url: url, success: $.ajaxSettings.success, type: method || $.ajaxSettings.type, iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' }, options); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var traditional = options.traditional; if ( traditional === undefined ) { traditional = $.ajaxSettings.traditional; } var elements = []; var qx, a = this.formToArray(options.semantic, elements); if (options.data) { options.extraData = options.data; qx = $.param(options.data, traditional); } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a, traditional); if (qx) { q = ( q ? (q + '&' + qx) : qx ); } if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else { options.data = q; // data is the query string for 'post' } var callbacks = []; if (options.resetForm) { callbacks.push(function() { $form.resetForm(); }); } if (options.clearForm) { callbacks.push(function() { $form.clearForm(options.includeHidden); }); } // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { var fn = options.replaceTarget ? 'replaceWith' : 'html'; $(options.target)[fn](data).each(oldSuccess, arguments); }); } else if (options.success) { callbacks.push(options.success); } options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg var context = options.context || this ; // jQuery 1.4+ supports scope context for (var i=0, max=callbacks.length; i < max; i++) { callbacks[i].apply(context, [data, status, xhr || $form, $form]); } }; if (options.error) { var oldError = options.error; options.error = function(xhr, status, error) { var context = options.context || this; oldError.apply(context, [xhr, status, error, $form]); }; } if (options.complete) { var oldComplete = options.complete; options.complete = function(xhr, status) { var context = options.context || this; oldComplete.apply(context, [xhr, status, $form]); }; } // are there files to upload? // [value] (issue #113), also see comment: // path_to_url#commitcomment-2180219 var fileInputs = $('input[type=file]:enabled', this).filter(function() { return $(this).val() !== ''; }); var hasFileInputs = fileInputs.length > 0; var mp = 'multipart/form-data'; var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); var fileAPI = feature.fileapi && feature.formdata; log("fileAPI :" + fileAPI); var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI; var jqxhr; // options.iframe allows user to force iframe mode // 06-NOV-09: now defaulting to iframe mode if file input is detected if (options.iframe !== false && (options.iframe || shouldUseFrame)) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: path_to_url if (options.closeKeepAlive) { $.get(options.closeKeepAlive, function() { jqxhr = fileUploadIframe(a); }); } else { jqxhr = fileUploadIframe(a); } } else if ((hasFileInputs || multipart) && fileAPI) { jqxhr = fileUploadXhr(a); } else { jqxhr = $.ajax(options); } $form.removeData('jqxhr').data('jqxhr', jqxhr); // clear element array for (var k=0; k < elements.length; k++) elements[k] = null; // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // utility fn for deep serialization function deepSerialize(extraData){ var serialized = $.param(extraData, options.traditional).split('&'); var len = serialized.length; var result = []; var i, part; for (i=0; i < len; i++) { // #252; undo param space replacement serialized[i] = serialized[i].replace(/\+/g,' '); part = serialized[i].split('='); // #278; use array instead of object storage, favoring array serializations result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]); } return result; } // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz) function fileUploadXhr(a) { var formdata = new FormData(); for (var i=0; i < a.length; i++) { formdata.append(a[i].name, a[i].value); } if (options.extraData) { var serializedData = deepSerialize(options.extraData); for (i=0; i < serializedData.length; i++) if (serializedData[i]) formdata.append(serializedData[i][0], serializedData[i][1]); } options.data = null; var s = $.extend(true, {}, $.ajaxSettings, options, { contentType: false, processData: false, cache: false, type: method || 'POST' }); if (options.uploadProgress) { // workaround because jqXHR does not expose upload property s.xhr = function() { var xhr = $.ajaxSettings.xhr(); if (xhr.upload) { xhr.upload.addEventListener('progress', function(event) { var percent = 0; var position = event.loaded || event.position; /*event.position is deprecated*/ var total = event.total; if (event.lengthComputable) { percent = Math.ceil(position / total * 100); } options.uploadProgress(event, position, total, percent); }, false); } return xhr; }; } s.data = null; var beforeSend = s.beforeSend; s.beforeSend = function(xhr, o) { //Send FormData() provided by user if (options.formData) o.data = options.formData; else o.data = formdata; if(beforeSend) beforeSend.call(this, xhr, o); }; return $.ajax(s); } // private function for handling file uploads (hat tip to YAHOO!) function fileUploadIframe(a) { var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle; var deferred = $.Deferred(); // #341 deferred.abort = function(status) { xhr.abort(status); }; if (a) { // ensure that every serialized input is still enabled for (i=0; i < elements.length; i++) { el = $(elements[i]); if ( hasProp ) el.prop('disabled', false); else el.removeAttr('disabled'); } } s = $.extend(true, {}, $.ajaxSettings, options); s.context = s.context || s; id = 'jqFormIO' + (new Date().getTime()); if (s.iframeTarget) { $io = $(s.iframeTarget); n = $io.attr2('name'); if (!n) $io.attr2('name', id); else id = n; } else { $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />'); $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); } io = $io[0]; xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function(status) { var e = (status === 'timeout' ? 'timeout' : 'aborted'); log('aborting upload... ' + e); this.aborted = 1; try { // #214, #257 if (io.contentWindow.document.execCommand) { io.contentWindow.document.execCommand('Stop'); } } catch(ignore) {} $io.attr('src', s.iframeSrc); // abort op in progress xhr.error = e; if (s.error) s.error.call(s.context, xhr, e, status); if (g) $.event.trigger("ajaxError", [xhr, s, e]); if (s.complete) s.complete.call(s.context, xhr, e); } }; g = s.global; // trigger ajax global events so that activity/block indicators work like normal if (g && 0 === $.active++) { $.event.trigger("ajaxStart"); } if (g) { $.event.trigger("ajaxSend", [xhr, s]); } if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { if (s.global) { $.active--; } deferred.reject(); return deferred; } if (xhr.aborted) { deferred.reject(); return deferred; } // add submitting element to data if we know it sub = form.clk; if (sub) { n = sub.name; if (n && !sub.disabled) { s.extraData = s.extraData || {}; s.extraData[n] = sub.value; if (sub.type == "image") { s.extraData[n+'.x'] = form.clk_x; s.extraData[n+'.y'] = form.clk_y; } } } var CLIENT_TIMEOUT_ABORT = 1; var SERVER_ABORT = 2; function getDoc(frame) { /* it looks like contentWindow or contentDocument do not * carry the protocol property in ie8, when running under ssl * frame.document is the only valid response document, since * the protocol is know but not on the other two objects. strange? * "Same origin policy" path_to_url */ var doc = null; // IE8 cascading access check try { if (frame.contentWindow) { doc = frame.contentWindow.document; } } catch(err) { // IE8 access denied under ssl & missing protocol log('cannot get iframe.contentWindow document: ' + err); } if (doc) { // successful getting content return doc; } try { // simply checking may throw in ie8 under ssl or mismatched protocol doc = frame.contentDocument ? frame.contentDocument : frame.document; } catch(err) { // last attempt log('cannot get iframe.contentDocument: ' + err); doc = frame.document; } return doc; } // Rails CSRF hack (thanks to Yvan Barthelemy) var csrf_token = $('meta[name=csrf-token]').attr('content'); var csrf_param = $('meta[name=csrf-param]').attr('content'); if (csrf_param && csrf_token) { s.extraData = s.extraData || {}; s.extraData[csrf_param] = csrf_token; } // take a breath so that pending repaints get some cpu time before the upload starts function doSubmit() { // make sure form attrs are set var t = $form.attr2('target'), a = $form.attr2('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (!method || /post/i.test(method) ) { form.setAttribute('method', 'POST'); } if (a != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.skipEncodingOverride && (!method || /post/i.test(method))) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout); } // look for server aborts function checkState() { try { var state = getDoc(io).readyState; log('state = ' + state); if (state && state.toLowerCase() == 'uninitialized') setTimeout(checkState,50); } catch(e) { log('Server abort: ' , e, ' (', e.name, ')'); cb(SERVER_ABORT); if (timeoutHandle) clearTimeout(timeoutHandle); timeoutHandle = undefined; } } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { if (s.extraData.hasOwnProperty(n)) { // if using the $.param format that allows for multiple values with the same name if($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) { extraInputs.push( $('<input type="hidden" name="'+s.extraData[n].name+'">').val(s.extraData[n].value) .appendTo(form)[0]); } else { extraInputs.push( $('<input type="hidden" name="'+n+'">').val(s.extraData[n]) .appendTo(form)[0]); } } } } if (!s.iframeTarget) { // add iframe to doc and submit the form $io.appendTo('body'); } if (io.attachEvent) io.attachEvent('onload', cb); else io.addEventListener('load', cb, false); setTimeout(checkState,15); try { form.submit(); } catch(err) { // just in case form has element with name/id of 'submit' var submitFn = document.createElement('form').submit; submitFn.apply(form); } } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } } if (s.forceSync) { doSubmit(); } else { setTimeout(doSubmit, 10); // this lets dom updates render } var data, doc, domCheckCount = 50, callbackProcessed; function cb(e) { if (xhr.aborted || callbackProcessed) { return; } doc = getDoc(io); if(!doc) { log('cannot access response document'); e = SERVER_ABORT; } if (e === CLIENT_TIMEOUT_ABORT && xhr) { xhr.abort('timeout'); deferred.reject(xhr, 'timeout'); return; } else if (e == SERVER_ABORT && xhr) { xhr.abort('server abort'); deferred.reject(xhr, 'error', 'server abort'); return; } if (!doc || doc.location.href == s.iframeSrc) { // response not received yet if (!timedOut) return; } if (io.detachEvent) io.detachEvent('onload', cb); else io.removeEventListener('load', cb, false); var status = 'success', errMsg; try { if (timedOut) { throw 'timeout'; } var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml='+isXml); if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) { if (--domCheckCount) { // in some browsers (Opera) the iframe DOM is not always traversable when // the onload callback fires, so we loop a bit to accommodate log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } // let this fall through because server response could be an empty document //log('Could not access iframe DOM after mutiple tries.'); //throw 'DOMException: not available'; } //log('response detected'); var docRoot = doc.body ? doc.body : doc.documentElement; xhr.responseText = docRoot ? docRoot.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; if (isXml) s.dataType = 'xml'; xhr.getResponseHeader = function(header){ var headers = {'content-type': s.dataType}; return headers[header.toLowerCase()]; }; // support for XHR 'status' & 'statusText' emulation : if (docRoot) { xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status; xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText; } var dt = (s.dataType || '').toLowerCase(); var scr = /(json|script|text)/.test(dt); if (scr || s.textarea) { // see if user embedded response in textarea var ta = doc.getElementsByTagName('textarea')[0]; if (ta) { xhr.responseText = ta.value; // support for XHR 'status' & 'statusText' emulation : xhr.status = Number( ta.getAttribute('status') ) || xhr.status; xhr.statusText = ta.getAttribute('statusText') || xhr.statusText; } else if (scr) { // account for browsers injecting pre around json response var pre = doc.getElementsByTagName('pre')[0]; var b = doc.getElementsByTagName('body')[0]; if (pre) { xhr.responseText = pre.textContent ? pre.textContent : pre.innerText; } else if (b) { xhr.responseText = b.textContent ? b.textContent : b.innerText; } } } else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) { xhr.responseXML = toXml(xhr.responseText); } try { data = httpData(xhr, dt, s); } catch (err) { status = 'parsererror'; xhr.error = errMsg = (err || status); } } catch (err) { log('error caught: ',err); status = 'error'; xhr.error = errMsg = (err || status); } if (xhr.aborted) { log('upload aborted'); status = null; } if (xhr.status) { // we've set xhr.status status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error'; } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (status === 'success') { if (s.success) s.success.call(s.context, data, 'success', xhr); deferred.resolve(xhr.responseText, 'success', xhr); if (g) $.event.trigger("ajaxSuccess", [xhr, s]); } else if (status) { if (errMsg === undefined) errMsg = xhr.statusText; if (s.error) s.error.call(s.context, xhr, status, errMsg); deferred.reject(xhr, 'error', errMsg); if (g) $.event.trigger("ajaxError", [xhr, s, errMsg]); } if (g) $.event.trigger("ajaxComplete", [xhr, s]); if (g && ! --$.active) { $.event.trigger("ajaxStop"); } if (s.complete) s.complete.call(s.context, xhr, status); callbackProcessed = true; if (s.timeout) clearTimeout(timeoutHandle); // clean up setTimeout(function() { if (!s.iframeTarget) $io.remove(); else //adding else to clean up existing iframe response. $io.attr('src', s.iframeSrc); xhr.responseXML = null; }, 100); } var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+) if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else { doc = (new DOMParser()).parseFromString(s, 'text/xml'); } return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null; }; var parseJSON = $.parseJSON || function(s) { /*jslint evil:true */ return window['eval']('(' + s + ')'); }; var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4 var ct = xhr.getResponseHeader('content-type') || '', xml = type === 'xml' || !type && ct.indexOf('xml') >= 0, data = xml ? xhr.responseXML : xhr.responseText; if (xml && data.documentElement.nodeName === 'parsererror') { if ($.error) $.error('parsererror'); } if (s && s.dataFilter) { data = s.dataFilter(data, type); } if (typeof data === 'string') { if (type === 'json' || !type && ct.indexOf('json') >= 0) { data = parseJSON(data); } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { $.globalEval(data); } } return data; }; return deferred; } }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { options = options || {}; options.delegation = options.delegation && $.isFunction($.fn.on); // in jQuery 1.3+ we can fix mistakes with the ready state if (!options.delegation && this.length === 0) { var o = { s: this.selector, c: this.context }; if (!$.isReady && o.s) { log('DOM not ready, queuing ajaxForm'); $(function() { $(o.s,o.c).ajaxForm(options); }); return this; } // is your DOM ready? path_to_url log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } if ( options.delegation ) { $(document) .off('submit.form-plugin', this.selector, doAjaxSubmit) .off('click.form-plugin', this.selector, captureSubmittingElement) .on('submit.form-plugin', this.selector, options, doAjaxSubmit) .on('click.form-plugin', this.selector, options, captureSubmittingElement); return this; } return this.ajaxFormUnbind() .bind('submit.form-plugin', options, doAjaxSubmit) .bind('click.form-plugin', options, captureSubmittingElement); }; // private event handlers function doAjaxSubmit(e) { /*jshint validthis:true */ var options = e.data; if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(e.target).ajaxSubmit(options); // #365 } } function captureSubmittingElement(e) { /*jshint validthis:true */ var target = e.target; var $el = $(target); if (!($el.is("[type=submit],[type=image]"))) { // is this a child element of the submit el? (ex: a span within a button) var t = $el.closest('[type=submit]'); if (t.length === 0) { return; } target = t[0]; } var form = this; form.clk = target; if (target.type == 'image') { if (e.offsetX !== undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { var offset = $el.offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - target.offsetLeft; form.clk_y = e.pageY - target.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100); } // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { return this.unbind('submit.form-plugin click.form-plugin'); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic, elements) { var a = []; if (this.length === 0) { return a; } var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) { return a; } var i,j,n,v,el,max,jmax; for(i=0, max=els.length; i < max; i++) { el = els[i]; n = el.name; if (!n || el.disabled) { continue; } if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(form.clk == el) { a.push({name: n, value: $(el).val(), type: el.type }); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } continue; } v = $.fieldValue(el, true); if (v && v.constructor == Array) { if (elements) elements.push(el); for(j=0, jmax=v.length; j < jmax; j++) { a.push({name: n, value: v[j]}); } } else if (feature.fileapi && el.type == 'file') { if (elements) elements.push(el); var files = el.files; if (files.length) { for (j=0; j < files.length; j++) { a.push({name: n, value: files[j], type: el.type}); } } else { // #180 a.push({ name: n, value: '', type: el.type }); } } else if (v !== null && typeof v != 'undefined') { if (elements) elements.push(el); a.push({name: n, value: v, type: el.type, required: el.required}); } } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle it here var $input = $(form.clk), input = $input[0]; n = input.name; if (n && !input.disabled && input.type == 'image') { a.push({name: n, value: $input.val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) { return; } var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) { a.push({name: n, value: v[i]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: this.name, value: v}); } }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $('input[type=text]').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $('input[type=checkbox]').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $('input[type=radio]').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per path_to_url#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) { continue; } if (v.constructor == Array) $.merge(val, v); else val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (successful === undefined) { successful = true; } if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) { return null; } if (tag == 'select') { var index = el.selectedIndex; if (index < 0) { return null; } var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) { // extra pain for IE... v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value; } if (one) { return v; } a.push(v); } } return a; } return $(el).val(); }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function(includeHidden) { return this.each(function() { $('input,select,textarea', this).clearFields(includeHidden); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function(includeHidden) { var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (re.test(t) || tag == 'textarea') { this.value = ''; } else if (t == 'checkbox' || t == 'radio') { this.checked = false; } else if (tag == 'select') { this.selectedIndex = -1; } else if (t == "file") { if (/MSIE/.test(navigator.userAgent)) { $(this).replaceWith($(this).clone(true)); } else { $(this).val(''); } } else if (includeHidden) { // includeHidden can be the value true, or it can be a selector string // indicating a special test; for example: // $('#myForm').clearForm('.special:hidden') // the above would clean hidden inputs that have the class of 'special' if ( (includeHidden === true && /hidden/.test(t)) || (typeof includeHidden == 'string' && $(this).is(includeHidden)) ) this.value = ''; } }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) { this.reset(); } }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b === undefined) { b = true; } return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select === undefined) { select = true; } return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') { this.checked = select; } else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // expose debug var $.fn.ajaxSubmit.debug = false; // helper fn for console logging function log() { if (!$.fn.ajaxSubmit.debug) return; var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,''); if (window.console && window.console.log) { window.console.log(msg); } else if (window.opera && window.opera.postError) { window.opera.postError(msg); } } })); ```
/content/code_sandbox/public/vendor/jquery-form/jquery.form.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
9,350
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.17 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ $.DateTimePicker = $.DateTimePicker || { name: "DateTimePicker", i18n: {}, // Internationalization Objects defaults: //Plugin Defaults { mode: "date", defaultDate: new Date(), dateSeparator: "-", timeSeparator: ":", timeMeridiemSeparator: " ", dateTimeSeparator: " ", monthYearSeparator: " ", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", maxDate: null, minDate: null, maxTime: null, minTime: null, maxDateTime: null, minDateTime: null, shortDayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], fullDayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], shortMonthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], fullMonthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], minuteInterval: 1, roundOffMinutes: true, secondsInterval: 1, roundOffSeconds: true, titleContentDate: "Set Date", titleContentTime: "Set Time", titleContentDateTime: "Set Date & Time", buttonsToDisplay: ["HeaderCloseButton", "SetButton", "ClearButton"], setButtonContent: "Set", clearButtonContent: "Clear", incrementButtonContent: "+", decrementButtonContent: "-", setValueInTextboxOnEveryClick: false, animationDuration: 400, isPopup: true, parentElement: "body", language: "", init: null, // init(oDateTimePicker) addEventHandlers: null, // addEventHandlers(oDateTimePicker) beforeShow: null, // beforeShow(oInputElement) afterShow: null, // afterShow(oInputElement) beforeHide: null, // beforeHide(oInputElement) afterHide: null, // afterHide(oInputElement) buttonClicked: null, // buttonClicked(sButtonType, oInputElement) where sButtonType = "SET"|"CLEAR"|"CANCEL" formatHumanDate: null, // formatHumanDate(oDate, sMode, sFormat) parseDateTimeString: null, // parseDateTimeString(sDateTime, sMode, oInputElement) formatDateTimeString: null, // formatDateTimeString(oFormat, sMode, oInputElement) }, dataObject: // Temporary Variables For Calculation Specific to DateTimePicker Instance { dCurrentDate: new Date(), iCurrentDay: 0, iCurrentMonth: 0, iCurrentYear: 0, iCurrentHour: 0, iCurrentMinutes: 0, iCurrentSeconds: 0, sCurrentMeridiem: "", iMaxNumberOfDays: 0, sDateFormat: "", sTimeFormat: "", sDateTimeFormat: "", dMinValue: null, dMaxValue: null, sArrInputDateFormats: [], sArrInputTimeFormats: [], sArrInputDateTimeFormats: [], bArrMatchFormat: [], bDateMode: false, bTimeMode: false, bDateTimeMode: false, oInputElement: null, iTabIndex: 0, bElemFocused: false, bIs12Hour: false } }; $.cf = { _isValid: function(sValue) { return (sValue !== undefined && sValue !== null && sValue !== ""); }, _compare: function(sString1, sString2) { var bString1 = (sString1 !== undefined && sString1 !== null), bString2 = (sString2 !== undefined && sString2 !== null); if(bString1 && bString2) { if(sString1.toLowerCase() === sString2.toLowerCase()) return true; else return false; } else return false; } }; var sLibrary = "zepto"; (function (factory) { if(typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([sLibrary], factory); } else if(typeof exports === 'object') { // Node/CommonJS module.exports = factory(require(sLibrary)); } else { // Browser globals if(sLibrary === "zepto") factory(Zepto); else if(sLibrary === "jquery") factory(jQuery); } }(function ($) { "use strict"; function DateTimePicker(element, options) { this.element = element; var sLanguage = ""; sLanguage = ($.cf._isValid(options) && $.cf._isValid(options.language)) ? options.language : $.DateTimePicker.defaults.language; this.settings = $.extend({}, $.DateTimePicker.defaults, options, $.DateTimePicker.i18n[sLanguage]); this.oData = $.extend({}, $.DateTimePicker.dataObject); this._defaults = $.DateTimePicker.defaults; this._name = $.DateTimePicker.name; this.init(); } $.fn.DateTimePicker = function (options) { var oDTP = $(this).data(), sArrDataKeys = Object.keys(oDTP), iKey, sKey; if(typeof options === "string") { if($.cf._isValid(oDTP)) { if(options === "destroy") { if(sArrDataKeys.length > 0) { for(iKey in sArrDataKeys) { sKey = sArrDataKeys[iKey]; if(sKey.search("plugin_DateTimePicker") !== -1) { $(document).unbind("click.DateTimePicker"); $(document).unbind("keydown.DateTimePicker"); $(document).unbind("keyup.DateTimePicker"); $(this).children().remove(); $(this).removeData(); $(this).unbind(); $(this).removeClass("dtpicker-overlay dtpicker-mobile"); oDTP = oDTP[sKey]; console.log("Destroyed DateTimePicker Object"); console.log(oDTP); break; } } } else { console.log("No DateTimePicker Object Defined For This Element"); } } else if(options === "object") { if(sArrDataKeys.length > 0) { for(iKey in sArrDataKeys) { sKey = sArrDataKeys[iKey]; if(sKey.search("plugin_DateTimePicker") !== -1) { return oDTP[sKey]; } } } else { console.log("No DateTimePicker Object Defined For This Element"); } } } } else { return this.each(function() { $(this).removeData("plugin_DateTimePicker"); if(!$(this).data("plugin_DateTimePicker")) $(this).data("plugin_DateTimePicker", new DateTimePicker(this, options)); }); } }; DateTimePicker.prototype = { // Public Method init: function () { var oDTP = this; oDTP._setDateFormatArray(); // Set DateFormatArray oDTP._setTimeFormatArray(); // Set TimeFormatArray oDTP._setDateTimeFormatArray(); // Set DateTimeFormatArray if(oDTP.settings.isPopup) { oDTP._createPicker(); $(oDTP.element).addClass("dtpicker-mobile"); } if(oDTP.settings.init) oDTP.settings.init.call(oDTP); oDTP._addEventHandlersForInput(); }, _setDateFormatArray: function() { var oDTP = this; oDTP.oData.sArrInputDateFormats = []; var sDate = ""; // "dd-MM-yyyy" sDate = "dd" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "yyyy"; oDTP.oData.sArrInputDateFormats.push(sDate); // "MM-dd-yyyy" sDate = "MM" + oDTP.settings.dateSeparator + "dd" + oDTP.settings.dateSeparator + "yyyy"; oDTP.oData.sArrInputDateFormats.push(sDate); // "yyyy-MM-dd" sDate = "yyyy" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "dd"; oDTP.oData.sArrInputDateFormats.push(sDate); // "dd-MMM-yyyy" sDate = "dd" + oDTP.settings.dateSeparator + "MMM" + oDTP.settings.dateSeparator + "yyyy"; oDTP.oData.sArrInputDateFormats.push(sDate); // "MM yyyy" sDate = "MM" + oDTP.settings.monthYearSeparator + "yyyy"; oDTP.oData.sArrInputDateFormats.push(sDate); // "MMM yyyy" sDate = "MMM" + oDTP.settings.monthYearSeparator + "yyyy"; oDTP.oData.sArrInputDateFormats.push(sDate); // "MMM yyyy" sDate = "MMMM" + oDTP.settings.monthYearSeparator + "yyyy"; oDTP.oData.sArrInputDateFormats.push(sDate); }, _setTimeFormatArray: function() { var oDTP = this; oDTP.oData.sArrInputTimeFormats = []; var sTime = ""; // "hh:mm:ss AA" sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss" + oDTP.settings.timeMeridiemSeparator + "AA"; oDTP.oData.sArrInputTimeFormats.push(sTime); // "HH:mm:ss" sTime = "HH" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss"; oDTP.oData.sArrInputTimeFormats.push(sTime); // "hh:mm AA" sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeMeridiemSeparator + "AA"; oDTP.oData.sArrInputTimeFormats.push(sTime); // "HH:mm" sTime = "HH" + oDTP.settings.timeSeparator + "mm"; oDTP.oData.sArrInputTimeFormats.push(sTime); }, _setDateTimeFormatArray: function() { var oDTP = this; oDTP.oData.sArrInputDateTimeFormats = []; var sDate = "", sTime = "", sDateTime = ""; // "dd-MM-yyyy HH:mm:ss" sDate = "dd" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "yyyy"; sTime = "HH" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // "dd-MM-yyyy hh:mm:ss AA" sDate = "dd" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "yyyy"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss" + oDTP.settings.timeMeridiemSeparator + "AA"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // "MM-dd-yyyy HH:mm:ss" sDate = "MM" + oDTP.settings.dateSeparator + "dd" + oDTP.settings.dateSeparator + "yyyy"; sTime = "HH" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // "MM-dd-yyyy hh:mm:ss AA" sDate = "MM" + oDTP.settings.dateSeparator + "dd" + oDTP.settings.dateSeparator + "yyyy"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss" + oDTP.settings.timeMeridiemSeparator + "AA"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // "yyyy-MM-dd HH:mm:ss" sDate = "yyyy" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "dd"; sTime = "HH" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // "yyyy-MM-dd hh:mm:ss AA" sDate = "yyyy" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "dd"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss" + oDTP.settings.timeMeridiemSeparator + "AA"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // "dd-MMM-yyyy hh:mm:ss" sDate = "dd" + oDTP.settings.dateSeparator + "MMM" + oDTP.settings.dateSeparator + "yyyy"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // "dd-MMM-yyyy hh:mm:ss AA" sDate = "dd" + oDTP.settings.dateSeparator + "MMM" + oDTP.settings.dateSeparator + "yyyy"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss" + oDTP.settings.timeMeridiemSeparator + "AA"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); //-------------- // "dd-MM-yyyy HH:mm" sDate = "dd" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "yyyy"; sTime = "HH" + oDTP.settings.timeSeparator + "mm"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // "dd-MM-yyyy hh:mm AA" sDate = "dd" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "yyyy"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeMeridiemSeparator + "AA"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // "MM-dd-yyyy HH:mm" sDate = "MM" + oDTP.settings.dateSeparator + "dd" + oDTP.settings.dateSeparator + "yyyy"; sTime = "HH" + oDTP.settings.timeSeparator + "mm"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // "MM-dd-yyyy hh:mm AA" sDate = "MM" + oDTP.settings.dateSeparator + "dd" + oDTP.settings.dateSeparator + "yyyy"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeMeridiemSeparator + "AA"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // "yyyy-MM-dd HH:mm" sDate = "yyyy" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "dd"; sTime = "HH" + oDTP.settings.timeSeparator + "mm"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // "yyyy-MM-dd hh:mm AA" sDate = "yyyy" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "dd"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeMeridiemSeparator + "AA"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // "dd-MMM-yyyy hh:mm" sDate = "dd" + oDTP.settings.dateSeparator + "MMM" + oDTP.settings.dateSeparator + "yyyy"; sTime = "hh" + oDTP.settings.timeSeparator + "mm"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // "dd-MMM-yyyy hh:mm AA" sDate = "dd" + oDTP.settings.dateSeparator + "MMM" + oDTP.settings.dateSeparator + "yyyy"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeMeridiemSeparator + "AA"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); }, _matchFormat: function(sMode, sFormat) { var oDTP = this; oDTP.oData.bArrMatchFormat = []; oDTP.oData.bDateMode = false; oDTP.oData.bTimeMode = false; oDTP.oData.bDateTimeMode = false; var oArrInput = [], iTempIndex; sMode = $.cf._isValid(sMode) ? sMode : oDTP.settings.mode; if($.cf._compare(sMode, "date")) { sFormat = $.cf._isValid(sFormat) ? sFormat : oDTP.oData.sDateFormat; oDTP.oData.bDateMode = true; oArrInput = oDTP.oData.sArrInputDateFormats; } else if($.cf._compare(sMode, "time")) { sFormat = $.cf._isValid(sFormat) ? sFormat : oDTP.oData.sTimeFormat; oDTP.oData.bTimeMode = true; oArrInput = oDTP.oData.sArrInputTimeFormats; } else if($.cf._compare(sMode, "datetime")) { sFormat = $.cf._isValid(sFormat) ? sFormat : oDTP.oData.sDateTimeFormat; oDTP.oData.bDateTimeMode = true; oArrInput = oDTP.oData.sArrInputDateTimeFormats; } for(iTempIndex = 0; iTempIndex < oArrInput.length; iTempIndex++) { oDTP.oData.bArrMatchFormat.push( $.cf._compare(sFormat, oArrInput[iTempIndex]) ); } }, _setMatchFormat: function(iArgsLength, sMode, sFormat) { var oDTP = this; if(iArgsLength > 0) oDTP._matchFormat(sMode, sFormat); }, _createPicker: function() { var oDTP = this; $(oDTP.element).addClass("dtpicker-overlay"); $(".dtpicker-overlay").click(function(e) { oDTP._hidePicker(""); }); var sTempStr = ""; sTempStr += "<div class='dtpicker-bg'>"; sTempStr += "<div class='dtpicker-cont'>"; sTempStr += "<div class='dtpicker-content'>"; sTempStr += "<div class='dtpicker-subcontent'>"; sTempStr += "</div>"; sTempStr += "</div>"; sTempStr += "</div>"; sTempStr += "</div>"; $(oDTP.element).html(sTempStr); }, _addEventHandlersForInput: function() { var oDTP = this; oDTP.oData.oInputElement = null; $(oDTP.settings.parentElement).find("input[type='date'], input[type='time'], input[type='datetime']").each(function() { $(this).attr("data-field", $(this).attr("type")); $(this).attr("type", "text"); }); var sel = "[data-field='date'], [data-field='time'], [data-field='datetime']"; $(oDTP.settings.parentElement).off("focus", sel, oDTP._inputFieldFocus); $(oDTP.settings.parentElement).on ("focus", sel, {"obj": oDTP}, oDTP._inputFieldFocus); $(oDTP.settings.parentElement).off("click", sel, oDTP._inputFieldClick); $(oDTP.settings.parentElement).on ("click", sel, {"obj": oDTP}, oDTP._inputFieldClick); if(oDTP.settings.addEventHandlers) //this is not an event-handler really. Its just a function called oDTP.settings.addEventHandlers.call(oDTP); // which could add EventHandlers }, _inputFieldFocus: function(e) { var oDTP = e.data.obj; oDTP.showDateTimePicker(this); oDTP.oData.bMouseDown = false; }, _inputFieldClick: function(e) { var oDTP = e.data.obj; if(!$.cf._compare($(this).prop("tagName"), "input")) { oDTP.showDateTimePicker(this); } e.stopPropagation(); }, // Public Method setDateTimeStringInInputField: function(oInputField, dInput) { var oDTP = this; dInput = dInput || oDTP.oData.dCurrentDate; var oArrElements; if($.cf._isValid(oInputField)) { oArrElements = []; if(typeof oInputField === "string") oArrElements.push(oInputField); else if(typeof oInputField === "object") oArrElements = oInputField; } else { if($.cf._isValid(oDTP.settings.parentElement)) { oArrElements = $(oDTP.settings.parentElement).find("[data-field='date'], [data-field='time'], [data-field='datetime']"); } else { oArrElements = $("[data-field='date'], [data-field='time'], [data-field='datetime']"); } } oArrElements.each(function() { var oElement = this, sMode, sFormat, bIs12Hour, sOutput; sMode = $(oElement).data("field"); if(!$.cf._isValid(sMode)) sMode = oDTP.settings.mode; sFormat = $(oElement).data("format"); if(!$.cf._isValid(sFormat)) { if($.cf._compare(sMode, "date")) sFormat = oDTP.settings.dateFormat; else if($.cf._compare(sMode, "time")) sFormat = oDTP.settings.timeFormat; else if($.cf._compare(sMode, "datetime")) sFormat = oDTP.settings.dateTimeFormat; } bIs12Hour = oDTP.getIs12Hour(sMode, sFormat); sOutput = oDTP._setOutput(sMode, sFormat, bIs12Hour, dInput); $(oElement).val(sOutput); }); }, // Public Method getDateTimeStringInFormat: function(sMode, sFormat, dInput) { var oDTP = this; return oDTP._setOutput(sMode, sFormat, oDTP.getIs12Hour(sMode, sFormat), dInput); }, // Public Method showDateTimePicker: function(oElement) { var oDTP = this; if(oDTP.oData.oInputElement !== null) oDTP._hidePicker(0, oElement); else oDTP._showPicker(oElement); }, _setButtonAction: function(bFromTab) { var oDTP = this; if(oDTP.oData.oInputElement !== null) { oDTP._setValueOfElement(oDTP._setOutput()); if(bFromTab) oDTP._hidePicker(0); else oDTP._hidePicker(""); } }, _setOutput: function(sMode, sFormat, bIs12Hour, dCurrentDate) { var oDTP = this; dCurrentDate = $.cf._isValid(dCurrentDate) ? dCurrentDate : oDTP.oData.dCurrentDate; bIs12Hour = bIs12Hour || oDTP.oData.bIs12Hour; var sOutput = "", iDate = dCurrentDate.getDate(), iMonth = dCurrentDate.getMonth(), iYear = dCurrentDate.getFullYear(), iHour = dCurrentDate.getHours(), iMinutes = dCurrentDate.getMinutes(), iSeconds = dCurrentDate.getSeconds(), sDate, sMonth, sMeridiem, sHour, sMinutes, sSeconds, sDateStr = "", sTimeStr = "", iArgsLength = Function.length, bAddSeconds; // Set bDate, bTime, bDateTime & bArrMatchFormat based on arguments of this function oDTP._setMatchFormat(iArgsLength, sMode, sFormat); if(oDTP.oData.bDateMode) { if(oDTP.oData.bArrMatchFormat[0]) { iMonth++; sDate = (iDate < 10) ? ("0" + iDate) : iDate; sMonth = (iMonth < 10) ? ("0" + iMonth) : iMonth; sOutput = sDate + oDTP.settings.dateSeparator + sMonth + oDTP.settings.dateSeparator + iYear; } else if(oDTP.oData.bArrMatchFormat[1]) { iMonth++; sDate = (iDate < 10) ? ("0" + iDate) : iDate; sMonth = (iMonth < 10) ? ("0" + iMonth) : iMonth; sOutput = sMonth + oDTP.settings.dateSeparator + sDate + oDTP.settings.dateSeparator + iYear; } else if(oDTP.oData.bArrMatchFormat[2]) { iMonth++; sDate = (iDate < 10) ? ("0" + iDate) : iDate; sMonth = (iMonth < 10) ? ("0" + iMonth) : iMonth; sOutput = iYear + oDTP.settings.dateSeparator + sMonth + oDTP.settings.dateSeparator + sDate; } else if(oDTP.oData.bArrMatchFormat[3]) { sDate = (iDate < 10) ? ("0" + iDate) : iDate; sMonth = oDTP.settings.shortMonthNames[iMonth]; sOutput = sDate + oDTP.settings.dateSeparator + sMonth + oDTP.settings.dateSeparator + iYear; } else if(oDTP.oData.bArrMatchFormat[4]) { iDate = 1; iMonth++; sMonth = (iMonth < 10) ? ("0" + iMonth) : iMonth; sOutput = sMonth + oDTP.settings.monthYearSeparator + iYear; } else if(oDTP.oData.bArrMatchFormat[5]) { iDate = 1; sMonth = oDTP.settings.shortMonthNames[iMonth]; sOutput = sMonth + oDTP.settings.monthYearSeparator + iYear; } else if(oDTP.oData.bArrMatchFormat[6]) { iDate = 1; sMonth = oDTP.settings.fullMonthNames[iMonth]; sOutput = sMonth + oDTP.settings.monthYearSeparator + iYear; } } else if(oDTP.oData.bTimeMode) { if(oDTP.oData.bArrMatchFormat[0] || oDTP.oData.bArrMatchFormat[2]) { sMeridiem = oDTP._determineMeridiemFromHourAndMinutes(iHour, iMinutes); if(iHour === 0 && sMeridiem === "AM") iHour = 12; else if(iHour > 12 && sMeridiem === "PM") iHour -= 12; } sHour = (iHour < 10) ? ("0" + iHour) : iHour; sMinutes = (iMinutes < 10) ? ("0" + iMinutes) : iMinutes; if(oDTP.oData.bArrMatchFormat[0]) { sSeconds = (iSeconds < 10) ? ("0" + iSeconds) : iSeconds; sOutput = sHour + oDTP.settings.timeSeparator + sMinutes + oDTP.settings.timeSeparator + sSeconds + oDTP.settings.timeMeridiemSeparator + sMeridiem; } else if(oDTP.oData.bArrMatchFormat[1]) { sSeconds = (iSeconds < 10) ? ("0" + iSeconds) : iSeconds; sOutput = sHour + oDTP.settings.timeSeparator + sMinutes + oDTP.settings.timeSeparator + sSeconds; } else if(oDTP.oData.bArrMatchFormat[2]) { sOutput = sHour + oDTP.settings.timeSeparator + sMinutes + oDTP.settings.timeMeridiemSeparator + sMeridiem; } else if(oDTP.oData.bArrMatchFormat[3]) { sOutput = sHour + oDTP.settings.timeSeparator + sMinutes; } } else if(oDTP.oData.bDateTimeMode) { // Date Part - "dd-MM-yyyy" if(oDTP.oData.bArrMatchFormat[0] || oDTP.oData.bArrMatchFormat[1] || oDTP.oData.bArrMatchFormat[8] || oDTP.oData.bArrMatchFormat[9]) { iMonth++; sDate = (iDate < 10) ? ("0" + iDate) : iDate; sMonth = (iMonth < 10) ? ("0" + iMonth) : iMonth; sDateStr = sDate + oDTP.settings.dateSeparator + sMonth + oDTP.settings.dateSeparator + iYear; } // Date Part - "MM-dd-yyyy" else if(oDTP.oData.bArrMatchFormat[2] || oDTP.oData.bArrMatchFormat[3] || oDTP.oData.bArrMatchFormat[10] || oDTP.oData.bArrMatchFormat[11]) { iMonth++; sDate = (iDate < 10) ? ("0" + iDate) : iDate; sMonth = (iMonth < 10) ? ("0" + iMonth) : iMonth; sDateStr = sMonth + oDTP.settings.dateSeparator + sDate + oDTP.settings.dateSeparator + iYear; } // Date Part - "yyyy-MM-dd" else if(oDTP.oData.bArrMatchFormat[4] || oDTP.oData.bArrMatchFormat[5] || oDTP.oData.bArrMatchFormat[12] || oDTP.oData.bArrMatchFormat[13]) { iMonth++; sDate = (iDate < 10) ? ("0" + iDate) : iDate; sMonth = (iMonth < 10) ? ("0" + iMonth) : iMonth; sDateStr = iYear + oDTP.settings.dateSeparator + sMonth + oDTP.settings.dateSeparator + sDate; } // Date Part - "dd-MMM-yyyy" else if(oDTP.oData.bArrMatchFormat[6] || oDTP.oData.bArrMatchFormat[7] || oDTP.oData.bArrMatchFormat[14] || oDTP.oData.bArrMatchFormat[15]) { sDate = (iDate < 10) ? ("0" + iDate) : iDate; sMonth = oDTP.settings.shortMonthNames[iMonth]; sDateStr = sDate + oDTP.settings.dateSeparator + sMonth + oDTP.settings.dateSeparator + iYear; } bAddSeconds = oDTP.oData.bArrMatchFormat[0] || oDTP.oData.bArrMatchFormat[1] || oDTP.oData.bArrMatchFormat[2] || oDTP.oData.bArrMatchFormat[3] || oDTP.oData.bArrMatchFormat[4] || oDTP.oData.bArrMatchFormat[5] || oDTP.oData.bArrMatchFormat[6] || oDTP.oData.bArrMatchFormat[7]; if(bIs12Hour) { sMeridiem = oDTP._determineMeridiemFromHourAndMinutes(iHour, iMinutes); if(iHour === 0 && sMeridiem === "AM") iHour = 12; else if(iHour > 12 && sMeridiem === "PM") iHour -= 12; sHour = (iHour < 10) ? ("0" + iHour) : iHour; sMinutes = (iMinutes < 10) ? ("0" + iMinutes) : iMinutes; if(bAddSeconds) { sSeconds = (iSeconds < 10) ? ("0" + iSeconds) : iSeconds; sTimeStr = sHour + oDTP.settings.timeSeparator + sMinutes + oDTP.settings.timeSeparator + sSeconds + oDTP.settings.timeMeridiemSeparator + sMeridiem; } else { sTimeStr = sHour + oDTP.settings.timeSeparator + sMinutes + oDTP.settings.timeMeridiemSeparator + sMeridiem; } } else { sHour = (iHour < 10) ? ("0" + iHour) : iHour; sMinutes = (iMinutes < 10) ? ("0" + iMinutes) : iMinutes; if(bAddSeconds) { sSeconds = (iSeconds < 10) ? ("0" + iSeconds) : iSeconds; sTimeStr = sHour + oDTP.settings.timeSeparator + sMinutes + oDTP.settings.timeSeparator + sSeconds; } else { sTimeStr = sHour + oDTP.settings.timeSeparator + sMinutes; } } sOutput = sDateStr + oDTP.settings.dateTimeSeparator + sTimeStr; } // Reset bDate, bTime, bDateTime & bArrMatchFormat to original values oDTP._setMatchFormat(iArgsLength); return sOutput; }, _clearButtonAction: function() { var oDTP = this; if(oDTP.oData.oInputElement !== null) { oDTP._setValueOfElement(""); } oDTP._hidePicker(""); }, _setOutputOnIncrementOrDecrement: function() { var oDTP = this; if($.cf._isValid(oDTP.oData.oInputElement) && oDTP.settings.setValueInTextboxOnEveryClick) { oDTP._setValueOfElement(oDTP._setOutput()); } }, _showPicker: function(oElement) { var oDTP = this; if(oDTP.oData.oInputElement === null) { oDTP.oData.oInputElement = oElement; oDTP.oData.iTabIndex = parseInt($(oElement).attr("tabIndex")); var sMode = $(oElement).data("field") || "", sMinValue = $(oElement).data("min") || "", sMaxValue = $(oElement).data("max") || "", sFormat = $(oElement).data("format") || "", sView = $(oElement).data("view") || "", sStartEnd = $(oElement).data("startend") || "", sStartEndElem = $(oElement).data("startendelem") || "", sCurrent = oDTP._getValueOfElement(oElement) || ""; if(sView !== "") { if($.cf._compare(sView, "Popup")) oDTP.setIsPopup(true); else oDTP.setIsPopup(false); } if(!oDTP.settings.isPopup) { oDTP._createPicker(); var iElemTop = $(oDTP.oData.oInputElement).offset().top + $(oDTP.oData.oInputElement).outerHeight(), iElemLeft = $(oDTP.oData.oInputElement).offset().left, iElemWidth = $(oDTP.oData.oInputElement).outerWidth(); $(oDTP.element).css({position: "absolute", top: iElemTop, left: iElemLeft, width: iElemWidth, height: "auto"}); } if(oDTP.settings.beforeShow) oDTP.settings.beforeShow.call(oDTP, oElement); sMode = $.cf._isValid(sMode) ? sMode : oDTP.settings.mode; oDTP.settings.mode = sMode; if(!$.cf._isValid(sFormat)) { if($.cf._compare(sMode, "date")) sFormat = oDTP.settings.dateFormat; else if($.cf._compare(sMode, "time")) sFormat = oDTP.settings.timeFormat; else if($.cf._compare(sMode, "datetime")) sFormat = oDTP.settings.dateTimeFormat; } oDTP._matchFormat(sMode, sFormat); oDTP.oData.dMinValue = null; oDTP.oData.dMaxValue = null; oDTP.oData.bIs12Hour = false; var sMin, sMax, sTempDate, dTempDate, sTempTime, dTempTime, sTempDateTime, dTempDateTime; if(oDTP.oData.bDateMode) { sMin = sMinValue || oDTP.settings.minDate; sMax = sMaxValue || oDTP.settings.maxDate; oDTP.oData.sDateFormat = sFormat; if($.cf._isValid(sMin)) oDTP.oData.dMinValue = oDTP._parseDate(sMin); if($.cf._isValid(sMax)) oDTP.oData.dMaxValue = oDTP._parseDate(sMax); if(sStartEnd !== "" && ($.cf._compare(sStartEnd, "start") || $.cf._compare(sStartEnd, "end")) && sStartEndElem !== "") { if($(sStartEndElem).length >= 1) { sTempDate = oDTP._getValueOfElement($(sStartEndElem)); if(sTempDate !== "") { if(oDTP.settings.parseDateTimeString) dTempDate = oDTP.settings.parseDateTimeString.call(oDTP, sTempDate, sMode, $(sStartEndElem)); else dTempDate = oDTP._parseDate(sTempDate); if($.cf._compare(sStartEnd, "start")) { if($.cf._isValid(sMax)) { if(oDTP._compareDates(dTempDate, oDTP.oData.dMaxValue) < 0) oDTP.oData.dMaxValue = new Date(dTempDate); } else oDTP.oData.dMaxValue = new Date(dTempDate); } else if($.cf._compare(sStartEnd, "end")) { if($.cf._isValid(sMin)) { if(oDTP._compareDates(dTempDate, oDTP.oData.dMinValue) > 0) oDTP.oData.dMinValue = new Date(dTempDate); } else oDTP.oData.dMinValue = new Date(dTempDate); } } } } if(oDTP.settings.parseDateTimeString) oDTP.oData.dCurrentDate = oDTP.settings.parseDateTimeString.call(oDTP, sCurrent, sMode, $(oElement)); else oDTP.oData.dCurrentDate = oDTP._parseDate(sCurrent); oDTP.oData.dCurrentDate.setHours(0); oDTP.oData.dCurrentDate.setMinutes(0); oDTP.oData.dCurrentDate.setSeconds(0); } else if(oDTP.oData.bTimeMode) { sMin = sMinValue || oDTP.settings.minTime; sMax = sMaxValue || oDTP.settings.maxTime; oDTP.oData.sTimeFormat = sFormat; if($.cf._isValid(sMin)) oDTP.oData.dMinValue = oDTP._parseTime(sMin); if($.cf._isValid(sMax)) oDTP.oData.dMaxValue = oDTP._parseTime(sMax); if(sStartEnd !== "" && ($.cf._compare(sStartEnd, "start") || $.cf._compare(sStartEnd, "end")) && sStartEndElem !== "") { if($(sStartEndElem).length >= 1) { sTempTime = oDTP._getValueOfElement($(sStartEndElem)); if(sTempTime !== "") { if(oDTP.settings.parseDateTimeString) dTempDate = oDTP.settings.parseDateTimeString.call(oDTP, sTempTime, sMode, $(sStartEndElem)); else dTempTime = oDTP._parseTime(sTempTime); if($.cf._compare(sStartEnd, "start")) { dTempTime.setMinutes(dTempTime.getMinutes() - 1); if($.cf._isValid(sMax)) { if(oDTP._compareTime(dTempTime, oDTP.oData.dMaxValue) === 2) oDTP.oData.dMaxValue = new Date(dTempTime); } else oDTP.oData.dMaxValue = new Date(dTempTime); } else if($.cf._compare(sStartEnd, "end")) { dTempTime.setMinutes(dTempTime.getMinutes() + 1); if($.cf._isValid(sMin)) { if(oDTP._compareTime(dTempTime, oDTP.oData.dMinValue) === 3) oDTP.oData.dMinValue = new Date(dTempTime); } else oDTP.oData.dMinValue = new Date(dTempTime); } } } } oDTP.oData.bIs12Hour = oDTP.getIs12Hour(); if(oDTP.settings.parseDateTimeString) oDTP.oData.dCurrentDate = oDTP.settings.parseDateTimeString.call(oDTP, sCurrent, sMode, $(oElement)); else oDTP.oData.dCurrentDate = oDTP._parseTime(sCurrent); } else if(oDTP.oData.bDateTimeMode) { sMin = sMinValue || oDTP.settings.minDateTime; sMax = sMaxValue || oDTP.settings.maxDateTime; oDTP.oData.sDateTimeFormat = sFormat; if($.cf._isValid(sMin)) oDTP.oData.dMinValue = oDTP._parseDateTime(sMin); if($.cf._isValid(sMax)) oDTP.oData.dMaxValue = oDTP._parseDateTime(sMax); if(sStartEnd !== "" && ($.cf._compare(sStartEnd, "start") || $.cf._compare(sStartEnd, "end")) && sStartEndElem !== "") { if($(sStartEndElem).length >= 1) { sTempDateTime = oDTP._getValueOfElement($(sStartEndElem)); if(sTempDateTime !== "") { if(oDTP.settings.parseDateTimeString) dTempDateTime = oDTP.settings.parseDateTimeString.call(oDTP, sTempDateTime, sMode, $(sStartEndElem)); else dTempDateTime = oDTP._parseDateTime(sTempDateTime); if($.cf._compare(sStartEnd, "start")) { if($.cf._isValid(sMax)) { if(oDTP._compareDateTime(dTempDateTime, oDTP.oData.dMaxValue) < 0) oDTP.oData.dMaxValue = new Date(dTempDateTime); } else oDTP.oData.dMaxValue = new Date(dTempDateTime); } else if($.cf._compare(sStartEnd, "end")) { if($.cf._isValid(sMin)) { if(oDTP._compareDateTime(dTempDateTime, oDTP.oData.dMinValue) > 0) oDTP.oData.dMinValue = new Date(dTempDateTime); } else oDTP.oData.dMinValue = new Date(dTempDateTime); } } } } oDTP.oData.bIs12Hour = oDTP.getIs12Hour(); if(oDTP.settings.parseDateTimeString) oDTP.oData.dCurrentDate = oDTP.settings.parseDateTimeString.call(oDTP, sCurrent, sMode, $(oElement)); else oDTP.oData.dCurrentDate = oDTP._parseDateTime(sCurrent); } oDTP._setVariablesForDate(); oDTP._modifyPicker(); $(oDTP.element).fadeIn(oDTP.settings.animationDuration); if(oDTP.settings.afterShow) { setTimeout(function() { oDTP.settings.afterShow.call(oDTP, oElement); }, oDTP.settings.animationDuration); } } }, _hidePicker: function(iDuration, oElementToShow) { var oDTP = this; var oElement = oDTP.oData.oInputElement; if(oDTP.settings.beforeHide) oDTP.settings.beforeHide.call(oDTP, oElement); if(!$.cf._isValid(iDuration)) iDuration = oDTP.settings.animationDuration; if($.cf._isValid(oDTP.oData.oInputElement)) { $(oDTP.oData.oInputElement).blur(); oDTP.oData.oInputElement = null; } $(oDTP.element).fadeOut(iDuration); if(iDuration === 0) { $(oDTP.element).find('.dtpicker-subcontent').html(""); } else { setTimeout(function() { $(oDTP.element).find('.dtpicker-subcontent').html(""); }, iDuration); } $(document).unbind("click.DateTimePicker"); $(document).unbind("keydown.DateTimePicker"); $(document).unbind("keyup.DateTimePicker"); if(oDTP.settings.afterHide) { if(iDuration === 0) { oDTP.settings.afterHide.call(oDTP, oElement); } else { setTimeout(function() { oDTP.settings.afterHide.call(oDTP, oElement); }, iDuration); } } if($.cf._isValid(oElementToShow)) oDTP._showPicker(oElementToShow); }, _modifyPicker: function() { var oDTP = this; var sTitleContent, iNumberOfColumns; var sArrFields = []; if(oDTP.oData.bDateMode) { sTitleContent = oDTP.settings.titleContentDate; iNumberOfColumns = 3; if(oDTP.oData.bArrMatchFormat[0]) // "dd-MM-yyyy" { sArrFields = ["day", "month", "year"]; } else if(oDTP.oData.bArrMatchFormat[1]) // "MM-dd-yyyy" { sArrFields = ["month", "day", "year"]; } else if(oDTP.oData.bArrMatchFormat[2]) // "yyyy-MM-dd" { sArrFields = ["year", "month", "day"]; } else if(oDTP.oData.bArrMatchFormat[3]) // "dd-MMM-yyyy" { sArrFields = ["day", "month", "year"]; } else if(oDTP.oData.bArrMatchFormat[4]) // "MM-yyyy" { iNumberOfColumns = 2; sArrFields = ["month", "year"]; } else if(oDTP.oData.bArrMatchFormat[5]) // "MMM yyyy" { iNumberOfColumns = 2; sArrFields = ["month", "year"]; } else if(oDTP.oData.bArrMatchFormat[6]) // "MMMM yyyy" { iNumberOfColumns = 2; sArrFields = ["month", "year"]; } } else if(oDTP.oData.bTimeMode) { sTitleContent = oDTP.settings.titleContentTime; if(oDTP.oData.bArrMatchFormat[0]) // hh:mm:ss AA { iNumberOfColumns = 4; sArrFields = ["hour", "minutes", "seconds", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[1]) // HH:mm:ss { iNumberOfColumns = 3; sArrFields = ["hour", "minutes", "seconds"]; } else if(oDTP.oData.bArrMatchFormat[2]) // hh:mm AA { iNumberOfColumns = 3; sArrFields = ["hour", "minutes", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[3]) // HH:mm { iNumberOfColumns = 2; sArrFields = ["hour", "minutes"]; } } else if(oDTP.oData.bDateTimeMode) { sTitleContent = oDTP.settings.titleContentDateTime; if(oDTP.oData.bArrMatchFormat[0]) { iNumberOfColumns = 6; sArrFields = ["day", "month", "year", "hour", "minutes", "seconds"]; } else if(oDTP.oData.bArrMatchFormat[1]) { iNumberOfColumns = 7; sArrFields = ["day", "month", "year", "hour", "minutes", "seconds", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[2]) { iNumberOfColumns = 6; sArrFields = ["month", "day", "year", "hour", "minutes", "seconds"]; } else if(oDTP.oData.bArrMatchFormat[3]) { iNumberOfColumns = 7; sArrFields = ["month", "day", "year", "hour", "minutes", "seconds", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[4]) { iNumberOfColumns = 6; sArrFields = ["year", "month", "day", "hour", "minutes", "seconds"]; } else if(oDTP.oData.bArrMatchFormat[5]) { iNumberOfColumns = 7; sArrFields = ["year", "month", "day", "hour", "minutes", "seconds", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[6]) { iNumberOfColumns = 6; sArrFields = ["day", "month", "year", "hour", "minutes", "seconds"]; } else if(oDTP.oData.bArrMatchFormat[7]) { iNumberOfColumns = 7; sArrFields = ["day", "month", "year", "hour", "minutes", "seconds", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[8]) { iNumberOfColumns = 5; sArrFields = ["day", "month", "year", "hour", "minutes"]; } else if(oDTP.oData.bArrMatchFormat[9]) { iNumberOfColumns = 6; sArrFields = ["day", "month", "year", "hour", "minutes", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[10]) { iNumberOfColumns = 5; sArrFields = ["month", "day", "year", "hour", "minutes"]; } else if(oDTP.oData.bArrMatchFormat[11]) { iNumberOfColumns = 6; sArrFields = ["month", "day", "year", "hour", "minutes", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[12]) { iNumberOfColumns = 5; sArrFields = ["year", "month", "day", "hour", "minutes"]; } else if(oDTP.oData.bArrMatchFormat[13]) { iNumberOfColumns = 6; sArrFields = ["year", "month", "day", "hour", "minutes", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[14]) { iNumberOfColumns = 5; sArrFields = ["day", "month", "year", "hour", "minutes"]; } else if(oDTP.oData.bArrMatchFormat[15]) { iNumberOfColumns = 6; sArrFields = ["day", "month", "year", "hour", "minutes", "meridiem"]; } } //your_sha256_hash---- var sColumnClass = "dtpicker-comp" + iNumberOfColumns, bDisplayHeaderCloseButton = false, bDisplaySetButton = false, bDisplayClearButton = false, iTempIndex; for(iTempIndex = 0; iTempIndex < oDTP.settings.buttonsToDisplay.length; iTempIndex++) { if($.cf._compare(oDTP.settings.buttonsToDisplay[iTempIndex], "HeaderCloseButton")) bDisplayHeaderCloseButton = true; else if($.cf._compare(oDTP.settings.buttonsToDisplay[iTempIndex], "SetButton")) bDisplaySetButton = true; else if($.cf._compare(oDTP.settings.buttonsToDisplay[iTempIndex], "ClearButton")) bDisplayClearButton = true; } var sHeader = ""; sHeader += "<div class='dtpicker-header'>"; sHeader += "<div class='dtpicker-title'>" + sTitleContent + "</div>"; if(bDisplayHeaderCloseButton) sHeader += "<a class='dtpicker-close'>&times;</a>"; sHeader += "<div class='dtpicker-value'></div>"; sHeader += "</div>"; //your_sha256_hash---- var sDTPickerComp = ""; sDTPickerComp += "<div class='dtpicker-components'>"; for(iTempIndex = 0; iTempIndex < iNumberOfColumns; iTempIndex++) { var sFieldName = sArrFields[iTempIndex]; sDTPickerComp += "<div class='dtpicker-compOutline " + sColumnClass + "'>"; sDTPickerComp += "<div class='dtpicker-comp " + sFieldName + "'>"; sDTPickerComp += "<a class='dtpicker-compButton increment'>" + oDTP.settings.incrementButtonContent + "</a>"; sDTPickerComp += "<input type='text' class='dtpicker-compValue'></input>"; sDTPickerComp += "<a class='dtpicker-compButton decrement'>" + oDTP.settings.decrementButtonContent + "</a>"; sDTPickerComp += "</div>"; sDTPickerComp += "</div>"; } sDTPickerComp += "</div>"; //your_sha256_hash---- var sButtonContClass = ""; if(bDisplaySetButton && bDisplayClearButton) sButtonContClass = " dtpicker-twoButtons"; else sButtonContClass = " dtpicker-singleButton"; var sDTPickerButtons = ""; sDTPickerButtons += "<div class='dtpicker-buttonCont" + sButtonContClass + "'>"; if(bDisplaySetButton) sDTPickerButtons += "<a class='dtpicker-button dtpicker-buttonSet'>" + oDTP.settings.setButtonContent + "</a>"; if(bDisplayClearButton) sDTPickerButtons += "<a class='dtpicker-button dtpicker-buttonClear'>" + oDTP.settings.clearButtonContent + "</a>"; sDTPickerButtons += "</div>"; //your_sha256_hash---- var sTempStr = sHeader + sDTPickerComp + sDTPickerButtons; $(oDTP.element).find('.dtpicker-subcontent').html(sTempStr); oDTP._setCurrentDate(); oDTP._addEventHandlersForPicker(); }, _addEventHandlersForPicker: function() { var oDTP = this; $(document).on("click.DateTimePicker", function(e) { oDTP._hidePicker(""); }); $(document).on("keydown.DateTimePicker", function(e) { if(! $('.dtpicker-compValue').is(':focus') && parseInt(e.keyCode ? e.keyCode : e.which) === 9) { oDTP._setButtonAction(true); $("[tabIndex=" + (oDTP.oData.iTabIndex + 1) + "]").focus(); return false; } }); $(document).on("keydown.DateTimePicker", function(e) { if(! $('.dtpicker-compValue').is(':focus') && parseInt(e.keyCode ? e.keyCode : e.which) !== 9) { oDTP._hidePicker(""); } }); $(".dtpicker-cont *").click(function(e) { e.stopPropagation(); }); $('.dtpicker-compValue').not('.month .dtpicker-compValue, .meridiem .dtpicker-compValue').keyup(function() { this.value = this.value.replace(/[^0-9\.]/g,''); }); $('.dtpicker-compValue').focus(function() { oDTP.oData.bElemFocused = true; }); $('.dtpicker-compValue').on("blur", function() { console.log("Executed blur"); oDTP._getValuesFromInputBoxes(); oDTP._setCurrentDate(); oDTP.oData.bElemFocused = false; var $oParentElem = $(this).parent().parent(); setTimeout(function() { if($oParentElem.is(':last-child') && !oDTP.oData.bElemFocused) { oDTP._setButtonAction(false); } }, 50); }); $(".dtpicker-compValue").keyup(function() { var $oTextField = $(this), sTextBoxVal = $oTextField.val(), iLength = sTextBoxVal.length, sNewTextBoxVal; if($oTextField.parent().hasClass("day") || $oTextField.parent().hasClass("hour") || $oTextField.parent().hasClass("minutes") || $oTextField.parent().hasClass("meridiem")) { if(iLength > 2) { sNewTextBoxVal = sTextBoxVal.slice(0, 2); $oTextField.val(sNewTextBoxVal); } } else if($oTextField.parent().hasClass("month")) { if(iLength > 3) { sNewTextBoxVal = sTextBoxVal.slice(0, 3); $oTextField.val(sNewTextBoxVal); } } else if($oTextField.parent().hasClass("year")) { if(iLength > 4) { sNewTextBoxVal = sTextBoxVal.slice(0, 4); $oTextField.val(sNewTextBoxVal); } } }); //your_sha256_hash------- $(oDTP.element).find('.dtpicker-close').click(function(e) { if(oDTP.settings.buttonClicked) oDTP.settings.buttonClicked.call(oDTP, "CLOSE", oDTP.oData.oInputElement); oDTP._hidePicker(""); }); $(oDTP.element).find('.dtpicker-buttonSet').click(function(e) { if(oDTP.settings.buttonClicked) oDTP.settings.buttonClicked.call(oDTP, "SET", oDTP.oData.oInputElement); oDTP._setButtonAction(false); }); $(oDTP.element).find('.dtpicker-buttonClear').click(function(e) { if(oDTP.settings.buttonClicked) oDTP.settings.buttonClicked.call(oDTP, "CLEAR", oDTP.oData.oInputElement); oDTP._clearButtonAction(); }); // your_sha256_hash------------ $(oDTP.element).find(".day .increment, .day .increment *").click(function(e) { oDTP.oData.iCurrentDay++; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".day .decrement, .day .decrement *").click(function(e) { oDTP.oData.iCurrentDay--; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".month .increment, .month .increment *").click(function(e) { oDTP.oData.iCurrentMonth++; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".month .decrement, .month .decrement *").click(function(e) { oDTP.oData.iCurrentMonth--; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".year .increment, .year .increment *").click(function(e) { oDTP.oData.iCurrentYear++; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".year .decrement, .year .decrement *").click(function(e) { oDTP.oData.iCurrentYear--; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".hour .increment, .hour .increment *").click(function(e) { oDTP.oData.iCurrentHour++; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".hour .decrement, .hour .decrement *").click(function(e) { oDTP.oData.iCurrentHour--; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".minutes .increment, .minutes .increment *").click(function(e) { oDTP.oData.iCurrentMinutes += oDTP.settings.minuteInterval; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".minutes .decrement, .minutes .decrement *").click(function(e) { oDTP.oData.iCurrentMinutes -= oDTP.settings.minuteInterval; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".seconds .increment, .seconds .increment *").click(function(e) { oDTP.oData.iCurrentSeconds += oDTP.settings.secondsInterval; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".seconds .decrement, .seconds .decrement *").click(function(e) { oDTP.oData.iCurrentSeconds -= oDTP.settings.secondsInterval; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".meridiem .dtpicker-compButton").click(function(e) { if($.cf._compare(oDTP.oData.sCurrentMeridiem, "AM")) { oDTP.oData.sCurrentMeridiem = "PM"; oDTP.oData.iCurrentHour += 12; } else if($.cf._compare(oDTP.oData.sCurrentMeridiem, "PM")) { oDTP.oData.sCurrentMeridiem = "AM"; oDTP.oData.iCurrentHour -= 12; } oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); }, _adjustMinutes: function(iMinutes) { var oDTP = this; if(oDTP.settings.roundOffMinutes && oDTP.settings.minuteInterval !== 1) { iMinutes = (iMinutes % oDTP.settings.minuteInterval) ? (iMinutes - (iMinutes % oDTP.settings.minuteInterval) + oDTP.settings.minuteInterval) : iMinutes; } return iMinutes; }, _adjustSeconds: function(iSeconds) { var oDTP = this; if(oDTP.settings.roundOffSeconds && oDTP.settings.secondsInterval !== 1) { iSeconds = (iSeconds % oDTP.settings.secondsInterval) ? (iSeconds - (iSeconds % oDTP.settings.secondsInterval) + oDTP.settings.secondsInterval) : iSeconds; } return iSeconds; }, _getValueOfElement: function(oElem) { var oDTP = this; var sElemValue = ""; if($.cf._compare($(oElem).prop("tagName"), "INPUT")) sElemValue = $(oElem).val(); else sElemValue = $(oElem).html(); return sElemValue; }, _setValueOfElement: function(sElemValue) { var oDTP = this; var $oElem = $(oDTP.oData.oInputElement); if(sElemValue !== "" && oDTP.settings.formatDateTimeString) { var sMode, oDate; sMode = $oElem.data("field"); sMode = $.cf._isValid(sMode) ? sMode : oDTP.settings.mode; if(oDTP.oData.bDateMode || oDTP.oData.bDateTimeMode) oDate = $.extend(oDate, oDTP._formatDate()); if(oDTP.oData.bTimeMode || oDTP.oData.bDateTimeMode) oDate = $.extend(oDate, oDTP._formatDate()); sElemValue = oDTP.settings.formatDateTimeString.call(oDTP, oDate, sMode, $oElem); } if($.cf._compare($oElem.prop("tagName"), "INPUT")) $oElem.val(sElemValue); else $oElem.html(sElemValue); $oElem.change(); return sElemValue; }, //your_sha256_hash- _parseDate: function(sDate) { var oDTP = this; var dTempDate = new Date(oDTP.settings.defaultDate), iDate = dTempDate.getDate(), iMonth = dTempDate.getMonth(), iYear = dTempDate.getFullYear(); if($.cf._isValid(sDate)) { var sArrDate; if(oDTP.oData.bArrMatchFormat[4] || oDTP.oData.bArrMatchFormat[5] || oDTP.oData.bArrMatchFormat[6]) sArrDate = sDate.split(oDTP.settings.monthYearSeparator); else sArrDate = sDate.split(oDTP.settings.dateSeparator); if(oDTP.oData.bArrMatchFormat[0]) // "dd-MM-yyyy" { iDate = parseInt(sArrDate[0]); iMonth = parseInt(sArrDate[1] - 1); iYear = parseInt(sArrDate[2]); } else if(oDTP.oData.bArrMatchFormat[1]) // "MM-dd-yyyy" { iMonth = parseInt(sArrDate[0] - 1); iDate = parseInt(sArrDate[1]); iYear = parseInt(sArrDate[2]); } else if(oDTP.oData.bArrMatchFormat[2]) // "yyyy-MM-dd" { iYear = parseInt(sArrDate[0]); iMonth = parseInt(sArrDate[1] - 1); iDate = parseInt(sArrDate[2]); } else if(oDTP.oData.bArrMatchFormat[3]) // "dd-MMM-yyyy" { iDate = parseInt(sArrDate[0]); iMonth = oDTP._getShortMonthIndex(sArrDate[1]); iYear = parseInt(sArrDate[2]); } else if(oDTP.oData.bArrMatchFormat[4]) // "MM-yyyy" { iDate = 1; iMonth = parseInt(sArrDate[0]) - 1; iYear = parseInt(sArrDate[1]); } else if(oDTP.oData.bArrMatchFormat[5]) // "MMM yyyy" { iDate = 1; iMonth = oDTP._getShortMonthIndex(sArrDate[0]); iYear = parseInt(sArrDate[1]); } else if(oDTP.oData.bArrMatchFormat[6]) // "MMMM yyyy" { iDate = 1; iMonth = oDTP._getFullMonthIndex(sArrDate[0]); iYear = parseInt(sArrDate[1]); } } dTempDate = new Date(iYear, iMonth, iDate, 0, 0, 0, 0); return dTempDate; }, _parseTime: function(sTime) { var oDTP = this; var dTempDate = new Date(oDTP.settings.defaultDate), iDate = dTempDate.getDate(), iMonth = dTempDate.getMonth(), iYear = dTempDate.getFullYear(), iHour = dTempDate.getHours(), iMinutes = dTempDate.getMinutes(), iSeconds = dTempDate.getSeconds(), sArrTime, sMeridiem, sArrTimeComp, bShowSeconds = oDTP.oData.bArrMatchFormat[0] || oDTP.oData.bArrMatchFormat[1]; iSeconds = bShowSeconds ? oDTP._adjustSeconds(iSeconds) : 0; if($.cf._isValid(sTime)) { if(oDTP.oData.bIs12Hour) { sArrTime = sTime.split(oDTP.settings.timeMeridiemSeparator); sTime = sArrTime[0]; sMeridiem = sArrTime[1]; if(!($.cf._compare(sMeridiem, "AM") || $.cf._compare(sMeridiem, "PM"))) sMeridiem = ""; } sArrTimeComp = sTime.split(oDTP.settings.timeSeparator); iHour = parseInt(sArrTimeComp[0]); iMinutes = parseInt(sArrTimeComp[1]); if(bShowSeconds) { iSeconds = parseInt(sArrTimeComp[2]); iSeconds = oDTP._adjustSeconds(iSeconds); } if(iHour === 12 && $.cf._compare(sMeridiem, "AM")) iHour = 0; else if(iHour < 12 && $.cf._compare(sMeridiem, "PM")) iHour += 12; } iMinutes = oDTP._adjustMinutes(iMinutes); dTempDate = new Date(iYear, iMonth, iDate, iHour, iMinutes, iSeconds, 0); return dTempDate; }, _parseDateTime: function(sDateTime) { var oDTP = this; var dTempDate = new Date(oDTP.settings.defaultDate), iDate = dTempDate.getDate(), iMonth = dTempDate.getMonth(), iYear = dTempDate.getFullYear(), iHour = dTempDate.getHours(), iMinutes = dTempDate.getMinutes(), iSeconds = dTempDate.getSeconds(), sMeridiem = "", sArrDateTime, sArrDate, sTime, sArrTimeComp, sArrTime, bShowSeconds = oDTP.oData.bArrMatchFormat[0] || oDTP.oData.bArrMatchFormat[1] || oDTP.oData.bArrMatchFormat[2] || oDTP.oData.bArrMatchFormat[3] || oDTP.oData.bArrMatchFormat[4] || oDTP.oData.bArrMatchFormat[5] || oDTP.oData.bArrMatchFormat[6] || oDTP.oData.bArrMatchFormat[7]; iSeconds = bShowSeconds ? oDTP._adjustSeconds(iSeconds) : 0; if($.cf._isValid(sDateTime)) { sArrDateTime = sDateTime.split(oDTP.settings.dateTimeSeparator); sArrDate = sArrDateTime[0].split(oDTP.settings.dateSeparator); if(oDTP.oData.bArrMatchFormat[0] || // "dd-MM-yyyy HH:mm:ss" oDTP.oData.bArrMatchFormat[1]) // ""dd-MM-yyyy hh:mm:ss AA" { iDate = parseInt(sArrDate[0]); iMonth = parseInt(sArrDate[1] - 1); iYear = parseInt(sArrDate[2]); } else if(oDTP.oData.bArrMatchFormat[2] || // "MM-dd-yyyy HH:mm:ss" oDTP.oData.bArrMatchFormat[3]) // "MM-dd-yyyy hh:mm:ss AA" { iMonth = parseInt(sArrDate[0] - 1); iDate = parseInt(sArrDate[1]); iYear = parseInt(sArrDate[2]); } else if(oDTP.oData.bArrMatchFormat[4] || // "yyyy-MM-dd HH:mm:ss" oDTP.oData.bArrMatchFormat[5]) // "yyyy-MM-dd hh:mm:ss AA" { iYear = parseInt(sArrDate[0]); iMonth = parseInt(sArrDate[1] - 1); iDate = parseInt(sArrDate[2]); } else if(oDTP.oData.bArrMatchFormat[6] || // "dd-MMM-yyyy HH:mm:ss" oDTP.oData.bArrMatchFormat[7]) // "dd-MMM-yyyy hh:mm:ss AA" { iDate = parseInt(sArrDate[0]); iMonth = oDTP._getShortMonthIndex(sArrDate[1]); iYear = parseInt(sArrDate[2]); } sTime = sArrDateTime[1]; if(oDTP.oData.bIs12Hour) { if($.cf._compare(oDTP.settings.dateTimeSeparator, oDTP.settings.timeMeridiemSeparator) && (sArrDateTime.length === 3)) sMeridiem = sArrDateTime[2]; else { sArrTimeComp = sTime.split(oDTP.settings.timeMeridiemSeparator); sTime = sArrTimeComp[0]; sMeridiem = sArrTimeComp[1]; } if(!($.cf._compare(sMeridiem, "AM") || $.cf._compare(sMeridiem, "PM"))) sMeridiem = ""; } sArrTime = sTime.split(oDTP.settings.timeSeparator); iHour = parseInt(sArrTime[0]); iMinutes = parseInt(sArrTime[1]); if(bShowSeconds) { iSeconds = parseInt(sArrTime[2]); } if(iHour === 12 && $.cf._compare(sMeridiem, "AM")) iHour = 0; else if(iHour < 12 && $.cf._compare(sMeridiem, "PM")) iHour += 12; } iMinutes = oDTP._adjustMinutes(iMinutes); dTempDate = new Date(iYear, iMonth, iDate, iHour, iMinutes, iSeconds, 0); return dTempDate; }, _getShortMonthIndex: function(sMonthName) { var oDTP = this; for(var iTempIndex = 0; iTempIndex < oDTP.settings.shortMonthNames.length; iTempIndex++) { if($.cf._compare(sMonthName, oDTP.settings.shortMonthNames[iTempIndex])) return iTempIndex; } }, _getFullMonthIndex: function(sMonthName) { var oDTP = this; for(var iTempIndex = 0; iTempIndex < oDTP.settings.fullMonthNames.length; iTempIndex++) { if($.cf._compare(sMonthName, oDTP.settings.fullMonthNames[iTempIndex])) return iTempIndex; } }, // Public Method getIs12Hour: function(sMode, sFormat) { var oDTP = this; var bIs12Hour = false, iArgsLength = Function.length; oDTP._setMatchFormat(iArgsLength, sMode, sFormat); if(oDTP.oData.bTimeMode) { bIs12Hour = oDTP.oData.bArrMatchFormat[0] || oDTP.oData.bArrMatchFormat[2]; } else if(oDTP.oData.bDateTimeMode) { bIs12Hour = oDTP.oData.bArrMatchFormat[1] || oDTP.oData.bArrMatchFormat[3] || oDTP.oData.bArrMatchFormat[5] || oDTP.oData.bArrMatchFormat[7] || oDTP.oData.bArrMatchFormat[9] || oDTP.oData.bArrMatchFormat[11] || oDTP.oData.bArrMatchFormat[13] || oDTP.oData.bArrMatchFormat[15]; } oDTP._setMatchFormat(iArgsLength); return bIs12Hour; }, //your_sha256_hash- _setVariablesForDate: function() { var oDTP = this; oDTP.oData.iCurrentDay = oDTP.oData.dCurrentDate.getDate(); oDTP.oData.iCurrentMonth = oDTP.oData.dCurrentDate.getMonth(); oDTP.oData.iCurrentYear = oDTP.oData.dCurrentDate.getFullYear(); if(oDTP.oData.bTimeMode || oDTP.oData.bDateTimeMode) { oDTP.oData.iCurrentHour = oDTP.oData.dCurrentDate.getHours(); oDTP.oData.iCurrentMinutes = oDTP.oData.dCurrentDate.getMinutes(); oDTP.oData.iCurrentSeconds = oDTP.oData.dCurrentDate.getSeconds(); if(oDTP.oData.bIs12Hour) { oDTP.oData.sCurrentMeridiem = oDTP._determineMeridiemFromHourAndMinutes(oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes); } } }, _getValuesFromInputBoxes: function() { var oDTP = this; if(oDTP.oData.bDateMode || oDTP.oData.bDateTimeMode) { var sMonth, iMonth; sMonth = $(oDTP.element).find(".month .dtpicker-compValue").val(); if(sMonth.length > 1) sMonth = sMonth.charAt(0).toUpperCase() + sMonth.slice(1); iMonth = oDTP.settings.shortMonthNames.indexOf(sMonth); if(iMonth !== -1) { oDTP.oData.iCurrentMonth = parseInt(iMonth); } else { if(sMonth.match("^[+|-]?[0-9]+$")) { oDTP.oData.iCurrentMonth = parseInt(sMonth - 1); } } oDTP.oData.iCurrentDay = parseInt($(oDTP.element).find(".day .dtpicker-compValue").val()) || oDTP.oData.iCurrentDay; oDTP.oData.iCurrentYear = parseInt($(oDTP.element).find(".year .dtpicker-compValue").val()) || oDTP.oData.iCurrentYear; } if(oDTP.oData.bTimeMode || oDTP.oData.bDateTimeMode) { var iTempHour, iTempMinutes, iTempSeconds, sMeridiem; iTempHour = parseInt($(oDTP.element).find(".hour .dtpicker-compValue").val()); iTempMinutes = oDTP._adjustMinutes(parseInt($(oDTP.element).find(".minutes .dtpicker-compValue").val())); iTempSeconds = oDTP._adjustMinutes(parseInt($(oDTP.element).find(".seconds .dtpicker-compValue").val())); oDTP.oData.iCurrentHour = isNaN(iTempHour) ? oDTP.oData.iCurrentHour : iTempHour; oDTP.oData.iCurrentMinutes = isNaN(iTempMinutes) ? oDTP.oData.iCurrentMinutes : iTempMinutes; oDTP.oData.iCurrentSeconds = isNaN(iTempSeconds) ? oDTP.oData.iCurrentSeconds : iTempSeconds; if(oDTP.oData.iCurrentSeconds > 59) { oDTP.oData.iCurrentMinutes += oDTP.oData.iCurrentSeconds / 60; oDTP.oData.iCurrentSeconds = oDTP.oData.iCurrentSeconds % 60; } if(oDTP.oData.iCurrentMinutes > 59) { oDTP.oData.iCurrentHour += oDTP.oData.iCurrentMinutes / 60; oDTP.oData.iCurrentMinutes = oDTP.oData.iCurrentMinutes % 60; } if(oDTP.oData.bIs12Hour) { if(oDTP.oData.iCurrentHour > 12) oDTP.oData.iCurrentHour = (oDTP.oData.iCurrentHour % 12); } else { if(oDTP.oData.iCurrentHour > 23) oDTP.oData.iCurrentHour = (oDTP.oData.iCurrentHour % 23); } if(oDTP.oData.bIs12Hour) { sMeridiem = $(oDTP.element).find(".meridiem .dtpicker-compValue").val(); if($.cf._compare(sMeridiem, "AM") || $.cf._compare(sMeridiem, "PM")) oDTP.oData.sCurrentMeridiem = sMeridiem; if($.cf._compare(oDTP.oData.sCurrentMeridiem, "PM")) { if(oDTP.oData.iCurrentHour !== 12 && oDTP.oData.iCurrentHour < 13) oDTP.oData.iCurrentHour += 12; } if($.cf._compare(oDTP.oData.sCurrentMeridiem, "AM") && oDTP.oData.iCurrentHour === 12) oDTP.oData.iCurrentHour = 0; } } }, _setCurrentDate: function() { var oDTP = this; if(oDTP.oData.bTimeMode || oDTP.oData.bDateTimeMode) { if(oDTP.oData.iCurrentSeconds > 59) { oDTP.oData.iCurrentMinutes += oDTP.oData.iCurrentSeconds / 60; oDTP.oData.iCurrentSeconds = oDTP.oData.iCurrentSeconds % 60; } else if(oDTP.oData.iCurrentSeconds < 0) { oDTP.oData.iCurrentMinutes -= oDTP.settings.minuteInterval; oDTP.oData.iCurrentSeconds += 60; } oDTP.oData.iCurrentMinutes = oDTP._adjustMinutes(oDTP.oData.iCurrentMinutes); oDTP.oData.iCurrentSeconds = oDTP._adjustSeconds(oDTP.oData.iCurrentSeconds); } var dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0), bGTMaxDate = false, bLTMinDate = false, sFormat, oDate, oFormattedDate, oFormattedTime, sDate, sTime, sDateTime; if(oDTP.oData.dMaxValue !== null) bGTMaxDate = (dTempDate.getTime() > oDTP.oData.dMaxValue.getTime()); if(oDTP.oData.dMinValue !== null) bLTMinDate = (dTempDate.getTime() < oDTP.oData.dMinValue.getTime()); if(bGTMaxDate || bLTMinDate) { var bCDGTMaxDate = false, bCDLTMinDate = false; if(oDTP.oData.dMaxValue !== null) bCDGTMaxDate = (oDTP.oData.dCurrentDate.getTime() > oDTP.oData.dMaxValue.getTime()); if(oDTP.oData.dMinValue !== null) bCDLTMinDate = (oDTP.oData.dCurrentDate.getTime() < oDTP.oData.dMinValue.getTime()); if(!(bCDGTMaxDate || bCDLTMinDate)) dTempDate = new Date(oDTP.oData.dCurrentDate); else { if(bCDGTMaxDate) { dTempDate = new Date(oDTP.oData.dMaxValue); console.log("Info : Date/Time/DateTime you entered is later than Maximum value, so DateTimePicker is showing Maximum value in Input Field."); } if(bCDLTMinDate) { dTempDate = new Date(oDTP.oData.dMinValue); console.log("Info : Date/Time/DateTime you entered is earlier than Minimum value, so DateTimePicker is showing Minimum value in Input Field."); } console.log("Please enter proper Date/Time/DateTime values."); } } oDTP.oData.dCurrentDate = new Date(dTempDate); oDTP._setVariablesForDate(); oDate = {}; sDate = ""; sTime = ""; sDateTime = ""; if(oDTP.oData.bDateMode || oDTP.oData.bDateTimeMode) { if(oDTP.oData.bDateMode && (oDTP.oData.bArrMatchFormat[4] || oDTP.oData.bArrMatchFormat[5] || oDTP.oData.bArrMatchFormat[6])) oDTP.oData.iCurrentDay = 1; oFormattedDate = oDTP._formatDate(); $(oDTP.element).find('.day .dtpicker-compValue').val(oFormattedDate.dd); if(oDTP.oData.bDateMode) { if(oDTP.oData.bArrMatchFormat[4]) // "MM-yyyy" $(oDTP.element).find('.month .dtpicker-compValue').val(oFormattedDate.MM); else if(oDTP.oData.bArrMatchFormat[6]) // "MMMM yyyy" $(oDTP.element).find('.month .dtpicker-compValue').val(oFormattedDate.month); else $(oDTP.element).find('.month .dtpicker-compValue').val(oFormattedDate.monthShort); } else $(oDTP.element).find('.month .dtpicker-compValue').val(oFormattedDate.monthShort); $(oDTP.element).find('.year .dtpicker-compValue').val(oFormattedDate.yyyy); if(oDTP.settings.formatHumanDate) { oDate = $.extend(oDate, oFormattedDate); } else { if(oDTP.oData.bDateMode && (oDTP.oData.bArrMatchFormat[4] || oDTP.oData.bArrMatchFormat[5] || oDTP.oData.bArrMatchFormat[6])) { if(oDTP.oData.bArrMatchFormat[4]) sDate = oFormattedDate.MM + oDTP.settings.monthYearSeparator + oFormattedDate.yyyy; else if(oDTP.oData.bArrMatchFormat[5]) sDate = oFormattedDate.monthShort + oDTP.settings.monthYearSeparator + oFormattedDate.yyyy; else if(oDTP.oData.bArrMatchFormat[6]) sDate = oFormattedDate.month + oDTP.settings.monthYearSeparator + oFormattedDate.yyyy; } else sDate = oFormattedDate.dayShort + ", " + oFormattedDate.month + " " + oFormattedDate.dd + ", " + oFormattedDate.yyyy; } } if(oDTP.oData.bTimeMode || oDTP.oData.bDateTimeMode) { oFormattedTime = oDTP._formatTime(); if(oDTP.oData.bIs12Hour) $(oDTP.element).find('.meridiem .dtpicker-compValue').val(oDTP.oData.sCurrentMeridiem); $(oDTP.element).find('.hour .dtpicker-compValue').val(oFormattedTime.hour); $(oDTP.element).find('.minutes .dtpicker-compValue').val(oFormattedTime.mm); $(oDTP.element).find('.seconds .dtpicker-compValue').val(oFormattedTime.ss); if(oDTP.settings.formatHumanDate) { oDate = $.extend(oDate, oFormattedTime); } else { var bShowSecondsTime = (oDTP.oData.bTimeMode && ( oDTP.oData.bArrMatchFormat[0] || oDTP.oData.bArrMatchFormat[1])), bShowSecondsDateTime = (oDTP.oData.bDateTimeMode && (oDTP.oData.bArrMatchFormat[0] || oDTP.oData.bArrMatchFormat[1] || oDTP.oData.bArrMatchFormat[2] || oDTP.oData.bArrMatchFormat[3] || oDTP.oData.bArrMatchFormat[4] || oDTP.oData.bArrMatchFormat[5] || oDTP.oData.bArrMatchFormat[6] || oDTP.oData.bArrMatchFormat[7])); if(bShowSecondsTime || bShowSecondsDateTime) sTime = oFormattedTime.hour + oDTP.settings.timeSeparator + oFormattedTime.mm + oDTP.settings.timeSeparator + oFormattedTime.ss; else sTime = oFormattedTime.hour + oDTP.settings.timeSeparator + oFormattedTime.mm; if(oDTP.oData.bIs12Hour) sTime += oDTP.settings.timeMeridiemSeparator + oDTP.oData.sCurrentMeridiem; } } if(oDTP.settings.formatHumanDate) { if(oDTP.oData.bDateTimeMode) sFormat = oDTP.oData.sDateFormat; else if(oDTP.oData.bDateMode) sFormat = oDTP.oData.sTimeFormat; else if(oDTP.oData.bTimeMode) sFormat = oDTP.oData.sDateTimeFormat; sDateTime = oDTP.settings.formatHumanDate.call(oDTP, oDate, oDTP.settings.mode, sFormat); } else { if(oDTP.oData.bDateTimeMode) sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; else if(oDTP.oData.bDateMode) sDateTime = sDate; else if(oDTP.oData.bTimeMode) sDateTime = sTime; } $(oDTP.element).find('.dtpicker-value').html(sDateTime); oDTP._setButtons(); }, _formatDate: function() { var oDTP = this; var sDay, sYear, iMonth, sMonth, sMonthShort, sMonthFull, iDayOfTheWeek, sDayOfTheWeek, sDayOfTheWeekFull; sDay = oDTP.oData.iCurrentDay; sDay = (sDay < 10) ? ("0" + sDay) : sDay; iMonth = oDTP.oData.iCurrentMonth; sMonth = oDTP.oData.iCurrentMonth + 1; sMonth = (sMonth < 10) ? ("0" + sMonth) : sMonth; sMonthShort = oDTP.settings.shortMonthNames[iMonth]; sMonthFull = oDTP.settings.fullMonthNames[iMonth]; sYear = oDTP.oData.iCurrentYear; iDayOfTheWeek = oDTP.oData.dCurrentDate.getDay(); sDayOfTheWeek = oDTP.settings.shortDayNames[iDayOfTheWeek]; sDayOfTheWeekFull = oDTP.settings.fullDayNames[iDayOfTheWeek]; return { "dd": sDay, "MM": sMonth, "monthShort": sMonthShort, "month": sMonthFull, "yyyy": sYear, "dayShort": sDayOfTheWeek, "day": sDayOfTheWeekFull }; }, _formatTime: function() { var oDTP = this; var iHour24, sHour24, iHour12, sHour12, sHour, sMinutes, sSeconds; iHour24 = oDTP.oData.iCurrentHour; sHour24 = (iHour24 < 10) ? ("0" + iHour24) : iHour24; sHour = sHour24; if(oDTP.oData.bIs12Hour) { iHour12 = oDTP.oData.iCurrentHour; if(iHour12 > 12) iHour12 -= 12; if(sHour === 0) iHour12 = 12; sHour12 = (iHour12 < 10) ? ("0" + iHour12) : iHour12; sHour = sHour12; } sMinutes = oDTP.oData.iCurrentMinutes; sMinutes = (sMinutes < 10) ? ("0" + sMinutes) : sMinutes; sSeconds = oDTP.oData.iCurrentSeconds; sSeconds = (sSeconds < 10) ? ("0" + sSeconds) : sSeconds; return { "H": iHour24, "HH": sHour24, "h": iHour12, "hh": sHour12, "hour": sHour, "m": oDTP.oData.iCurrentMinutes, "mm": sMinutes, "s": oDTP.oData.iCurrentSeconds, "ss": sSeconds, "ME": oDTP.oData.sCurrentMeridiem }; }, _setButtons: function() { var oDTP = this; $(oDTP.element).find('.dtpicker-compButton').removeClass("dtpicker-compButtonDisable").addClass('dtpicker-compButtonEnable'); var dTempDate; if(oDTP.oData.dMaxValue !== null) { if(oDTP.oData.bTimeMode) { // Decrement Hour if((oDTP.oData.iCurrentHour + 1) > oDTP.oData.dMaxValue.getHours() || ((oDTP.oData.iCurrentHour + 1) === oDTP.oData.dMaxValue.getHours() && oDTP.oData.iCurrentMinutes > oDTP.oData.dMaxValue.getMinutes())) $(oDTP.element).find(".hour .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Decrement Minutes if(oDTP.oData.iCurrentHour >= oDTP.oData.dMaxValue.getHours() && (oDTP.oData.iCurrentMinutes + 1) > oDTP.oData.dMaxValue.getMinutes()) $(oDTP.element).find(".minutes .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); } else { // Increment Day dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, (oDTP.oData.iCurrentDay + 1), oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() > oDTP.oData.dMaxValue.getTime()) $(oDTP.element).find(".day .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Increment Month dTempDate = new Date(oDTP.oData.iCurrentYear, (oDTP.oData.iCurrentMonth + 1), oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() > oDTP.oData.dMaxValue.getTime()) $(oDTP.element).find(".month .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Increment Year dTempDate = new Date((oDTP.oData.iCurrentYear + 1), oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() > oDTP.oData.dMaxValue.getTime()) $(oDTP.element).find(".year .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Increment Hour dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, (oDTP.oData.iCurrentHour + 1), oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() > oDTP.oData.dMaxValue.getTime()) $(oDTP.element).find(".hour .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Increment Minutes dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, (oDTP.oData.iCurrentMinutes + 1), oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() > oDTP.oData.dMaxValue.getTime()) $(oDTP.element).find(".minutes .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Increment Seconds dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, (oDTP.oData.iCurrentSeconds + 1), 0); if(dTempDate.getTime() > oDTP.oData.dMaxValue.getTime()) $(oDTP.element).find(".seconds .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); } } if(oDTP.oData.dMinValue !== null) { if(oDTP.oData.bTimeMode) { // Decrement Hour if((oDTP.oData.iCurrentHour - 1) < oDTP.oData.dMinValue.getHours() || ((oDTP.oData.iCurrentHour - 1) === oDTP.oData.dMinValue.getHours() && oDTP.oData.iCurrentMinutes < oDTP.oData.dMinValue.getMinutes())) $(oDTP.element).find(".hour .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Decrement Minutes if(oDTP.oData.iCurrentHour <= oDTP.oData.dMinValue.getHours() && (oDTP.oData.iCurrentMinutes - 1) < oDTP.oData.dMinValue.getMinutes()) $(oDTP.element).find(".minutes .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); } else { // Decrement Day dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, (oDTP.oData.iCurrentDay - 1), oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() < oDTP.oData.dMinValue.getTime()) $(oDTP.element).find(".day .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Decrement Month dTempDate = new Date(oDTP.oData.iCurrentYear, (oDTP.oData.iCurrentMonth - 1), oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() < oDTP.oData.dMinValue.getTime()) $(oDTP.element).find(".month .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Decrement Year dTempDate = new Date((oDTP.oData.iCurrentYear - 1), oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() < oDTP.oData.dMinValue.getTime()) $(oDTP.element).find(".year .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Decrement Hour dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, (oDTP.oData.iCurrentHour - 1), oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() < oDTP.oData.dMinValue.getTime()) $(oDTP.element).find(".hour .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Decrement Minutes dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, (oDTP.oData.iCurrentMinutes - 1), oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() < oDTP.oData.dMinValue.getTime()) $(oDTP.element).find(".minutes .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Decrement Seconds dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, (oDTP.oData.iCurrentSeconds - 1), 0); if(dTempDate.getTime() < oDTP.oData.dMinValue.getTime()) $(oDTP.element).find(".seconds .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); } } if(oDTP.oData.bIs12Hour) { var iTempHour, iTempMinutes; if(oDTP.oData.dMaxValue !== null || oDTP.oData.dMinValue !== null) { iTempHour = oDTP.oData.iCurrentHour; if($.cf._compare(oDTP.oData.sCurrentMeridiem, "AM")) iTempHour += 12; else if($.cf._compare(oDTP.oData.sCurrentMeridiem, "PM")) iTempHour -= 12; dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, iTempHour, oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(oDTP.oData.dMaxValue !== null) { if(oDTP.oData.bTimeMode) { iTempMinutes = oDTP.oData.iCurrentMinutes; if(iTempHour > oDTP.oData.dMaxValue.getHours() || (iTempHour === oDTP.oData.dMaxValue.getHours() && iTempMinutes > oDTP.oData.dMaxValue.getMinutes())) $(oDTP.element).find(".meridiem .dtpicker-compButton").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); } else { if(dTempDate.getTime() > oDTP.oData.dMaxValue.getTime()) $(oDTP.element).find(".meridiem .dtpicker-compButton").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); } } if(oDTP.oData.dMinValue !== null) { if(oDTP.oData.bTimeMode) { iTempMinutes = oDTP.oData.iCurrentMinutes; if(iTempHour < oDTP.oData.dMinValue.getHours() || (iTempHour === oDTP.oData.dMinValue.getHours() && iTempMinutes < oDTP.oData.dMinValue.getMinutes())) $(oDTP.element).find(".meridiem .dtpicker-compButton").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); } else { if(dTempDate.getTime() < oDTP.oData.dMinValue.getTime()) $(oDTP.element).find(".meridiem .dtpicker-compButton").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); } } } } }, // Public Method setIsPopup: function(bIsPopup) { var oDTP = this; oDTP.settings.isPopup = bIsPopup; if($(oDTP.element).css("display") !== "none") oDTP._hidePicker(0); if(oDTP.settings.isPopup) { $(oDTP.element).addClass("dtpicker-mobile"); $(oDTP.element).css({position: "fixed", top: 0, left: 0, width: "100%", height: "100%"}); } else { $(oDTP.element).removeClass("dtpicker-mobile"); if(oDTP.oData.oInputElement !== null) { var iElemTop = $(oDTP.oData.oInputElement).offset().top + $(oDTP.oData.oInputElement).outerHeight(), iElemLeft = $(oDTP.oData.oInputElement).offset().left, iElemWidth = $(oDTP.oData.oInputElement).outerWidth(); $(oDTP.element).css({position: "absolute", top: iElemTop, left: iElemLeft, width: iElemWidth, height: "auto"}); } } }, _compareDates: function(dDate1, dDate2) { dDate1 = new Date(dDate1.getDate(), dDate1.getMonth(), dDate1.getFullYear(), 0, 0, 0, 0); dDate1 = new Date(dDate1.getDate(), dDate1.getMonth(), dDate1.getFullYear(), 0, 0, 0, 0); var iDateDiff = (dDate1.getTime() - dDate2.getTime()) / 864E5; return (iDateDiff === 0) ? iDateDiff: (iDateDiff/Math.abs(iDateDiff)); }, _compareTime: function(dTime1, dTime2) { var iTimeMatch = 0; if((dTime1.getHours() === dTime2.getHours()) && (dTime1.getMinutes() === dTime2.getMinutes())) iTimeMatch = 1; // 1 = Exact Match else { if(dTime1.getHours() < dTime2.getHours()) iTimeMatch = 2; // time1 < time2 else if(dTime1.getHours() > dTime2.getHours()) iTimeMatch = 3; // time1 > time2 else if(dTime1.getHours() === dTime2.getHours()) { if(dTime1.getMinutes() < dTime2.getMinutes()) iTimeMatch = 2; // time1 < time2 else if(dTime1.getMinutes() > dTime2.getMinutes()) iTimeMatch = 3; // time1 > time2 } } return iTimeMatch; }, _compareDateTime: function(dDate1, dDate2) { var iDateTimeDiff = (dDate1.getTime() - dDate2.getTime()) / 6E4; return (iDateTimeDiff === 0) ? iDateTimeDiff: (iDateTimeDiff/Math.abs(iDateTimeDiff)); }, _determineMeridiemFromHourAndMinutes: function(iHour, iMinutes) { if(iHour > 12) { return "PM"; } else if(iHour === 12 && iMinutes >= 0) { return "PM"; } else { return "AM"; } }, // Public Method setLanguage: function(sLanguage) { var oDTP = this; oDTP.settings = $.extend({}, oDTP.settings, $.DateTimePicker.i18n[sLanguage]); oDTP._setDateFormatArray(); // Set DateFormatArray oDTP._setTimeFormatArray(); // Set TimeFormatArray oDTP._setDateTimeFormatArray(); // Set DateTimeFormatArray return oDTP; } }; })); ```
/content/code_sandbox/public/vendor/datetimepicker/src/DateTimePicker-Zepto.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
25,861
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url Author : Yanike Mann (path_to_url your_sha256_hash------------- */ /* Detect iOS device */ var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream; /* Execute if iOS device is found */ if (iOS) { function dtpickerContMoveiOS() { /* Execute if iOS device is found */ if (iOS) { /* Get SCROLL location */ var tscroll = window.scrollY /*Modern Way (Chrome, Firefox)*/ || window.pageYOffset /*Modern IE, including IE11*/ || document.documentElement.scrollTop /*Old IE, 6,7,8*/ ; /* Calculate position */ var topscroll = (((document.documentElement.clientHeight / 2) + tscroll) + "px"); /* Make POSITION ABSOLUTE so iOS devices can interact with DateTimePicker */ jQuery('.dtpicker-mobile').css('position', 'absolute'); jQuery('.dtpicker-cont').css('position', 'absolute'); /* Scroll DateTimePicker into position */ jQuery('.dtpicker-cont').css('top', topscroll); } } /* WINDOW EVENTLISTENER to LOAD and SCROLL */ if (window.addEventListener) { window.addEventListener('load', dtpickerContMoveiOS, false); window.addEventListener('scroll', dtpickerContMoveiOS, false); } else if (window.attachEvent) { window.attachEvent('on' + 'load', dtpickerContMoveiOS); window.attachEvent('on' + 'scroll', dtpickerContMoveiOS); } else { window['on' + 'load'] = dtpickerContMoveiOS; window['on' + 'scroll'] = dtpickerContMoveiOS; } /* Makes readonly INPUTS on iOS correctly work */ $(function() { $('input[readonly]').on('focus', function(ev) { $(this).trigger('blur'); }); }); } ```
/content/code_sandbox/public/vendor/datetimepicker/src/DateTimePicker_iOS_fix.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
474
```css /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ .dtpicker-overlay { z-index: 2000; display:none; min-width: 300px; background: rgba(0, 0, 0, 0.2); font-size: 12px; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .dtpicker-mobile { position: fixed; top: 0; left: 0; width: 100%; height: 100%; } .dtpicker-overlay * { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; -ms-box-sizing: border-box; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); } .dtpicker-bg { width: 100%; height: 100%; font-family: Arial; } .dtpicker-cont { border: 1px solid #ECF0F1; } .dtpicker-mobile .dtpicker-cont { position: relative; top: 50%; -webkit-transform: translateY(-50%); -moz-transform: translateY(-50%); -o-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); border: none; } .dtpicker-content { margin: 0 auto; padding: 1em 0; max-width: 500px; background: #fff; } .dtpicker-mobile .dtpicker-content { width: 97%; } .dtpicker-subcontent { position: relative; } .dtpicker-header { margin: 0.2em 1em; } .dtpicker-header .dtpicker-title { color: #2980B9; text-align: center; font-size: 1.1em; } .dtpicker-header .dtpicker-close { position: absolute; top: -0.7em; right: 0.3em; padding: 0.5em 0.5em 1em 1em; color: #FF3B30; font-size: 1.5em; cursor: pointer; } .dtpicker-header .dtpicker-close:hover { color: #FF3B30; } .dtpicker-header .dtpicker-value { padding: 0.8em 0.2em 0.2em 0.2em; color: #FF3B30; text-align: center; font-size: 1.4em; } .dtpicker-components { overflow: hidden; margin: 1em 1em; font-size: 1.3em; } .dtpicker-components * { margin: 0; padding: 0; } .dtpicker-components .dtpicker-compOutline { display: inline-block; float: left; } .dtpicker-comp2 { width: 50%; } .dtpicker-comp3 { width: 33.3%; } .dtpicker-comp4 { width: 25%; } .dtpicker-comp5 { width: 20%; } .dtpicker-comp6 { width: 16.66%; } .dtpicker-comp7 { width: 14.285%; } .dtpicker-components .dtpicker-comp { margin: 2%; text-align: center; } .dtpicker-components .dtpicker-comp > * { display: block; height: 30px; color: #2980B9; text-align: center; line-height: 30px; } .dtpicker-components .dtpicker-comp > *:hover { color: #2980B9; } .dtpicker-components .dtpicker-compButtonEnable { opacity: 1; } .dtpicker-components .dtpicker-compButtonDisable { opacity: 0.5; } .dtpicker-components .dtpicker-compButton { background: #FFFFFF; font-size: 140%; cursor: pointer; } .dtpicker-components .dtpicker-compValue { margin: 0.4em 0; width: 100%; border: none; background: #FFFFFF; font-size: 100%; -webkit-appearance: none; -moz-appearance: none; } .dtpicker-overlay .dtpicker-compValue:focus { outline: none; background: #F2FCFF; } .dtpicker-buttonCont { overflow: hidden; margin: 0.2em 1em; } .dtpicker-buttonCont .dtpicker-button { display: block; padding: 0.6em 0; width: 47%; background: #FF3B30; color: #FFFFFF; text-align: center; font-size: 1.3em; cursor: pointer; } .dtpicker-buttonCont .dtpicker-button:hover { color: #FFFFFF; } .dtpicker-singleButton .dtpicker-button { margin: 0.2em auto; } .dtpicker-twoButtons .dtpicker-buttonSet { float: left; } .dtpicker-twoButtons .dtpicker-buttonClear { float: right; } ```
/content/code_sandbox/public/vendor/datetimepicker/src/DateTimePicker.css
css
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
1,153
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length; var from = Number(arguments[1]) || 0; from = (from < 0) ? Math.ceil(from) : Math.floor(from); if (from < 0) from += len; for (; from < len; from++) { if (from in this && this[from] === elt) return from; } return -1; }; } jQuery.fn.fadeIn = function() { this.show(); } jQuery.fn.fadeOut = function() { this.hide(); } ```
/content/code_sandbox/public/vendor/datetimepicker/src/DateTimePicker-ltie9.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
204
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ /* language: Spanish file: DateTimePicker-i18n-es author: kristophone(path_to_url */ (function ($) { $.DateTimePicker.i18n["es"] = $.extend($.DateTimePicker.i18n["es"], { language: "es", dateTimeFormat: "dd-MMM-yyyy HH:mm:ss", dateFormat: "dd-MMM-yyyy", timeFormat: "HH:mm:ss", shortDayNames: ["Dom", "Lun", "Mar", "Mi", "Jue", "Vie", "Sb"], fullDayNames: ["Domingo", "Lunes", "Martes", "Mircoles", "Jueves", "Viernes", "Sbado"], shortMonthNames: ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"], fullMonthNames: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"], titleContentDate: "Ingresar fecha", titleContentTime: "Ingresar hora", titleContentDateTime: "Ingresar fecha y hora", setButtonContent: "Guardar", clearButtonContent: "Cancelar", formatHumanDate: function(oDate, sMode, sFormat) { if(sMode === "date") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ ", " + oDate.yyyy; else if(sMode === "time") return oDate.HH + ":" + oDate.mm + ":" + oDate.ss; else if(sMode === "datetime") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ ", " + oDate.yyyy + " " + oDate.HH + ":" + oDate.mm + ":" + oDate.ss; } }); })(jQuery); ```
/content/code_sandbox/public/vendor/datetimepicker/src/i18n/DateTimePicker-i18n-es.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
519
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ /* language: Romanian file: DateTimePicker-i18n-nl author: Radu Mogo(path_to_url */ (function ($) { $.DateTimePicker.i18n["ro"] = $.extend($.DateTimePicker.i18n["ro"], { language: "ro", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", shortDayNames: ["Dum", "Lun", "Mar", "Mie", "Joi", "Vim", "Sm"], fullDayNames: ["Duminic", "Luni", "Mari", "Miercuri", "Joi", "Vineri", "Smbt"], shortMonthNames: ["Ian", "Feb", "Mar", "Apr", "Mai", "Iun", "Iul", "Aug", "Sep", "Oct", "Noi", "Dec"], fullMonthNames: ["Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"], titleContentDate: "Setare Dat", titleContentTime: "Setare Or", titleContentDateTime: "Setare Dat i Or", setButtonContent: "Seteaz", clearButtonContent: "terge" }); })(jQuery); ```
/content/code_sandbox/public/vendor/datetimepicker/src/i18n/DateTimePicker-i18n-ro.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
383
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ /* language: Traditional Chinese file: DateTimePicker-i18n-zh-TW author: JasonYCHuang (path_to_url */ (function ($) { $.DateTimePicker.i18n["zh-TW"] = $.extend($.DateTimePicker.i18n["zh-TW"], { language: "zh-TW", labels: { 'year': '', 'month': '', 'day': '', 'hour': '', 'minutes': '', 'seconds': '', 'meridiem': '' }, dateTimeFormat: "yyyy-MM-dd HH:mm", dateFormat: "yyyy-MM-dd", timeFormat: "HH:mm", shortDayNames: ['', '', '', '', '', '', ''], fullDayNames: ['', '', '', '', '', '', ''], shortMonthNames: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'], fullMonthNames: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'], titleContentDate: "", titleContentTime: "", titleContentDateTime: "", setButtonContent: "", clearButtonContent: "", formatHumanDate: function (oDate, sMode, sFormat) { if (sMode === "date") return oDate.dayShort + ", " + oDate.yyyy + "" + oDate.month +"" + oDate.dd + ""; else if (sMode === "time") return oDate.HH + "" + oDate.mm + "" + oDate.ss + ""; else if (sMode === "datetime") return oDate.dayShort + ", " + oDate.yyyy + "" + oDate.month +"" + oDate.dd + " " + oDate.HH + "" + oDate.mm + ""; } }); })(jQuery); ```
/content/code_sandbox/public/vendor/datetimepicker/src/i18n/DateTimePicker-i18n-zh-TW.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
487
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ /* language: Simple Chinese file: DateTimePicker-i18n-zh-CN author: Calvin(path_to_url */ (function ($) { $.DateTimePicker.i18n["zh-CN"] = $.extend($.DateTimePicker.i18n["zh-CN"], { language: "zh-CN", labels: { 'year': '', 'month': '', 'day': '', 'hour': '', 'minutes': '', 'seconds': '', 'meridiem': '' }, dateTimeFormat: "yyyy-MM-dd HH:mm", dateFormat: "yyyy-MM-dd", timeFormat: "HH:mm", shortDayNames: ['', '', '', '', '', '', ''], fullDayNames: ['', '', '', '', '', '', ''], shortMonthNames: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'], fullMonthNames: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'], titleContentDate: "", titleContentTime: "", titleContentDateTime: "", setButtonContent: "", clearButtonContent: "", formatHumanDate: function (oDate, sMode, sFormat) { if (sMode === "date") return oDate.dayShort + ", " + oDate.yyyy + "" + oDate.month +"" + oDate.dd + ""; else if (sMode === "time") return oDate.HH + "" + oDate.mm + "" + oDate.ss + ""; else if (sMode === "datetime") return oDate.dayShort + ", " + oDate.yyyy + "" + oDate.month +"" + oDate.dd + " " + oDate.HH + "" + oDate.mm + ""; } }); })(jQuery); ```
/content/code_sandbox/public/vendor/datetimepicker/src/i18n/DatetimePicker-i18n-zh-CN.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
478
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ /* language: Japanese file: DateTimePicker-i18n-ja author: JasonYCHuang (path_to_url */ (function ($) { $.DateTimePicker.i18n["ja"] = $.extend($.DateTimePicker.i18n["ja"], { language: "ja", labels: { 'year': '', 'month': '', 'day': '', 'hour': '', 'minutes': '', 'seconds': '', 'meridiem': '' }, dateTimeFormat: "yyyy-MM-dd HH:mm", dateFormat: "yyyy-MM-dd", timeFormat: "HH:mm", shortDayNames: ['', '', '', '', '', '', ''], fullDayNames: ['', '', '', '', '', '', ''], shortMonthNames: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'], fullMonthNames: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'], titleContentDate: "", titleContentTime: "", titleContentDateTime: "", setButtonContent: "", clearButtonContent: "", formatHumanDate: function (oDate, sMode, sFormat) { if (sMode === "date") return oDate.dayShort + ", " + oDate.yyyy + "" + oDate.month +"" + oDate.dd + ""; else if (sMode === "time") return oDate.HH + "" + oDate.mm + "" + oDate.ss + ""; else if (sMode === "datetime") return oDate.dayShort + ", " + oDate.yyyy + "" + oDate.month +"" + oDate.dd + " " + oDate.HH + "" + oDate.mm + ""; } }); })(jQuery); ```
/content/code_sandbox/public/vendor/datetimepicker/src/i18n/DateTimePicker-i18n-ja.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
478
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ /* language: English file: DateTimePicker-i18n-en */ (function ($) { $.DateTimePicker.i18n["en"] = $.extend($.DateTimePicker.i18n["en"], { language: "en", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", shortDayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], fullDayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], shortMonthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], fullMonthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], titleContentDate: "Set Date", titleContentTime: "Set Time", titleContentDateTime: "Set Date & Time", setButtonContent: "Set", clearButtonContent: "Clear" }); })(jQuery); ```
/content/code_sandbox/public/vendor/datetimepicker/src/i18n/DateTimePicker-i18n-en.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
327
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ /* language: Korean file: DateTimePicker-i18n-ko */ (function ($) { $.DateTimePicker.i18n["ko"] = $.extend($.DateTimePicker.i18n["ko"], { language: "ko", labels: { 'year': '', 'month': '', 'day': '', 'hour': '', 'minutes': '', 'seconds': '', 'meridiem': '' }, dateTimeFormat: "yyyy-MM-dd HH:mm", dateFormat: "yyyy-MM-dd", timeFormat: "HH:mm", shortDayNames: ["", "", "", "", "", "", ""], fullDayNames: ["", "", "", "", "", "", ""], shortMonthNames: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"], fullMonthNames: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"], titleContentDate: " ", titleContentTime: " ", titleContentDateTime: " ", setButtonContent: "", clearButtonContent: "" }); })(jQuery); ```
/content/code_sandbox/public/vendor/datetimepicker/src/i18n/DateTimePicker-i18n-ko.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
346
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ /* language: Dutch file: DateTimePicker-i18n-nl author: Bernardo(path_to_url */ (function ($) { $.DateTimePicker.i18n["nl"] = $.extend($.DateTimePicker.i18n["nl"], { language: "nl", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", shortDayNames: ["zo", "ma", "di", "wo", "do", "vr", "za"], fullDayNames: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"], shortMonthNames: ["jan", "feb", "mrt", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec"], fullMonthNames: ["januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"], titleContentDate: "Kies datum", titleContentTime: "Kies tijd", titleContentDateTime: "Kies datum & tijd", setButtonContent: "Kiezen", clearButtonContent: "Leegmaken" }); })(jQuery); ```
/content/code_sandbox/public/vendor/datetimepicker/src/i18n/DateTimePicker-i18n-nl.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
377
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ /* language: Russian file: DateTimePicker-i18n-ru author: Valery Bogdanov (path_to_url */ (function ($) { $.DateTimePicker.i18n["ru"] = $.extend($.DateTimePicker.i18n["ru"], { language: "ru", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", shortDayNames: ["", "", "", "", "", "", ""], fullDayNames: ["", "", "", "", "", "", ""], shortMonthNames: ["", "", "", "", "", "", "", "", "", "", "", ""], fullMonthNames: ["", "", "", "", "", "", "", "", "", "", "", ""], titleContentDate: " ", titleContentTime: " ", titleContentDateTime: " ", setButtonContent: "", clearButtonContent: "", formatHumanDate: function(oDate, sMode, sFormat) { if(sMode === "date") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ " " + oDate.yyyy; else if(sMode === "time") return oDate.HH + ":" + oDate.mm + ":" + oDate.ss; else if(sMode === "datetime") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ " " + oDate.yyyy + ", " + oDate.HH + ":" + oDate.mm + ":" + oDate.ss; } }); })(jQuery); ```
/content/code_sandbox/public/vendor/datetimepicker/src/i18n/DateTimePicker-i18n-ru.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
402
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ /* language: French file: DateTimePicker-i18n-fr author: LivioGama(path_to_url */ (function ($) { $.DateTimePicker.i18n["fr"] = $.extend($.DateTimePicker.i18n["fr"], { language: "fr", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", shortDayNames: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"], fullDayNames: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"], shortMonthNames: ["Jan", "Fv", "Mar", "Avr", "Mai", "Jun", "Jul", "Ao", "Sep", "Oct", "Nov", "Dc"], fullMonthNames: ["Janvier", "Fvrier", "Mars", "Avril", "Mai", "Juin", "Juillet", "Aot", "Septembre", "Octobre", "Novembre", "Dcembre"], titleContentDate: "Choisir une date", titleContentTime: "Choisir un horaire", titleContentDateTime: "Choisir une date et un horaire", setButtonContent: "Choisir", clearButtonContent: "Effacer", formatHumanDate: function(oDate, sMode, sFormat) { if(sMode === "date") return oDate.dayShort + " " + oDate.dd + " " + oDate.month+ " " + oDate.yyyy; else if(sMode === "time") return oDate.HH + ":" + oDate.mm + ":" + oDate.ss; else if(sMode === "datetime") return oDate.dayShort + " " + oDate.dd + " " + oDate.month+ " " + oDate.yyyy + ", " + oDate.HH + ":" + oDate.mm + ":" + oDate.ss; } }); })(jQuery); ```
/content/code_sandbox/public/vendor/datetimepicker/src/i18n/DateTimePicker-i18n-fr.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
525
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ /* language: Czech file: DateTimePicker-i18n-cs author: aiphee (path_to_url */ (function ($) { $.DateTimePicker.i18n["cs"] = $.extend($.DateTimePicker.i18n["cs"], { language: "cs", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", shortDayNames: ["Ne", "Po", "t", "St", "t", "P", "So"], fullDayNames: ["Nedle", "Pondl", "ter", "Steda", "tvrtek", "Ptek", "Sobota"], shortMonthNames: ["Led", "no", "Be", "Dub", "Kv", "er", "vc", "Srp", "Z", "j", "Lis", "Pro"], fullMonthNames: ["Leden", "nor", "Bezen", "Duben", "Kvten", "erven", "ervenec", "Srpen", "Z", "jen", "Listopad", "Prosinec"], titleContentDate: "Nastavit datum", titleContentTime: "Nastavit as", titleContentDateTime: "Nastavit datum a as", setButtonContent: "Nastavit", clearButtonContent: "Resetovat" }); })(jQuery); /* language: German file: DateTimePicker-i18n-de author: Lu, Feng (path_to_url */ (function ($) { $.DateTimePicker.i18n["de"] = $.extend($.DateTimePicker.i18n["de"], { language: "de", dateTimeFormat: "dd-MMM-yyyy HH:mm:ss", dateFormat: "dd-MMM-yyyy", timeFormat: "HH:mm:ss", shortDayNames: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"], fullDayNames: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"], shortMonthNames: ["Jan", "Feb", "Mr", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"], fullMonthNames: ["Januar", "Februar", "Mrz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"], titleContentDate: "Datum auswhlen", titleContentTime: "Zeit auswhlen", titleContentDateTime: "Datum & Zeit auswhlen", setButtonContent: "Auswhlen", clearButtonContent: "Zurcksetzen", formatHumanDate: function(oDate, sMode, sFormat) { if(sMode === "date") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ ", " + oDate.yyyy; else if(sMode === "time") return oDate.HH + ":" + oDate.mm + ":" + oDate.ss; else if(sMode === "datetime") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ ", " + oDate.yyyy + " " + oDate.HH + ":" + oDate.mm + ":" + oDate.ss; } }); })(jQuery); /* language: English file: DateTimePicker-i18n-en */ (function ($) { $.DateTimePicker.i18n["en"] = $.extend($.DateTimePicker.i18n["en"], { language: "en", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", shortDayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], fullDayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], shortMonthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], fullMonthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], titleContentDate: "Set Date", titleContentTime: "Set Time", titleContentDateTime: "Set Date & Time", setButtonContent: "Set", clearButtonContent: "Clear" }); })(jQuery); /* language: Spanish file: DateTimePicker-i18n-es author: kristophone(path_to_url */ (function ($) { $.DateTimePicker.i18n["es"] = $.extend($.DateTimePicker.i18n["es"], { language: "es", dateTimeFormat: "dd-MMM-yyyy HH:mm:ss", dateFormat: "dd-MMM-yyyy", timeFormat: "HH:mm:ss", shortDayNames: ["Dom", "Lun", "Mar", "Mi", "Jue", "Vie", "Sb"], fullDayNames: ["Domingo", "Lunes", "Martes", "Mircoles", "Jueves", "Viernes", "Sbado"], shortMonthNames: ["Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic"], fullMonthNames: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"], titleContentDate: "Ingresar fecha", titleContentTime: "Ingresar hora", titleContentDateTime: "Ingresar fecha y hora", setButtonContent: "Guardar", clearButtonContent: "Cancelar", formatHumanDate: function(oDate, sMode, sFormat) { if(sMode === "date") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ ", " + oDate.yyyy; else if(sMode === "time") return oDate.HH + ":" + oDate.mm + ":" + oDate.ss; else if(sMode === "datetime") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ ", " + oDate.yyyy + " " + oDate.HH + ":" + oDate.mm + ":" + oDate.ss; } }); })(jQuery); /* language: French file: DateTimePicker-i18n-fr author: LivioGama(path_to_url */ (function ($) { $.DateTimePicker.i18n["fr"] = $.extend($.DateTimePicker.i18n["fr"], { language: "fr", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", shortDayNames: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"], fullDayNames: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"], shortMonthNames: ["Jan", "Fv", "Mar", "Avr", "Mai", "Jun", "Jul", "Ao", "Sep", "Oct", "Nov", "Dc"], fullMonthNames: ["Janvier", "Fvrier", "Mars", "Avril", "Mai", "Juin", "Juillet", "Aot", "Septembre", "Octobre", "Novembre", "Dcembre"], titleContentDate: "Choisir une date", titleContentTime: "Choisir un horaire", titleContentDateTime: "Choisir une date et un horaire", setButtonContent: "Choisir", clearButtonContent: "Effacer", formatHumanDate: function(oDate, sMode, sFormat) { if(sMode === "date") return oDate.dayShort + " " + oDate.dd + " " + oDate.month+ " " + oDate.yyyy; else if(sMode === "time") return oDate.HH + ":" + oDate.mm + ":" + oDate.ss; else if(sMode === "datetime") return oDate.dayShort + " " + oDate.dd + " " + oDate.month+ " " + oDate.yyyy + ", " + oDate.HH + ":" + oDate.mm + ":" + oDate.ss; } }); })(jQuery); /* language: Italiano file: DateTimePicker-i18n-it author: Cristian Segattini */ (function ($) { $.DateTimePicker.i18n["it"] = $.extend($.DateTimePicker.i18n["it"], { language: "it", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", shortDayNames: ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"], fullDayNames: ["Domenica", "Luned", "Marted", "Mercoled", "Gioved", "Venerd", "Sabato"], shortMonthNames: ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"], fullMonthNames: ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"], titleContentDate: "Imposta Data", titleContentTime: "Imposta Ora", titleContentDateTime: "Imposta Data & Ora", setButtonContent: "Imposta", clearButtonContent: "Pulisci" }); })(jQuery); /* language: Japanese file: DateTimePicker-i18n-ja author: JasonYCHuang (path_to_url */ (function ($) { $.DateTimePicker.i18n["ja"] = $.extend($.DateTimePicker.i18n["ja"], { language: "ja", labels: { 'year': '', 'month': '', 'day': '', 'hour': '', 'minutes': '', 'seconds': '', 'meridiem': '' }, dateTimeFormat: "yyyy-MM-dd HH:mm", dateFormat: "yyyy-MM-dd", timeFormat: "HH:mm", shortDayNames: ['', '', '', '', '', '', ''], fullDayNames: ['', '', '', '', '', '', ''], shortMonthNames: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'], fullMonthNames: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'], titleContentDate: "", titleContentTime: "", titleContentDateTime: "", setButtonContent: "", clearButtonContent: "", formatHumanDate: function (oDate, sMode, sFormat) { if (sMode === "date") return oDate.dayShort + ", " + oDate.yyyy + "" + oDate.month +"" + oDate.dd + ""; else if (sMode === "time") return oDate.HH + "" + oDate.mm + "" + oDate.ss + ""; else if (sMode === "datetime") return oDate.dayShort + ", " + oDate.yyyy + "" + oDate.month +"" + oDate.dd + " " + oDate.HH + "" + oDate.mm + ""; } }); })(jQuery); /* language: Norsk Bokml file: DateTimePicker-i18n-nb author: Tommy Eliassen (path_to_url */ (function ($) { $.DateTimePicker.i18n["nb"] = $.extend($.DateTimePicker.i18n["nb"], { language: "nb", dateTimeFormat: "dd.MM.yyyy HH:mm", dateFormat: "dd.MM.yyyy", timeFormat: "HH:mm", dateSeparator: ".", shortDayNames: ["Sn", "Man", "Tir", "Ons", "Tor", "Fre", "Lr"], fullDayNames: ["Sndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lrdag"], shortMonthNames: ["Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Des"], fullMonthNames: ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"], titleContentDate: "Sett Dato", titleContentTime: "Sett Klokkeslett", titleContentDateTime: "Sett Dato & Klokkeslett", setButtonContent: "Bruk", clearButtonContent: "Nullstill" }); })(jQuery); /* language: Dutch file: DateTimePicker-i18n-nl author: Bernardo(path_to_url */ (function ($) { $.DateTimePicker.i18n["nl"] = $.extend($.DateTimePicker.i18n["nl"], { language: "nl", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", shortDayNames: ["zo", "ma", "di", "wo", "do", "vr", "za"], fullDayNames: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"], shortMonthNames: ["jan", "feb", "mrt", "apr", "mei", "jun", "jul", "aug", "sep", "okt", "nov", "dec"], fullMonthNames: ["januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"], titleContentDate: "Kies datum", titleContentTime: "Kies tijd", titleContentDateTime: "Kies datum & tijd", setButtonContent: "Kiezen", clearButtonContent: "Leegmaken" }); })(jQuery); /* language: Romanian file: DateTimePicker-i18n-nl author: Radu Mogo(path_to_url */ (function ($) { $.DateTimePicker.i18n["ro"] = $.extend($.DateTimePicker.i18n["ro"], { language: "ro", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", shortDayNames: ["Dum", "Lun", "Mar", "Mie", "Joi", "Vim", "Sm"], fullDayNames: ["Duminic", "Luni", "Mari", "Miercuri", "Joi", "Vineri", "Smbt"], shortMonthNames: ["Ian", "Feb", "Mar", "Apr", "Mai", "Iun", "Iul", "Aug", "Sep", "Oct", "Noi", "Dec"], fullMonthNames: ["Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"], titleContentDate: "Setare Dat", titleContentTime: "Setare Or", titleContentDateTime: "Setare Dat i Or", setButtonContent: "Seteaz", clearButtonContent: "terge" }); })(jQuery); /* language: Russian file: DateTimePicker-i18n-ru author: Valery Bogdanov (path_to_url */ (function ($) { $.DateTimePicker.i18n["ru"] = $.extend($.DateTimePicker.i18n["ru"], { language: "ru", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", shortDayNames: ["", "", "", "", "", "", ""], fullDayNames: ["", "", "", "", "", "", ""], shortMonthNames: ["", "", "", "", "", "", "", "", "", "", "", ""], fullMonthNames: ["", "", "", "", "", "", "", "", "", "", "", ""], titleContentDate: " ", titleContentTime: " ", titleContentDateTime: " ", setButtonContent: "", clearButtonContent: "", formatHumanDate: function(oDate, sMode, sFormat) { if(sMode === "date") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ " " + oDate.yyyy; else if(sMode === "time") return oDate.HH + ":" + oDate.mm + ":" + oDate.ss; else if(sMode === "datetime") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ " " + oDate.yyyy + ", " + oDate.HH + ":" + oDate.mm + ":" + oDate.ss; } }); })(jQuery); /* language: Ukrainian file: DateTimePicker-i18n-uk author: Valery Bogdanov (path_to_url */ (function ($) { $.DateTimePicker.i18n["uk"] = $.extend($.DateTimePicker.i18n["uk"], { language: "uk", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", shortDayNames: ["", "", "", "", "", "", ""], fullDayNames: ["", "", "", "", "", "", ""], shortMonthNames: ["", "", "", "", "", "", "", "", "", "", "", ""], fullMonthNames: ["", "", "", "", "", "", "", "", "", "", "", ""], fullDayNames: ["", "", "", "", "", "'", ""], shortMonthNames: ["", "", "", "", "", "", "", "", "", "", "", ""], fullMonthNames: ["", "", "", "", "", "", "", "", "", "", "", ""], titleContentDate: " ", titleContentTime: " ", titleContentDateTime: " ", setButtonContent: "", clearButtonContent: "", formatHumanDate: function(oDate, sMode, sFormat) { if(sMode === "date") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ " " + oDate.yyyy; else if(sMode === "time") return oDate.HH + ":" + oDate.mm + ":" + oDate.ss; else if(sMode === "datetime") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ " " + oDate.yyyy + ", " + oDate.HH + ":" + oDate.mm + ":" + oDate.ss; } }); })(jQuery); /* language: Traditional Chinese file: DateTimePicker-i18n-zh-TW author: JasonYCHuang (path_to_url */ (function ($) { $.DateTimePicker.i18n["zh-TW"] = $.extend($.DateTimePicker.i18n["zh-TW"], { language: "zh-TW", labels: { 'year': '', 'month': '', 'day': '', 'hour': '', 'minutes': '', 'seconds': '', 'meridiem': '' }, dateTimeFormat: "yyyy-MM-dd HH:mm", dateFormat: "yyyy-MM-dd", timeFormat: "HH:mm", shortDayNames: ['', '', '', '', '', '', ''], fullDayNames: ['', '', '', '', '', '', ''], shortMonthNames: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'], fullMonthNames: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'], titleContentDate: "", titleContentTime: "", titleContentDateTime: "", setButtonContent: "", clearButtonContent: "", formatHumanDate: function (oDate, sMode, sFormat) { if (sMode === "date") return oDate.dayShort + ", " + oDate.yyyy + "" + oDate.month +"" + oDate.dd + ""; else if (sMode === "time") return oDate.HH + "" + oDate.mm + "" + oDate.ss + ""; else if (sMode === "datetime") return oDate.dayShort + ", " + oDate.yyyy + "" + oDate.month +"" + oDate.dd + " " + oDate.HH + "" + oDate.mm + ""; } }); })(jQuery); /* language: Simple Chinese file: DateTimePicker-i18n-zh-CN author: Calvin(path_to_url */ (function ($) { $.DateTimePicker.i18n["zh-CN"] = $.extend($.DateTimePicker.i18n["zh-CN"], { language: "zh-CN", labels: { 'year': '', 'month': '', 'day': '', 'hour': '', 'minutes': '', 'seconds': '', 'meridiem': '' }, dateTimeFormat: "yyyy-MM-dd HH:mm", dateFormat: "yyyy-MM-dd", timeFormat: "HH:mm", shortDayNames: ['', '', '', '', '', '', ''], fullDayNames: ['', '', '', '', '', '', ''], shortMonthNames: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'], fullMonthNames: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'], titleContentDate: "", titleContentTime: "", titleContentDateTime: "", setButtonContent: "", clearButtonContent: "", formatHumanDate: function (oDate, sMode, sFormat) { if (sMode === "date") return oDate.dayShort + ", " + oDate.yyyy + "" + oDate.month +"" + oDate.dd + ""; else if (sMode === "time") return oDate.HH + "" + oDate.mm + "" + oDate.ss + ""; else if (sMode === "datetime") return oDate.dayShort + ", " + oDate.yyyy + "" + oDate.month +"" + oDate.dd + " " + oDate.HH + "" + oDate.mm + ""; } }); })(jQuery); ```
/content/code_sandbox/public/vendor/datetimepicker/src/i18n/DateTimePicker-i18n.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
5,299
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ /* language: Norsk Bokml file: DateTimePicker-i18n-nb author: Tommy Eliassen (path_to_url */ (function ($) { $.DateTimePicker.i18n["nb"] = $.extend($.DateTimePicker.i18n["nb"], { language: "nb", dateTimeFormat: "dd.MM.yyyy HH:mm", dateFormat: "dd.MM.yyyy", timeFormat: "HH:mm", dateSeparator: ".", shortDayNames: ["Sn", "Man", "Tir", "Ons", "Tor", "Fre", "Lr"], fullDayNames: ["Sndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lrdag"], shortMonthNames: ["Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Des"], fullMonthNames: ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"], titleContentDate: "Sett Dato", titleContentTime: "Sett Klokkeslett", titleContentDateTime: "Sett Dato & Klokkeslett", setButtonContent: "Bruk", clearButtonContent: "Nullstill" }); })(jQuery); ```
/content/code_sandbox/public/vendor/datetimepicker/src/i18n/DateTimePicker-i18n-nb.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
386
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ /* Support Object.keys in IE8 */ if(!Object.keys) { Object.keys = function(obj) { var keys = []; for (var i in obj) { if (obj.hasOwnProperty(i)) { keys.push(i); } } return keys; }; } $.DateTimePicker = $.DateTimePicker || { name: "DateTimePicker", i18n: {}, // Internationalization Objects defaults: //Plugin Defaults { mode: "date", defaultDate: null, dateSeparator: "-", timeSeparator: ":", timeMeridiemSeparator: " ", dateTimeSeparator: " ", monthYearSeparator: " ", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", maxDate: null, minDate: null, maxTime: null, minTime: null, maxDateTime: null, minDateTime: null, shortDayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], fullDayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], shortMonthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], fullMonthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], labels: null, /*{"year": "Year", "month": "Month", "day": "Day", "hour": "Hour", "minutes": "Minutes", "seconds": "Seconds", "meridiem": "Meridiem"}*/ minuteInterval: 1, roundOffMinutes: true, secondsInterval: 1, roundOffSeconds: true, showHeader: true, titleContentDate: "Set Date", titleContentTime: "Set Time", titleContentDateTime: "Set Date & Time", buttonsToDisplay: ["HeaderCloseButton", "SetButton", "ClearButton"], setButtonContent: "Set", clearButtonContent: "Clear", incrementButtonContent: "+", decrementButtonContent: "-", setValueInTextboxOnEveryClick: false, readonlyInputs: false, animationDuration: 400, touchHoldInterval: 300, // in Milliseconds captureTouchHold: false, // capture Touch Hold Event mouseHoldInterval: 50, // in Milliseconds captureMouseHold: false, // capture Mouse Hold Event isPopup: true, parentElement: "body", isInline: false, inputElement: null, language: "", init: null, // init(oDateTimePicker) addEventHandlers: null, // addEventHandlers(oDateTimePicker) beforeShow: null, // beforeShow(oInputElement) afterShow: null, // afterShow(oInputElement) beforeHide: null, // beforeHide(oInputElement) afterHide: null, // afterHide(oInputElement) buttonClicked: null, // buttonClicked(sButtonType, oInputElement) where sButtonType = "SET"|"CLEAR"|"CANCEL"|"TAB" settingValueOfElement: null, // settingValueOfElement(sValue, dDateTime, oInputElement) formatHumanDate: null, // formatHumanDate(oDateTime, sMode, sFormat) parseDateTimeString: null, // parseDateTimeString(sDateTime, sMode, sFormat, oInputField) formatDateTimeString: null // formatDateTimeString(oDateTime, sMode, sFormat, oInputField) }, dataObject: // Temporary Variables For Calculation Specific to DateTimePicker Instance { dCurrentDate: new Date(), iCurrentDay: 0, iCurrentMonth: 0, iCurrentYear: 0, iCurrentHour: 0, iCurrentMinutes: 0, iCurrentSeconds: 0, sCurrentMeridiem: "", iMaxNumberOfDays: 0, sDateFormat: "", sTimeFormat: "", sDateTimeFormat: "", dMinValue: null, dMaxValue: null, sArrInputDateFormats: [], sArrInputTimeFormats: [], sArrInputDateTimeFormats: [], bArrMatchFormat: [], bDateMode: false, bTimeMode: false, bDateTimeMode: false, oInputElement: null, iTabIndex: 0, bElemFocused: false, bIs12Hour: false, sTouchButton: null, iTouchStart: null, oTimeInterval: null, bIsTouchDevice: "ontouchstart" in document.documentElement } }; $.cf = { _isValid: function(sValue) { return (sValue !== undefined && sValue !== null && sValue !== ""); }, _compare: function(sString1, sString2) { var bString1 = (sString1 !== undefined && sString1 !== null), bString2 = (sString2 !== undefined && sString2 !== null); if(bString1 && bString2) { if(sString1.toLowerCase() === sString2.toLowerCase()) return true; else return false; } else return false; } }; (function (factory) { if(typeof define === "function" && define.amd) { // AMD. Register as an anonymous module. define(["jquery"], factory); } else if(typeof exports === "object") { // Node/CommonJS module.exports = factory(require("jquery")); } else { // Browser globals factory(jQuery); } }(function ($) { "use strict"; function DateTimePicker(element, options) { this.element = element; var sLanguage = ""; sLanguage = ($.cf._isValid(options) && $.cf._isValid(options.language)) ? options.language : $.DateTimePicker.defaults.language; this.settings = $.extend({}, $.DateTimePicker.defaults, $.DateTimePicker.i18n[sLanguage], options); this.options = options; this.oData = $.extend({}, $.DateTimePicker.dataObject); this._defaults = $.DateTimePicker.defaults; this._name = $.DateTimePicker.name; this.init(); } $.fn.DateTimePicker = function (options) { var oDTP = $(this).data(), sArrDataKeys = oDTP ? Object.keys(oDTP) : [], iKey, sKey; if(typeof options === "string") { if($.cf._isValid(oDTP)) { if(options === "destroy") { if(sArrDataKeys.length > 0) { for(iKey in sArrDataKeys) { sKey = sArrDataKeys[iKey]; if(sKey.search("plugin_DateTimePicker") !== -1) { $(document).unbind("click.DateTimePicker keydown.DateTimePicker keyup.DateTimePicker"); $(this).children().remove(); $(this).removeData(); $(this).unbind(); $(this).removeClass("dtpicker-overlay dtpicker-mobile dtpicker-inline"); oDTP = oDTP[sKey]; console.log("Destroyed DateTimePicker Object"); console.log(oDTP); break; } } } else { console.log("No DateTimePicker Object Defined For This Element"); } } else if(options === "object") { if(sArrDataKeys.length > 0) { for(iKey in sArrDataKeys) { sKey = sArrDataKeys[iKey]; if(sKey.search("plugin_DateTimePicker") !== -1) { return oDTP[sKey]; } } } else { console.log("No DateTimePicker Object Defined For This Element"); } } } } else { return this.each(function() { $.removeData(this, "plugin_DateTimePicker"); if(!$.data(this, "plugin_DateTimePicker")) $.data(this, "plugin_DateTimePicker", new DateTimePicker(this, options)); }); } }; DateTimePicker.prototype = { // Public Method init: function () { var oDTP = this; oDTP._setDateFormatArray(); // Set DateFormatArray oDTP._setTimeFormatArray(); // Set TimeFormatArray oDTP._setDateTimeFormatArray(); // Set DateTimeFormatArray console.log($(oDTP.element).data('parentelement') + " " + $(oDTP.element).attr('data-parentelement')); if($(oDTP.element).data('parentelement') !== undefined) { oDTP.settings.parentElement = $(oDTP.element).data('parentelement'); } if(oDTP.settings.isPopup && !oDTP.settings.isInline) { oDTP._createPicker(); $(oDTP.element).addClass("dtpicker-mobile"); } if(oDTP.settings.isInline) { oDTP._createPicker(); oDTP._showPicker(oDTP.settings.inputElement); } if(oDTP.settings.init) oDTP.settings.init.call(oDTP); oDTP._addEventHandlersForInput(); }, _setDateFormatArray: function() { var oDTP = this; oDTP.oData.sArrInputDateFormats = []; var sDate = ""; // 0 - "dd-MM-yyyy" sDate = "dd" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "yyyy"; oDTP.oData.sArrInputDateFormats.push(sDate); // 1 - "MM-dd-yyyy" sDate = "MM" + oDTP.settings.dateSeparator + "dd" + oDTP.settings.dateSeparator + "yyyy"; oDTP.oData.sArrInputDateFormats.push(sDate); // 2 - "yyyy-MM-dd" sDate = "yyyy" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "dd"; oDTP.oData.sArrInputDateFormats.push(sDate); // 3 - "dd-MMM-yyyy" sDate = "dd" + oDTP.settings.dateSeparator + "MMM" + oDTP.settings.dateSeparator + "yyyy"; oDTP.oData.sArrInputDateFormats.push(sDate); // 4 - "MM yyyy" sDate = "MM" + oDTP.settings.monthYearSeparator + "yyyy"; oDTP.oData.sArrInputDateFormats.push(sDate); // 5 - "MMM yyyy" sDate = "MMM" + oDTP.settings.monthYearSeparator + "yyyy"; oDTP.oData.sArrInputDateFormats.push(sDate); // 6 - "MMM yyyy" sDate = "MMMM" + oDTP.settings.monthYearSeparator + "yyyy"; oDTP.oData.sArrInputDateFormats.push(sDate); // 7 - "yyyy MM" sDate = "yyyy" + oDTP.settings.monthYearSeparator + "MM"; oDTP.oData.sArrInputDateFormats.push(sDate); }, _setTimeFormatArray: function() { var oDTP = this; oDTP.oData.sArrInputTimeFormats = []; var sTime = ""; // 0 - "hh:mm:ss AA" sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss" + oDTP.settings.timeMeridiemSeparator + "AA"; oDTP.oData.sArrInputTimeFormats.push(sTime); // 1 - "HH:mm:ss" sTime = "HH" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss"; oDTP.oData.sArrInputTimeFormats.push(sTime); // 2 - "hh:mm AA" sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeMeridiemSeparator + "AA"; oDTP.oData.sArrInputTimeFormats.push(sTime); // 3 - "HH:mm" sTime = "HH" + oDTP.settings.timeSeparator + "mm"; oDTP.oData.sArrInputTimeFormats.push(sTime); }, _setDateTimeFormatArray: function() { var oDTP = this; oDTP.oData.sArrInputDateTimeFormats = []; var sDate = "", sTime = "", sDateTime = ""; // 0 - "dd-MM-yyyy HH:mm:ss" sDate = "dd" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "yyyy"; sTime = "HH" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // 1 - "dd-MM-yyyy hh:mm:ss AA" sDate = "dd" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "yyyy"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss" + oDTP.settings.timeMeridiemSeparator + "AA"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // 2 - "MM-dd-yyyy HH:mm:ss" sDate = "MM" + oDTP.settings.dateSeparator + "dd" + oDTP.settings.dateSeparator + "yyyy"; sTime = "HH" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // 3 - "MM-dd-yyyy hh:mm:ss AA" sDate = "MM" + oDTP.settings.dateSeparator + "dd" + oDTP.settings.dateSeparator + "yyyy"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss" + oDTP.settings.timeMeridiemSeparator + "AA"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // 4 - "yyyy-MM-dd HH:mm:ss" sDate = "yyyy" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "dd"; sTime = "HH" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // 5 - "yyyy-MM-dd hh:mm:ss AA" sDate = "yyyy" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "dd"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss" + oDTP.settings.timeMeridiemSeparator + "AA"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // 6 - "dd-MMM-yyyy hh:mm:ss" sDate = "dd" + oDTP.settings.dateSeparator + "MMM" + oDTP.settings.dateSeparator + "yyyy"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // 7 - "dd-MMM-yyyy hh:mm:ss AA" sDate = "dd" + oDTP.settings.dateSeparator + "MMM" + oDTP.settings.dateSeparator + "yyyy"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeSeparator + "ss" + oDTP.settings.timeMeridiemSeparator + "AA"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); //-------------- // 8 - "dd-MM-yyyy HH:mm" sDate = "dd" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "yyyy"; sTime = "HH" + oDTP.settings.timeSeparator + "mm"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // 9 - "dd-MM-yyyy hh:mm AA" sDate = "dd" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "yyyy"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeMeridiemSeparator + "AA"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // 10 - "MM-dd-yyyy HH:mm" sDate = "MM" + oDTP.settings.dateSeparator + "dd" + oDTP.settings.dateSeparator + "yyyy"; sTime = "HH" + oDTP.settings.timeSeparator + "mm"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // 11 - "MM-dd-yyyy hh:mm AA" sDate = "MM" + oDTP.settings.dateSeparator + "dd" + oDTP.settings.dateSeparator + "yyyy"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeMeridiemSeparator + "AA"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // 12 - "yyyy-MM-dd HH:mm" sDate = "yyyy" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "dd"; sTime = "HH" + oDTP.settings.timeSeparator + "mm"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // 13 - "yyyy-MM-dd hh:mm AA" sDate = "yyyy" + oDTP.settings.dateSeparator + "MM" + oDTP.settings.dateSeparator + "dd"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeMeridiemSeparator + "AA"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // 14 - "dd-MMM-yyyy hh:mm" sDate = "dd" + oDTP.settings.dateSeparator + "MMM" + oDTP.settings.dateSeparator + "yyyy"; sTime = "hh" + oDTP.settings.timeSeparator + "mm"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); // 15 - "dd-MMM-yyyy hh:mm AA" sDate = "dd" + oDTP.settings.dateSeparator + "MMM" + oDTP.settings.dateSeparator + "yyyy"; sTime = "hh" + oDTP.settings.timeSeparator + "mm" + oDTP.settings.timeMeridiemSeparator + "AA"; sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; oDTP.oData.sArrInputDateTimeFormats.push(sDateTime); }, _matchFormat: function(sMode, sFormat) { var oDTP = this; oDTP.oData.bArrMatchFormat = []; oDTP.oData.bDateMode = false; oDTP.oData.bTimeMode = false; oDTP.oData.bDateTimeMode = false; var oArrInput = [], iTempIndex; sMode = $.cf._isValid(sMode) ? sMode : oDTP.settings.mode; if($.cf._compare(sMode, "date")) { sFormat = $.cf._isValid(sFormat) ? sFormat : oDTP.oData.sDateFormat; oDTP.oData.bDateMode = true; oArrInput = oDTP.oData.sArrInputDateFormats; } else if($.cf._compare(sMode, "time")) { sFormat = $.cf._isValid(sFormat) ? sFormat : oDTP.oData.sTimeFormat; oDTP.oData.bTimeMode = true; oArrInput = oDTP.oData.sArrInputTimeFormats; } else if($.cf._compare(sMode, "datetime")) { sFormat = $.cf._isValid(sFormat) ? sFormat : oDTP.oData.sDateTimeFormat; oDTP.oData.bDateTimeMode = true; oArrInput = oDTP.oData.sArrInputDateTimeFormats; } for(iTempIndex = 0; iTempIndex < oArrInput.length; iTempIndex++) { oDTP.oData.bArrMatchFormat.push( $.cf._compare(sFormat, oArrInput[iTempIndex]) ); } }, _setMatchFormat: function(iArgsLength, sMode, sFormat) { var oDTP = this; if(iArgsLength > 0) oDTP._matchFormat(sMode, sFormat); }, _createPicker: function() { var oDTP = this; if(oDTP.settings.isInline) { $(oDTP.element).addClass("dtpicker-inline"); } else { $(oDTP.element).addClass("dtpicker-overlay"); $(".dtpicker-overlay").click(function(e) { oDTP._hidePicker(""); }); } var sTempStr = ""; sTempStr += "<div class='dtpicker-bg'>"; sTempStr += "<div class='dtpicker-cont'>"; sTempStr += "<div class='dtpicker-content'>"; sTempStr += "<div class='dtpicker-subcontent'>"; sTempStr += "</div>"; sTempStr += "</div>"; sTempStr += "</div>"; sTempStr += "</div>"; $(oDTP.element).html(sTempStr); }, _addEventHandlersForInput: function() { var oDTP = this; if(!oDTP.settings.isInline) { oDTP.oData.oInputElement = null; $(oDTP.settings.parentElement).find("input[type='date'], input[type='time'], input[type='datetime']").each(function() { $(this).attr("data-field", $(this).attr("type")); $(this).attr("type", "text"); }); var sel = "[data-field='date'], [data-field='time'], [data-field='datetime']"; $(oDTP.settings.parentElement).off("focus", sel, oDTP._inputFieldFocus) .on ("focus", sel, {"obj": oDTP}, oDTP._inputFieldFocus) $(oDTP.settings.parentElement).off("click", sel, oDTP._inputFieldClick) .on ("click", sel, {"obj": oDTP}, oDTP._inputFieldClick); } if(oDTP.settings.addEventHandlers) oDTP.settings.addEventHandlers.call(oDTP); }, _inputFieldFocus: function(e) { var oDTP = e.data.obj; oDTP.showDateTimePicker(this); oDTP.oData.bMouseDown = false; }, _inputFieldClick: function(e) { var oDTP = e.data.obj; if(!$.cf._compare($(this).prop("tagName"), "input")) { oDTP.showDateTimePicker(this); } e.stopPropagation(); }, // Public Method getDateObjectForInputField: function(oInputField) { var oDTP = this; if($.cf._isValid(oInputField)) { var sDateTime = oDTP._getValueOfElement(oInputField), sMode = $(oInputField).data("field"), sFormat = "", dInput; if(!$.cf._isValid(sMode)) sMode = oDTP.settings.mode; if(! oDTP.settings.formatDateTimeString) { sFormat = $(oInputField).data("format"); if(!$.cf._isValid(sFormat)) { if($.cf._compare(sMode, "date")) sFormat = oDTP.settings.dateFormat; else if($.cf._compare(sMode, "time")) sFormat = oDTP.settings.timeFormat; else if($.cf._compare(sMode, "datetime")) sFormat = oDTP.settings.dateTimeFormat; } oDTP._matchFormat(sMode, sFormat); if($.cf._compare(sMode, "date")) dInput = oDTP._parseDate(sDateTime); else if($.cf._compare(sMode, "time")) dInput = oDTP._parseTime(sDateTime); else if($.cf._compare(sMode, "datetime")) dInput = oDTP._parseDateTime(sDateTime); } else { dInput = oDTP.settings.parseDateTimeString.call(oDTP, sDateTime, sMode, sFormat, $(oInputField)); } return dInput; } }, // Public Method setDateTimeStringInInputField: function(oInputField, dInput) { var oDTP = this; dInput = dInput || oDTP.oData.dCurrentDate; var oArrElements; if($.cf._isValid(oInputField)) { oArrElements = []; if(typeof oInputField === "string") oArrElements.push(oInputField); else if(typeof oInputField === "object") oArrElements = oInputField; } else { if($.cf._isValid(oDTP.settings.parentElement)) { oArrElements = $(oDTP.settings.parentElement).find("[data-field='date'], [data-field='time'], [data-field='datetime']"); } else { oArrElements = $("[data-field='date'], [data-field='time'], [data-field='datetime']"); } } oArrElements.each(function() { var oElement = this, sMode, sFormat, bIs12Hour, sOutput; sMode = $(oElement).data("field"); if(!$.cf._isValid(sMode)) sMode = oDTP.settings.mode; sFormat = "Custom"; bIs12Hour = false; if(! oDTP.settings.formatDateTimeString) { sFormat = $(oElement).data("format"); if(!$.cf._isValid(sFormat)) { if($.cf._compare(sMode, "date")) sFormat = oDTP.settings.dateFormat; else if($.cf._compare(sMode, "time")) sFormat = oDTP.settings.timeFormat; else if($.cf._compare(sMode, "datetime")) sFormat = oDTP.settings.dateTimeFormat; } bIs12Hour = oDTP.getIs12Hour(sMode, sFormat); } sOutput = oDTP._setOutput(sMode, sFormat, bIs12Hour, dInput, oElement); oDTP._setValueOfElement(sOutput, $(oElement)); }); }, // Public Method getDateTimeStringInFormat: function(sMode, sFormat, dInput) { var oDTP = this; return oDTP._setOutput(sMode, sFormat, oDTP.getIs12Hour(sMode, sFormat), dInput); }, // Public Method showDateTimePicker: function(oElement) { var oDTP = this; if(oDTP.oData.oInputElement !== null) { if(!oDTP.settings.isInline) oDTP._hidePicker(0, oElement); } else oDTP._showPicker(oElement); }, _setButtonAction: function(bFromTab) { var oDTP = this; if(oDTP.oData.oInputElement !== null) { oDTP._setValueOfElement(oDTP._setOutput()); if(bFromTab) { if(oDTP.settings.buttonClicked) oDTP.settings.buttonClicked.call(oDTP, "TAB", oDTP.oData.oInputElement); if(!oDTP.settings.isInline) oDTP._hidePicker(0); } else { if(!oDTP.settings.isInline) oDTP._hidePicker(""); } } }, _setOutput: function(sMode, sFormat, bIs12Hour, dCurrentDate, oElement) { var oDTP = this; dCurrentDate = $.cf._isValid(dCurrentDate) ? dCurrentDate : oDTP.oData.dCurrentDate; bIs12Hour = bIs12Hour || oDTP.oData.bIs12Hour; var oDTV = oDTP._setVariablesForDate(dCurrentDate, true, true); var sOutput = "", oFDate = oDTP._formatDate(oDTV), oFTime = oDTP._formatTime(oDTV), oFDT = $.extend({}, oFDate, oFTime), sDateStr = "", sTimeStr = "", iArgsLength = Function.length, bAddSeconds; if(oDTP.settings.formatDateTimeString) { sOutput = oDTP.settings.formatDateTimeString.call(oDTP, oFDT, sMode, sFormat, oElement); } else { // Set bDate, bTime, bDateTime & bArrMatchFormat based on arguments of this function oDTP._setMatchFormat(iArgsLength, sMode, sFormat); if(oDTP.oData.bDateMode) { if(oDTP.oData.bArrMatchFormat[0]) { sOutput = oFDT.dd + oDTP.settings.dateSeparator + oFDT.MM + oDTP.settings.dateSeparator + oFDT.yyyy; } else if(oDTP.oData.bArrMatchFormat[1]) { sOutput = oFDT.MM + oDTP.settings.dateSeparator + oFDT.dd + oDTP.settings.dateSeparator + oFDT.yyyy; } else if(oDTP.oData.bArrMatchFormat[2]) { sOutput = oFDT.yyyy + oDTP.settings.dateSeparator + oFDT.MM + oDTP.settings.dateSeparator + oFDT.dd; } else if(oDTP.oData.bArrMatchFormat[3]) { sOutput = oFDT.dd + oDTP.settings.dateSeparator + oFDT.monthShort + oDTP.settings.dateSeparator + oFDT.yyyy; } else if(oDTP.oData.bArrMatchFormat[4]) { sOutput = oFDT.MM + oDTP.settings.monthYearSeparator + oFDT.yyyy; } else if(oDTP.oData.bArrMatchFormat[5]) { sOutput = oFDT.monthShort + oDTP.settings.monthYearSeparator + oFDT.yyyy; } else if(oDTP.oData.bArrMatchFormat[6]) { sOutput = oFDT.month + oDTP.settings.monthYearSeparator + oFDT.yyyy; } else if(oDTP.oData.bArrMatchFormat[7]) { sOutput = oFDT.yyyy + oDTP.settings.monthYearSeparator + oFDT.MM; } } else if(oDTP.oData.bTimeMode) { if(oDTP.oData.bArrMatchFormat[0]) { sOutput = oFDT.hh + oDTP.settings.timeSeparator + oFDT.mm + oDTP.settings.timeSeparator + oFDT.ss + oDTP.settings.timeMeridiemSeparator + oFDT.ME; } else if(oDTP.oData.bArrMatchFormat[1]) { sOutput = oFDT.HH + oDTP.settings.timeSeparator + oFDT.mm + oDTP.settings.timeSeparator + oFDT.ss; } else if(oDTP.oData.bArrMatchFormat[2]) { sOutput = oFDT.hh + oDTP.settings.timeSeparator + oFDT.mm + oDTP.settings.timeMeridiemSeparator + oFDT.ME; } else if(oDTP.oData.bArrMatchFormat[3]) { sOutput = oFDT.HH + oDTP.settings.timeSeparator + oFDT.mm; } } else if(oDTP.oData.bDateTimeMode) { // Date Part - "dd-MM-yyyy" if(oDTP.oData.bArrMatchFormat[0] || oDTP.oData.bArrMatchFormat[1] || oDTP.oData.bArrMatchFormat[8] || oDTP.oData.bArrMatchFormat[9]) { sDateStr = oFDT.dd + oDTP.settings.dateSeparator + oFDT.MM + oDTP.settings.dateSeparator + oFDT.yyyy; } // Date Part - "MM-dd-yyyy" else if(oDTP.oData.bArrMatchFormat[2] || oDTP.oData.bArrMatchFormat[3] || oDTP.oData.bArrMatchFormat[10] || oDTP.oData.bArrMatchFormat[11]) { sDateStr = oFDT.MM + oDTP.settings.dateSeparator + oFDT.dd + oDTP.settings.dateSeparator + oFDT.yyyy; } // Date Part - "yyyy-MM-dd" else if(oDTP.oData.bArrMatchFormat[4] || oDTP.oData.bArrMatchFormat[5] || oDTP.oData.bArrMatchFormat[12] || oDTP.oData.bArrMatchFormat[13]) { sDateStr = oFDT.yyyy + oDTP.settings.dateSeparator + oFDT.MM + oDTP.settings.dateSeparator + oFDT.dd; } // Date Part - "dd-MMM-yyyy" else if(oDTP.oData.bArrMatchFormat[6] || oDTP.oData.bArrMatchFormat[7] || oDTP.oData.bArrMatchFormat[14] || oDTP.oData.bArrMatchFormat[15]) { sDateStr = oFDT.dd + oDTP.settings.dateSeparator + oFDT.monthShort + oDTP.settings.dateSeparator + oFDT.yyyy; } bAddSeconds = oDTP.oData.bArrMatchFormat[0] || oDTP.oData.bArrMatchFormat[1] || oDTP.oData.bArrMatchFormat[2] || oDTP.oData.bArrMatchFormat[3] || oDTP.oData.bArrMatchFormat[4] || oDTP.oData.bArrMatchFormat[5] || oDTP.oData.bArrMatchFormat[6] || oDTP.oData.bArrMatchFormat[7]; if(bIs12Hour) { if(bAddSeconds) { sTimeStr = oFDT.hh + oDTP.settings.timeSeparator + oFDT.mm + oDTP.settings.timeSeparator + oFDT.ss + oDTP.settings.timeMeridiemSeparator + oFDT.ME; } else { sTimeStr = oFDT.hh + oDTP.settings.timeSeparator + oFDT.mm + oDTP.settings.timeMeridiemSeparator + oFDT.ME; } } else { if(bAddSeconds) { sTimeStr = oFDT.HH + oDTP.settings.timeSeparator + oFDT.mm + oDTP.settings.timeSeparator + oFDT.ss; } else { sTimeStr = oFDT.HH + oDTP.settings.timeSeparator + oFDT.mm; } } if(sDateStr !== "" && sTimeStr !== "") sOutput = sDateStr + oDTP.settings.dateTimeSeparator + sTimeStr; } // Reset bDate, bTime, bDateTime & bArrMatchFormat to original values oDTP._setMatchFormat(iArgsLength); } return sOutput; }, _clearButtonAction: function() { var oDTP = this; if(oDTP.oData.oInputElement !== null) { oDTP._setValueOfElement(""); } if(!oDTP.settings.isInline) oDTP._hidePicker(""); }, _setOutputOnIncrementOrDecrement: function() { var oDTP = this; if($.cf._isValid(oDTP.oData.oInputElement) && oDTP.settings.setValueInTextboxOnEveryClick) { oDTP._setValueOfElement(oDTP._setOutput()); } }, _showPicker: function(oElement) { var oDTP = this; if(oDTP.oData.oInputElement === null) { oDTP.oData.oInputElement = oElement; oDTP.oData.iTabIndex = parseInt($(oElement).attr("tabIndex")); var sMode = $(oElement).data("field") || "", sMinValue = $(oElement).data("min") || "", sMaxValue = $(oElement).data("max") || "", sFormat = $(oElement).data("format") || "", sView = $(oElement).data("view") || "", sStartEnd = $(oElement).data("startend") || "", sStartEndElem = $(oElement).data("startendelem") || "", sCurrent = oDTP._getValueOfElement(oElement) || ""; if(sView !== "") { if($.cf._compare(sView, "Popup")) oDTP.setIsPopup(true); else oDTP.setIsPopup(false); } if(!oDTP.settings.isPopup && !oDTP.settings.isInline) { oDTP._createPicker(); var iElemTop = $(oDTP.oData.oInputElement).offset().top + $(oDTP.oData.oInputElement).outerHeight(), iElemLeft = $(oDTP.oData.oInputElement).offset().left, iElemWidth = $(oDTP.oData.oInputElement).outerWidth(); $(oDTP.element).css({position: "absolute", top: iElemTop, left: iElemLeft, width: iElemWidth, height: "auto"}); } if(oDTP.settings.beforeShow) oDTP.settings.beforeShow.call(oDTP, oElement); sMode = $.cf._isValid(sMode) ? sMode : oDTP.settings.mode; oDTP.settings.mode = sMode; if(!$.cf._isValid(sFormat)) { if($.cf._compare(sMode, "date")) sFormat = oDTP.settings.dateFormat; else if($.cf._compare(sMode, "time")) sFormat = oDTP.settings.timeFormat; else if($.cf._compare(sMode, "datetime")) sFormat = oDTP.settings.dateTimeFormat; } oDTP._matchFormat(sMode, sFormat); oDTP.oData.dMinValue = null; oDTP.oData.dMaxValue = null; oDTP.oData.bIs12Hour = false; var sMin, sMax, sTempDate, dTempDate, sTempTime, dTempTime, sTempDateTime, dTempDateTime; if(oDTP.oData.bDateMode) { sMin = sMinValue || oDTP.settings.minDate; sMax = sMaxValue || oDTP.settings.maxDate; oDTP.oData.sDateFormat = sFormat; if($.cf._isValid(sMin)) oDTP.oData.dMinValue = oDTP._parseDate(sMin); if($.cf._isValid(sMax)) oDTP.oData.dMaxValue = oDTP._parseDate(sMax); if(sStartEnd !== "" && ($.cf._compare(sStartEnd, "start") || $.cf._compare(sStartEnd, "end")) && sStartEndElem !== "") { if($(sStartEndElem).length >= 1) { sTempDate = oDTP._getValueOfElement($(sStartEndElem)); if(sTempDate !== "") { if(oDTP.settings.parseDateTimeString) dTempDate = oDTP.settings.parseDateTimeString.call(oDTP, sTempDate, sMode, sFormat, $(sStartEndElem)); else dTempDate = oDTP._parseDate(sTempDate); if($.cf._compare(sStartEnd, "start")) { if($.cf._isValid(sMax)) { if(oDTP._compareDates(dTempDate, oDTP.oData.dMaxValue) < 0) oDTP.oData.dMaxValue = new Date(dTempDate); } else oDTP.oData.dMaxValue = new Date(dTempDate); } else if($.cf._compare(sStartEnd, "end")) { if($.cf._isValid(sMin)) { if(oDTP._compareDates(dTempDate, oDTP.oData.dMinValue) > 0) oDTP.oData.dMinValue = new Date(dTempDate); } else oDTP.oData.dMinValue = new Date(dTempDate); } } } } if(oDTP.settings.parseDateTimeString) oDTP.oData.dCurrentDate = oDTP.settings.parseDateTimeString.call(oDTP, sCurrent, sMode, sFormat, $(oElement)); else oDTP.oData.dCurrentDate = oDTP._parseDate(sCurrent); oDTP.oData.dCurrentDate.setHours(0); oDTP.oData.dCurrentDate.setMinutes(0); oDTP.oData.dCurrentDate.setSeconds(0); } else if(oDTP.oData.bTimeMode) { sMin = sMinValue || oDTP.settings.minTime; sMax = sMaxValue || oDTP.settings.maxTime; oDTP.oData.sTimeFormat = sFormat; oDTP.oData.bIs12Hour = oDTP.getIs12Hour(); if($.cf._isValid(sMin)) { oDTP.oData.dMinValue = oDTP._parseTime(sMin); if(!$.cf._isValid(sMax)) { if(oDTP.oData.sTimeFormat === oDTP.oData.sArrInputTimeFormats[0]) sMax = "11:59:59 PM"; else if(oDTP.oData.sTimeFormat === oDTP.oData.sArrInputTimeFormats[1]) sMax = "23:59:59"; else if(oDTP.oData.sTimeFormat === oDTP.oData.sArrInputTimeFormats[2]) sMax = "11:59 PM"; else if(oDTP.oData.sTimeFormat === oDTP.oData.sArrInputTimeFormats[3]) sMax = "23:59"; oDTP.oData.dMaxValue = oDTP._parseTime(sMax); } } if($.cf._isValid(sMax)) { oDTP.oData.dMaxValue = oDTP._parseTime(sMax); if(!$.cf._isValid(sMin)) { if(oDTP.oData.sTimeFormat === oDTP.oData.sArrInputTimeFormats[0]) sMin = "12:00:00 AM"; else if(oDTP.oData.sTimeFormat === oDTP.oData.sArrInputTimeFormats[1]) sMin = "00:00:00"; else if(oDTP.oData.sTimeFormat === oDTP.oData.sArrInputTimeFormats[2]) sMin = "12:00 AM"; else if(oDTP.oData.sTimeFormat === oDTP.oData.sArrInputTimeFormats[3]) sMin = "00:00"; oDTP.oData.dMinValue = oDTP._parseTime(sMin); } } if(sStartEnd !== "" && ($.cf._compare(sStartEnd, "start") || $.cf._compare(sStartEnd, "end")) && sStartEndElem !== "") { if($(sStartEndElem).length >= 1) { sTempTime = oDTP._getValueOfElement($(sStartEndElem)); if(sTempTime !== "") { if(oDTP.settings.parseDateTimeString) dTempDate = oDTP.settings.parseDateTimeString.call(oDTP, sTempTime, sMode, sFormat, $(sStartEndElem)); else dTempTime = oDTP._parseTime(sTempTime); if($.cf._compare(sStartEnd, "start")) { dTempTime.setMinutes(dTempTime.getMinutes() - 1); if($.cf._isValid(sMax)) { if(oDTP._compareTime(dTempTime, oDTP.oData.dMaxValue) === 2) oDTP.oData.dMaxValue = new Date(dTempTime); } else oDTP.oData.dMaxValue = new Date(dTempTime); } else if($.cf._compare(sStartEnd, "end")) { dTempTime.setMinutes(dTempTime.getMinutes() + 1); if($.cf._isValid(sMin)) { if(oDTP._compareTime(dTempTime, oDTP.oData.dMinValue) === 3) oDTP.oData.dMinValue = new Date(dTempTime); } else oDTP.oData.dMinValue = new Date(dTempTime); } } } } if(oDTP.settings.parseDateTimeString) oDTP.oData.dCurrentDate = oDTP.settings.parseDateTimeString.call(oDTP, sCurrent, sMode, sFormat, $(oElement)); else oDTP.oData.dCurrentDate = oDTP._parseTime(sCurrent); } else if(oDTP.oData.bDateTimeMode) { sMin = sMinValue || oDTP.settings.minDateTime; sMax = sMaxValue || oDTP.settings.maxDateTime; oDTP.oData.sDateTimeFormat = sFormat; oDTP.oData.bIs12Hour = oDTP.getIs12Hour(); if($.cf._isValid(sMin)) oDTP.oData.dMinValue = oDTP._parseDateTime(sMin); if($.cf._isValid(sMax)) oDTP.oData.dMaxValue = oDTP._parseDateTime(sMax); if(sStartEnd !== "" && ($.cf._compare(sStartEnd, "start") || $.cf._compare(sStartEnd, "end")) && sStartEndElem !== "") { if($(sStartEndElem).length >= 1) { sTempDateTime = oDTP._getValueOfElement($(sStartEndElem)); if(sTempDateTime !== "") { if(oDTP.settings.parseDateTimeString) dTempDateTime = oDTP.settings.parseDateTimeString.call(oDTP, sTempDateTime, sMode, sFormat, $(sStartEndElem)); else dTempDateTime = oDTP._parseDateTime(sTempDateTime); if($.cf._compare(sStartEnd, "start")) { if($.cf._isValid(sMax)) { if(oDTP._compareDateTime(dTempDateTime, oDTP.oData.dMaxValue) < 0) oDTP.oData.dMaxValue = new Date(dTempDateTime); } else oDTP.oData.dMaxValue = new Date(dTempDateTime); } else if($.cf._compare(sStartEnd, "end")) { if($.cf._isValid(sMin)) { if(oDTP._compareDateTime(dTempDateTime, oDTP.oData.dMinValue) > 0) oDTP.oData.dMinValue = new Date(dTempDateTime); } else oDTP.oData.dMinValue = new Date(dTempDateTime); } } } } if(oDTP.settings.parseDateTimeString) oDTP.oData.dCurrentDate = oDTP.settings.parseDateTimeString.call(oDTP, sCurrent, sMode, sFormat, $(oElement)); else oDTP.oData.dCurrentDate = oDTP._parseDateTime(sCurrent); } oDTP._setVariablesForDate(); oDTP._modifyPicker(); $(oDTP.element).fadeIn(oDTP.settings.animationDuration); if(oDTP.settings.afterShow) { setTimeout(function() { oDTP.settings.afterShow.call(oDTP, oElement); }, oDTP.settings.animationDuration); } } }, _hidePicker: function(iDuration, oElementToShow) { var oDTP = this; var oElement = oDTP.oData.oInputElement; if(oDTP.settings.beforeHide) oDTP.settings.beforeHide.call(oDTP, oElement); if(!$.cf._isValid(iDuration)) iDuration = oDTP.settings.animationDuration; if($.cf._isValid(oDTP.oData.oInputElement)) { $(oDTP.oData.oInputElement).blur(); oDTP.oData.oInputElement = null; } $(oDTP.element).fadeOut(iDuration); if(iDuration === 0) { $(oDTP.element).find(".dtpicker-subcontent").html(""); } else { setTimeout(function() { $(oDTP.element).find(".dtpicker-subcontent").html(""); }, iDuration); } $(document).unbind("click.DateTimePicker keydown.DateTimePicker keyup.DateTimePicker"); if(oDTP.settings.afterHide) { if(iDuration === 0) { oDTP.settings.afterHide.call(oDTP, oElement); } else { setTimeout(function() { oDTP.settings.afterHide.call(oDTP, oElement); }, iDuration); } } if($.cf._isValid(oElementToShow)) oDTP._showPicker(oElementToShow); }, _modifyPicker: function() { var oDTP = this; var sTitleContent, iNumberOfColumns; var sArrFields = []; if(oDTP.oData.bDateMode) { sTitleContent = oDTP.settings.titleContentDate; iNumberOfColumns = 3; if(oDTP.oData.bArrMatchFormat[0]) // "dd-MM-yyyy" { sArrFields = ["day", "month", "year"]; } else if(oDTP.oData.bArrMatchFormat[1]) // "MM-dd-yyyy" { sArrFields = ["month", "day", "year"]; } else if(oDTP.oData.bArrMatchFormat[2]) // "yyyy-MM-dd" { sArrFields = ["year", "month", "day"]; } else if(oDTP.oData.bArrMatchFormat[3]) // "dd-MMM-yyyy" { sArrFields = ["day", "month", "year"]; } else if(oDTP.oData.bArrMatchFormat[4]) // "MM-yyyy" { iNumberOfColumns = 2; sArrFields = ["month", "year"]; } else if(oDTP.oData.bArrMatchFormat[5]) // "MMM yyyy" { iNumberOfColumns = 2; sArrFields = ["month", "year"]; } else if(oDTP.oData.bArrMatchFormat[6]) // "MMMM yyyy" { iNumberOfColumns = 2; sArrFields = ["month", "year"]; } else if(oDTP.oData.bArrMatchFormat[7]) // "yyyy-MM" { iNumberOfColumns = 2; sArrFields = ["year", "month"]; } } else if(oDTP.oData.bTimeMode) { sTitleContent = oDTP.settings.titleContentTime; if(oDTP.oData.bArrMatchFormat[0]) // hh:mm:ss AA { iNumberOfColumns = 4; sArrFields = ["hour", "minutes", "seconds", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[1]) // HH:mm:ss { iNumberOfColumns = 3; sArrFields = ["hour", "minutes", "seconds"]; } else if(oDTP.oData.bArrMatchFormat[2]) // hh:mm AA { iNumberOfColumns = 3; sArrFields = ["hour", "minutes", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[3]) // HH:mm { iNumberOfColumns = 2; sArrFields = ["hour", "minutes"]; } } else if(oDTP.oData.bDateTimeMode) { sTitleContent = oDTP.settings.titleContentDateTime; if(oDTP.oData.bArrMatchFormat[0]) { iNumberOfColumns = 6; sArrFields = ["day", "month", "year", "hour", "minutes", "seconds"]; } else if(oDTP.oData.bArrMatchFormat[1]) { iNumberOfColumns = 7; sArrFields = ["day", "month", "year", "hour", "minutes", "seconds", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[2]) { iNumberOfColumns = 6; sArrFields = ["month", "day", "year", "hour", "minutes", "seconds"]; } else if(oDTP.oData.bArrMatchFormat[3]) { iNumberOfColumns = 7; sArrFields = ["month", "day", "year", "hour", "minutes", "seconds", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[4]) { iNumberOfColumns = 6; sArrFields = ["year", "month", "day", "hour", "minutes", "seconds"]; } else if(oDTP.oData.bArrMatchFormat[5]) { iNumberOfColumns = 7; sArrFields = ["year", "month", "day", "hour", "minutes", "seconds", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[6]) { iNumberOfColumns = 6; sArrFields = ["day", "month", "year", "hour", "minutes", "seconds"]; } else if(oDTP.oData.bArrMatchFormat[7]) { iNumberOfColumns = 7; sArrFields = ["day", "month", "year", "hour", "minutes", "seconds", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[8]) { iNumberOfColumns = 5; sArrFields = ["day", "month", "year", "hour", "minutes"]; } else if(oDTP.oData.bArrMatchFormat[9]) { iNumberOfColumns = 6; sArrFields = ["day", "month", "year", "hour", "minutes", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[10]) { iNumberOfColumns = 5; sArrFields = ["month", "day", "year", "hour", "minutes"]; } else if(oDTP.oData.bArrMatchFormat[11]) { iNumberOfColumns = 6; sArrFields = ["month", "day", "year", "hour", "minutes", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[12]) { iNumberOfColumns = 5; sArrFields = ["year", "month", "day", "hour", "minutes"]; } else if(oDTP.oData.bArrMatchFormat[13]) { iNumberOfColumns = 6; sArrFields = ["year", "month", "day", "hour", "minutes", "meridiem"]; } else if(oDTP.oData.bArrMatchFormat[14]) { iNumberOfColumns = 5; sArrFields = ["day", "month", "year", "hour", "minutes"]; } else if(oDTP.oData.bArrMatchFormat[15]) { iNumberOfColumns = 6; sArrFields = ["day", "month", "year", "hour", "minutes", "meridiem"]; } } //your_sha256_hash---- var sColumnClass = "dtpicker-comp" + iNumberOfColumns, bDisplayHeaderCloseButton = false, bDisplaySetButton = false, bDisplayClearButton = false, iTempIndex; for(iTempIndex = 0; iTempIndex < oDTP.settings.buttonsToDisplay.length; iTempIndex++) { if($.cf._compare(oDTP.settings.buttonsToDisplay[iTempIndex], "HeaderCloseButton")) bDisplayHeaderCloseButton = true; else if($.cf._compare(oDTP.settings.buttonsToDisplay[iTempIndex], "SetButton")) bDisplaySetButton = true; else if($.cf._compare(oDTP.settings.buttonsToDisplay[iTempIndex], "ClearButton")) bDisplayClearButton = true; } var sHeader = ""; if(oDTP.settings.showHeader) { sHeader += "<div class='dtpicker-header'>"; sHeader += "<div class='dtpicker-title'>" + sTitleContent + "</div>"; if(bDisplayHeaderCloseButton) sHeader += "<a class='dtpicker-close'>&times;</a>"; sHeader += "<div class='dtpicker-value'></div>"; sHeader += "</div>"; } //your_sha256_hash---- var sDTPickerComp = ""; sDTPickerComp += "<div class='dtpicker-components'>"; for(iTempIndex = 0; iTempIndex < iNumberOfColumns; iTempIndex++) { var sFieldName = sArrFields[iTempIndex]; sDTPickerComp += "<div class='dtpicker-compOutline " + sColumnClass + "'>"; sDTPickerComp += "<div class='dtpicker-comp " + sFieldName + "'>"; sDTPickerComp += "<a class='dtpicker-compButton increment'>" + oDTP.settings.incrementButtonContent + "</a>"; if(oDTP.settings.readonlyInputs) sDTPickerComp += "<input type='text' class='dtpicker-compValue' readonly>"; else sDTPickerComp += "<input type='text' class='dtpicker-compValue'>"; sDTPickerComp += "<a class='dtpicker-compButton decrement'>" + oDTP.settings.decrementButtonContent + "</a>"; if(oDTP.settings.labels) sDTPickerComp += "<div class='dtpicker-label'>" + oDTP.settings.labels[sFieldName] + "</div>"; sDTPickerComp += "</div>"; sDTPickerComp += "</div>"; } sDTPickerComp += "</div>"; //your_sha256_hash---- var sButtonContClass = ""; if(bDisplaySetButton && bDisplayClearButton) sButtonContClass = " dtpicker-twoButtons"; else sButtonContClass = " dtpicker-singleButton"; var sDTPickerButtons = ""; sDTPickerButtons += "<div class='dtpicker-buttonCont" + sButtonContClass + "'>"; if(bDisplaySetButton) sDTPickerButtons += "<a class='dtpicker-button dtpicker-buttonSet'>" + oDTP.settings.setButtonContent + "</a>"; if(bDisplayClearButton) sDTPickerButtons += "<a class='dtpicker-button dtpicker-buttonClear'>" + oDTP.settings.clearButtonContent + "</a>"; sDTPickerButtons += "</div>"; //your_sha256_hash---- var sTempStr = sHeader + sDTPickerComp + sDTPickerButtons; $(oDTP.element).find(".dtpicker-subcontent").html(sTempStr); oDTP._setCurrentDate(); oDTP._addEventHandlersForPicker(); }, _addEventHandlersForPicker: function() { var oDTP = this; var classType, keyCode, $nextElem; if(!oDTP.settings.isInline) { $(document).on("click.DateTimePicker", function(e) { if (oDTP.oData.bElemFocused) oDTP._hidePicker(""); }); } $(document).on("keydown.DateTimePicker", function(e) { keyCode = parseInt(e.keyCode ? e.keyCode : e.which); if(! $(".dtpicker-compValue").is(":focus") && keyCode === 9) // TAB { oDTP._setButtonAction(true); $("[tabIndex=" + (oDTP.oData.iTabIndex + 1) + "]").focus(); return false; } else if($(".dtpicker-compValue").is(":focus")) { /*if(keyCode === 37) // Left Arrow { oDTP._setButtonAction(true); $nextElem = $(".dtpicker-compValue:focus").parent().prev().children(".dtpicker-compValue"); $nextElem.focus(); console.log('Left Arrow '); console.log($nextElem); return false; } else if(keyCode === 39) // Right Arrow { oDTP._setButtonAction(true); var compVal = $(".dtpicker-compValue:focus"); $nextElem = $(".dtpicker-compValue:focus").parent(".dtpicker-comp").next().children(".dtpicker-compValue"); $nextElem.focus(); console.log('Right Arrow '); console.log($nextElem); return false; } else*/ if(keyCode === 38) // Up Arrow { classType = $(".dtpicker-compValue:focus").parent().attr("class"); oDTP._incrementDecrementActionsUsingArrowAndMouse(classType, "inc"); return false; } else if(keyCode === 40) // Down Arrow { classType = $(".dtpicker-compValue:focus").parent().attr("class"); oDTP._incrementDecrementActionsUsingArrowAndMouse(classType, "dec"); return false; } } }); if(!oDTP.settings.isInline) { $(document).on("keydown.DateTimePicker", function(e) { keyCode = parseInt(e.keyCode ? e.keyCode : e.which); // console.log("keydown " + keyCode); if(! $(".dtpicker-compValue").is(":focus") && keyCode !== 9) { //if(keyCode !== 37 && keyCode !== 39) oDTP._hidePicker(""); } }); } $(".dtpicker-cont *").click(function(e) { e.stopPropagation(); }); if(!oDTP.settings.readonlyInputs) { $(".dtpicker-compValue").not(".month .dtpicker-compValue, .meridiem .dtpicker-compValue").keyup(function() { this.value = this.value.replace(/[^0-9\.]/g,""); }); $(".dtpicker-compValue").focus(function() { oDTP.oData.bElemFocused = true; $(this).select(); }); $(".dtpicker-compValue").blur(function() { oDTP._getValuesFromInputBoxes(); oDTP._setCurrentDate(); oDTP.oData.bElemFocused = false; var $oParentElem = $(this).parent().parent(); setTimeout(function() { if($oParentElem.is(":last-child") && !oDTP.oData.bElemFocused) { oDTP._setButtonAction(false); } }, 50); }); $(".dtpicker-compValue").keyup(function(e) { var $oTextField = $(this), sTextBoxVal = $oTextField.val(), iLength = sTextBoxVal.length, sNewTextBoxVal; if($oTextField.parent().hasClass("day") || $oTextField.parent().hasClass("hour") || $oTextField.parent().hasClass("minutes") || $oTextField.parent().hasClass("meridiem")) { if(iLength > 2) { sNewTextBoxVal = sTextBoxVal.slice(0, 2); $oTextField.val(sNewTextBoxVal); } } else if($oTextField.parent().hasClass("month")) { if(iLength > 3) { sNewTextBoxVal = sTextBoxVal.slice(0, 3); $oTextField.val(sNewTextBoxVal); } } else if($oTextField.parent().hasClass("year")) { if(iLength > 4) { sNewTextBoxVal = sTextBoxVal.slice(0, 4); $oTextField.val(sNewTextBoxVal); } } if(parseInt(e.keyCode ? e.keyCode : e.which) === 9) $(this).select(); }); } $(oDTP.element).find(".dtpicker-compValue").on("mousewheel DOMMouseScroll onmousewheel", function(e) { if($(".dtpicker-compValue").is(":focus")) { var delta = Math.max(-1, Math.min(1, e.originalEvent.wheelDelta)); if(delta > 0) { classType = $(".dtpicker-compValue:focus").parent().attr("class"); oDTP._incrementDecrementActionsUsingArrowAndMouse(classType, "inc"); } else { classType = $(".dtpicker-compValue:focus").parent().attr("class"); oDTP._incrementDecrementActionsUsingArrowAndMouse(classType, "dec"); } return false; } }); //your_sha256_hash------- $(oDTP.element).find(".dtpicker-close").click(function(e) { if(oDTP.settings.buttonClicked) oDTP.settings.buttonClicked.call(oDTP, "CLOSE", oDTP.oData.oInputElement); if(!oDTP.settings.isInline) oDTP._hidePicker(""); }); $(oDTP.element).find(".dtpicker-buttonSet").click(function(e) { if(oDTP.settings.buttonClicked) oDTP.settings.buttonClicked.call(oDTP, "SET", oDTP.oData.oInputElement); oDTP._setButtonAction(false); }); $(oDTP.element).find(".dtpicker-buttonClear").click(function(e) { if(oDTP.settings.buttonClicked) oDTP.settings.buttonClicked.call(oDTP, "CLEAR", oDTP.oData.oInputElement); oDTP._clearButtonAction(); }); // your_sha256_hash------------ //console.log((oDTP.settings.captureTouchHold || oDTP.settings.captureMouseHold)); if(oDTP.settings.captureTouchHold || oDTP.settings.captureMouseHold) { var sHoldEvents = ""; if(oDTP.settings.captureTouchHold && oDTP.oData.bIsTouchDevice) sHoldEvents += "touchstart touchmove touchend "; if(oDTP.settings.captureMouseHold) sHoldEvents += "mousedown mouseup"; $(".dtpicker-cont *").on(sHoldEvents, function(e) { oDTP._clearIntervalForTouchEvents(); }); oDTP._bindTouchEvents("day"); oDTP._bindTouchEvents("month"); oDTP._bindTouchEvents("year"); oDTP._bindTouchEvents("hour"); oDTP._bindTouchEvents("minutes"); oDTP._bindTouchEvents("seconds"); } else { $(oDTP.element).find(".day .increment, .day .increment *").click(function(e) { oDTP.oData.iCurrentDay++; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".day .decrement, .day .decrement *").click(function(e) { oDTP.oData.iCurrentDay--; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".month .increment, .month .increment *").click(function(e) { oDTP.oData.iCurrentMonth++; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".month .decrement, .month .decrement *").click(function(e) { oDTP.oData.iCurrentMonth--; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".year .increment, .year .increment *").click(function(e) { oDTP.oData.iCurrentYear++; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".year .decrement, .year .decrement *").click(function(e) { oDTP.oData.iCurrentYear--; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".hour .increment, .hour .increment *").click(function(e) { oDTP.oData.iCurrentHour++; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".hour .decrement, .hour .decrement *").click(function(e) { oDTP.oData.iCurrentHour--; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".minutes .increment, .minutes .increment *").click(function(e) { oDTP.oData.iCurrentMinutes += oDTP.settings.minuteInterval; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".minutes .decrement, .minutes .decrement *").click(function(e) { oDTP.oData.iCurrentMinutes -= oDTP.settings.minuteInterval; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".seconds .increment, .seconds .increment *").click(function(e) { oDTP.oData.iCurrentSeconds += oDTP.settings.secondsInterval; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); $(oDTP.element).find(".seconds .decrement, .seconds .decrement *").click(function(e) { oDTP.oData.iCurrentSeconds -= oDTP.settings.secondsInterval; oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); } $(oDTP.element).find(".meridiem .dtpicker-compButton, .meridiem .dtpicker-compButton *").click(function(e) { if($.cf._compare(oDTP.oData.sCurrentMeridiem, "AM")) { oDTP.oData.sCurrentMeridiem = "PM"; oDTP.oData.iCurrentHour += 12; } else if($.cf._compare(oDTP.oData.sCurrentMeridiem, "PM")) { oDTP.oData.sCurrentMeridiem = "AM"; oDTP.oData.iCurrentHour -= 12; } oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }); }, _adjustMinutes: function(iMinutes) { var oDTP = this; if(oDTP.settings.roundOffMinutes && oDTP.settings.minuteInterval !== 1) { iMinutes = (iMinutes % oDTP.settings.minuteInterval) ? (iMinutes - (iMinutes % oDTP.settings.minuteInterval) + oDTP.settings.minuteInterval) : iMinutes; } return iMinutes; }, _adjustSeconds: function(iSeconds) { var oDTP = this; if(oDTP.settings.roundOffSeconds && oDTP.settings.secondsInterval !== 1) { iSeconds = (iSeconds % oDTP.settings.secondsInterval) ? (iSeconds - (iSeconds % oDTP.settings.secondsInterval) + oDTP.settings.secondsInterval) : iSeconds; } return iSeconds; }, _getValueOfElement: function(oElem) { var oDTP = this; var sElemValue = ""; if($.cf._compare($(oElem).prop("tagName"), "INPUT")) sElemValue = $(oElem).val(); else sElemValue = $(oElem).html(); return sElemValue; }, _setValueOfElement: function(sElemValue, $oElem) { var oDTP = this; if(!$.cf._isValid($oElem)) $oElem = $(oDTP.oData.oInputElement); if($.cf._compare($oElem.prop("tagName"), "INPUT")) $oElem.val(sElemValue); else $oElem.html(sElemValue); var dElemValue = oDTP.getDateObjectForInputField($oElem); if(oDTP.settings.settingValueOfElement) oDTP.settings.settingValueOfElement.call(oDTP, sElemValue, dElemValue, $oElem); $oElem.change(); return sElemValue; }, _bindTouchEvents: function(type) { var oDTP = this; $(oDTP.element).find("." + type + " .increment, ." + type + " .increment *").on("touchstart mousedown", function(e) { e.stopPropagation(); if(!$.cf._isValid(oDTP.oData.sTouchButton)) { oDTP.oData.iTouchStart = (new Date()).getTime(); oDTP.oData.sTouchButton = type + "-inc"; oDTP._setIntervalForTouchEvents(); } }); $(oDTP.element).find("." + type + " .increment, ." + type + " .increment *").on("touchend mouseup", function(e) { e.stopPropagation(); oDTP._clearIntervalForTouchEvents(); }); $(oDTP.element).find("." + type + " .decrement, ." + type + " .decrement *").on("touchstart mousedown", function(e) { e.stopPropagation(); if(!$.cf._isValid(oDTP.oData.sTouchButton)) { oDTP.oData.iTouchStart = (new Date()).getTime(); oDTP.oData.sTouchButton = type + "-dec"; oDTP._setIntervalForTouchEvents(); } }); $(oDTP.element).find("." + type + " .decrement, ." + type + " .decrement *").on("touchend mouseup", function(e) { e.stopPropagation(); oDTP._clearIntervalForTouchEvents(); }); }, _setIntervalForTouchEvents: function() { var oDTP = this; var iInterval = oDTP.oData.bIsTouchDevice ? oDTP.settings.touchHoldInterval : oDTP.settings.mouseHoldInterval; if(!$.cf._isValid(oDTP.oData.oTimeInterval)) { var iDiff; oDTP.oData.oTimeInterval = setInterval(function() { iDiff = ((new Date()).getTime() - oDTP.oData.iTouchStart); if(iDiff > iInterval && $.cf._isValid(oDTP.oData.sTouchButton)) { if(oDTP.oData.sTouchButton === "day-inc") { oDTP.oData.iCurrentDay++; } else if(oDTP.oData.sTouchButton === "day-dec") { oDTP.oData.iCurrentDay--; } else if(oDTP.oData.sTouchButton === "month-inc") { oDTP.oData.iCurrentMonth++; } else if(oDTP.oData.sTouchButton === "month-dec") { oDTP.oData.iCurrentMonth--; } else if(oDTP.oData.sTouchButton === "year-inc") { oDTP.oData.iCurrentYear++; } else if(oDTP.oData.sTouchButton === "year-dec") { oDTP.oData.iCurrentYear--; } else if(oDTP.oData.sTouchButton === "hour-inc") { oDTP.oData.iCurrentHour++; } else if(oDTP.oData.sTouchButton === "hour-dec") { oDTP.oData.iCurrentHour--; } else if(oDTP.oData.sTouchButton === "minute-inc") { oDTP.oData.iCurrentMinutes += oDTP.settings.minuteInterval; } else if(oDTP.oData.sTouchButton === "minute-dec") { oDTP.oData.iCurrentMinutes -= oDTP.settings.minuteInterval; } else if(oDTP.oData.sTouchButton === "second-inc") { oDTP.oData.iCurrentSeconds += oDTP.settings.secondsInterval; } else if(oDTP.oData.sTouchButton === "second-dec") { oDTP.oData.iCurrentSeconds -= oDTP.settings.secondsInterval; } oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); oDTP.oData.iTouchStart = (new Date()).getTime(); } }, iInterval); } }, _clearIntervalForTouchEvents: function() { var oDTP = this; clearInterval(oDTP.oData.oTimeInterval); if($.cf._isValid(oDTP.oData.sTouchButton)) { oDTP.oData.sTouchButton = null; oDTP.oData.iTouchStart = 0; } oDTP.oData.oTimeInterval = null; }, _incrementDecrementActionsUsingArrowAndMouse: function(type, action) { var oDTP = this; if(type.includes("day")) { if (action === "inc") oDTP.oData.iCurrentDay++; else if (action === "dec") oDTP.oData.iCurrentDay--; } else if(type.includes("month")) { if (action === "inc") oDTP.oData.iCurrentMonth++; else if (action === "dec") oDTP.oData.iCurrentMonth--; } else if(type.includes("year")) { if (action === "inc") oDTP.oData.iCurrentYear++; else if (action === "dec") oDTP.oData.iCurrentYear--; } else if(type.includes("hour")) { if (action === "inc") oDTP.oData.iCurrentHour++; else if (action === "dec") oDTP.oData.iCurrentHour--; } else if(type.includes("minutes")) { if (action === "inc") oDTP.oData.iCurrentMinutes += oDTP.settings.minuteInterval; else if (action === "dec") oDTP.oData.iCurrentMinutes -= oDTP.settings.minuteInterval; } else if(type.includes("seconds")) { if (action === "inc") oDTP.oData.iCurrentSeconds += oDTP.settings.secondsInterval; else if (action === "dec") oDTP.oData.iCurrentSeconds -= oDTP.settings.secondsInterval; } oDTP._setCurrentDate(); oDTP._setOutputOnIncrementOrDecrement(); }, //your_sha256_hash- _parseDate: function(sDate) { var oDTP = this; var dTempDate = (oDTP.settings.defaultDate ? new Date(oDTP.settings.defaultDate) : new Date()), iDate = dTempDate.getDate(), iMonth = dTempDate.getMonth(), iYear = dTempDate.getFullYear(); if($.cf._isValid(sDate)) { if(typeof sDate === "string") { var sArrDate; if(oDTP.oData.bArrMatchFormat[4] || oDTP.oData.bArrMatchFormat[5] || oDTP.oData.bArrMatchFormat[6]) sArrDate = sDate.split(oDTP.settings.monthYearSeparator); else sArrDate = sDate.split(oDTP.settings.dateSeparator); if(oDTP.oData.bArrMatchFormat[0]) // "dd-MM-yyyy" { iDate = parseInt(sArrDate[0]); iMonth = parseInt(sArrDate[1] - 1); iYear = parseInt(sArrDate[2]); } else if(oDTP.oData.bArrMatchFormat[1]) // "MM-dd-yyyy" { iMonth = parseInt(sArrDate[0] - 1); iDate = parseInt(sArrDate[1]); iYear = parseInt(sArrDate[2]); } else if(oDTP.oData.bArrMatchFormat[2]) // "yyyy-MM-dd" { iYear = parseInt(sArrDate[0]); iMonth = parseInt(sArrDate[1] - 1); iDate = parseInt(sArrDate[2]); } else if(oDTP.oData.bArrMatchFormat[3]) // "dd-MMM-yyyy" { iDate = parseInt(sArrDate[0]); iMonth = oDTP._getShortMonthIndex(sArrDate[1]); iYear = parseInt(sArrDate[2]); } else if(oDTP.oData.bArrMatchFormat[4]) // "MM-yyyy" { iDate = 1; iMonth = parseInt(sArrDate[0]) - 1; iYear = parseInt(sArrDate[1]); } else if(oDTP.oData.bArrMatchFormat[5]) // "MMM yyyy" { iDate = 1; iMonth = oDTP._getShortMonthIndex(sArrDate[0]); iYear = parseInt(sArrDate[1]); } else if(oDTP.oData.bArrMatchFormat[6]) // "MMMM yyyy" { iDate = 1; iMonth = oDTP._getFullMonthIndex(sArrDate[0]); iYear = parseInt(sArrDate[1]); } else if(oDTP.oData.bArrMatchFormat[7]) // "yyyy MM" { iDate = 1; iMonth = parseInt(sArrDate[1]) - 1; iYear = parseInt(sArrDate[0]); } } else { iDate = sDate.getDate(); iMonth = sDate.getMonth(); iYear = sDate.getFullYear(); } } dTempDate = new Date(iYear, iMonth, iDate, 0, 0, 0, 0); return dTempDate; }, _parseTime: function(sTime) { var oDTP = this; var dTempDate = (oDTP.settings.defaultDate ? new Date(oDTP.settings.defaultDate) : new Date()), iDate = dTempDate.getDate(), iMonth = dTempDate.getMonth(), iYear = dTempDate.getFullYear(), iHour = dTempDate.getHours(), iMinutes = dTempDate.getMinutes(), iSeconds = dTempDate.getSeconds(), sArrTime, sMeridiem, sArrTimeComp, bShowSeconds = oDTP.oData.bArrMatchFormat[0] || oDTP.oData.bArrMatchFormat[1]; iSeconds = bShowSeconds ? oDTP._adjustSeconds(iSeconds) : 0; if($.cf._isValid(sTime)) { if(typeof sTime === "string") { if(oDTP.oData.bIs12Hour) { sArrTime = sTime.split(oDTP.settings.timeMeridiemSeparator); sTime = sArrTime[0]; sMeridiem = sArrTime[1]; if(!($.cf._compare(sMeridiem, "AM") || $.cf._compare(sMeridiem, "PM"))) sMeridiem = ""; } sArrTimeComp = sTime.split(oDTP.settings.timeSeparator); iHour = parseInt(sArrTimeComp[0]); iMinutes = parseInt(sArrTimeComp[1]); if(bShowSeconds) { iSeconds = parseInt(sArrTimeComp[2]); iSeconds = oDTP._adjustSeconds(iSeconds); } if(iHour === 12 && $.cf._compare(sMeridiem, "AM")) iHour = 0; else if(iHour < 12 && $.cf._compare(sMeridiem, "PM")) iHour += 12; } else { iHour = sTime.getHours(); iMinutes = sTime.getMinutes(); if(bShowSeconds) { iSeconds = sTime.getSeconds(); iSeconds = oDTP._adjustSeconds(iSeconds); } } } iMinutes = oDTP._adjustMinutes(iMinutes); dTempDate = new Date(iYear, iMonth, iDate, iHour, iMinutes, iSeconds, 0); return dTempDate; }, _parseDateTime: function(sDateTime) { var oDTP = this; var dTempDate = (oDTP.settings.defaultDate ? new Date(oDTP.settings.defaultDate) : new Date()), iDate = dTempDate.getDate(), iMonth = dTempDate.getMonth(), iYear = dTempDate.getFullYear(), iHour = dTempDate.getHours(), iMinutes = dTempDate.getMinutes(), iSeconds = dTempDate.getSeconds(), sMeridiem = "", sArrDateTime, sArrDate, sTime, sArrTimeComp, sArrTime, bShowSeconds = oDTP.oData.bArrMatchFormat[0] || // "dd-MM-yyyy HH:mm:ss" oDTP.oData.bArrMatchFormat[1] || // ""dd-MM-yyyy hh:mm:ss AA" oDTP.oData.bArrMatchFormat[2] || // "MM-dd-yyyy HH:mm:ss" oDTP.oData.bArrMatchFormat[3] || // "MM-dd-yyyy hh:mm:ss AA" oDTP.oData.bArrMatchFormat[4] || // "yyyy-MM-dd HH:mm:ss" oDTP.oData.bArrMatchFormat[5] || // "yyyy-MM-dd hh:mm:ss AA" oDTP.oData.bArrMatchFormat[6] || // "dd-MMM-yyyy HH:mm:ss" oDTP.oData.bArrMatchFormat[7]; // "dd-MMM-yyyy hh:mm:ss AA" iSeconds = bShowSeconds ? oDTP._adjustSeconds(iSeconds) : 0; if($.cf._isValid(sDateTime)) { if(typeof sDateTime === "string") { sArrDateTime = sDateTime.split(oDTP.settings.dateTimeSeparator); sArrDate = sArrDateTime[0].split(oDTP.settings.dateSeparator); if(oDTP.oData.bArrMatchFormat[0] || // "dd-MM-yyyy HH:mm:ss" oDTP.oData.bArrMatchFormat[1] || // ""dd-MM-yyyy hh:mm:ss AA" oDTP.oData.bArrMatchFormat[8] || // "dd-MM-yyyy HH:mm" oDTP.oData.bArrMatchFormat[9]) // "dd-MM-yyyy hh:mm AA" { iDate = parseInt(sArrDate[0]); iMonth = parseInt(sArrDate[1] - 1); iYear = parseInt(sArrDate[2]); } else if(oDTP.oData.bArrMatchFormat[2] || // "MM-dd-yyyy HH:mm:ss" oDTP.oData.bArrMatchFormat[3] || // "MM-dd-yyyy hh:mm:ss AA" oDTP.oData.bArrMatchFormat[10] || // "MM-dd-yyyy HH:mm" oDTP.oData.bArrMatchFormat[11]) // "MM-dd-yyyy hh:mm AA" { iMonth = parseInt(sArrDate[0] - 1); iDate = parseInt(sArrDate[1]); iYear = parseInt(sArrDate[2]); } else if(oDTP.oData.bArrMatchFormat[4] || // "yyyy-MM-dd HH:mm:ss" oDTP.oData.bArrMatchFormat[5] || // "yyyy-MM-dd hh:mm:ss AA" oDTP.oData.bArrMatchFormat[12] || // "yyyy-MM-dd HH:mm" oDTP.oData.bArrMatchFormat[13]) // "yyyy-MM-dd hh:mm AA" { iYear = parseInt(sArrDate[0]); iMonth = parseInt(sArrDate[1] - 1); iDate = parseInt(sArrDate[2]); } else if(oDTP.oData.bArrMatchFormat[6] || // "dd-MMM-yyyy HH:mm:ss" oDTP.oData.bArrMatchFormat[7] || // "dd-MMM-yyyy hh:mm:ss AA" oDTP.oData.bArrMatchFormat[14] || // "dd-MMM-yyyy HH:mm:ss" oDTP.oData.bArrMatchFormat[15]) // "dd-MMM-yyyy hh:mm:ss AA" { iDate = parseInt(sArrDate[0]); iMonth = oDTP._getShortMonthIndex(sArrDate[1]); iYear = parseInt(sArrDate[2]); } sTime = sArrDateTime[1]; if($.cf._isValid(sTime)) { if(oDTP.oData.bIs12Hour) { if($.cf._compare(oDTP.settings.dateTimeSeparator, oDTP.settings.timeMeridiemSeparator) && (sArrDateTime.length === 3)) sMeridiem = sArrDateTime[2]; else { sArrTimeComp = sTime.split(oDTP.settings.timeMeridiemSeparator); sTime = sArrTimeComp[0]; sMeridiem = sArrTimeComp[1]; } if(!($.cf._compare(sMeridiem, "AM") || $.cf._compare(sMeridiem, "PM"))) sMeridiem = ""; } sArrTime = sTime.split(oDTP.settings.timeSeparator); iHour = parseInt(sArrTime[0]); iMinutes = parseInt(sArrTime[1]); if(bShowSeconds) { iSeconds = parseInt(sArrTime[2]); } if(iHour === 12 && $.cf._compare(sMeridiem, "AM")) iHour = 0; else if(iHour < 12 && $.cf._compare(sMeridiem, "PM")) iHour += 12; } } else { iDate = sDateTime.getDate(); iMonth = sDateTime.getMonth(); iYear = sDateTime.getFullYear(); iHour = sDateTime.getHours(); iMinutes = sDateTime.getMinutes(); if(bShowSeconds) { iSeconds = sDateTime.getSeconds(); iSeconds = oDTP._adjustSeconds(iSeconds); } } } iMinutes = oDTP._adjustMinutes(iMinutes); dTempDate = new Date(iYear, iMonth, iDate, iHour, iMinutes, iSeconds, 0); return dTempDate; }, _getShortMonthIndex: function(sMonthName) { var oDTP = this; for(var iTempIndex = 0; iTempIndex < oDTP.settings.shortMonthNames.length; iTempIndex++) { if($.cf._compare(sMonthName, oDTP.settings.shortMonthNames[iTempIndex])) return iTempIndex; } }, _getFullMonthIndex: function(sMonthName) { var oDTP = this; for(var iTempIndex = 0; iTempIndex < oDTP.settings.fullMonthNames.length; iTempIndex++) { if($.cf._compare(sMonthName, oDTP.settings.fullMonthNames[iTempIndex])) return iTempIndex; } }, // Public Method getIs12Hour: function(sMode, sFormat) { var oDTP = this; var bIs12Hour = false, iArgsLength = Function.length; oDTP._setMatchFormat(iArgsLength, sMode, sFormat); if(oDTP.oData.bTimeMode) { bIs12Hour = oDTP.oData.bArrMatchFormat[0] || oDTP.oData.bArrMatchFormat[2]; } else if(oDTP.oData.bDateTimeMode) { bIs12Hour = oDTP.oData.bArrMatchFormat[1] || oDTP.oData.bArrMatchFormat[3] || oDTP.oData.bArrMatchFormat[5] || oDTP.oData.bArrMatchFormat[7] || oDTP.oData.bArrMatchFormat[9] || oDTP.oData.bArrMatchFormat[11] || oDTP.oData.bArrMatchFormat[13] || oDTP.oData.bArrMatchFormat[15]; } oDTP._setMatchFormat(iArgsLength); return bIs12Hour; }, //your_sha256_hash- _setVariablesForDate: function(dInput, bIncludeTime, bSetMeridiem) { var oDTP = this; var dTemp, oDTV = {}, bValidInput = $.cf._isValid(dInput); if(bValidInput) { dTemp = new Date(dInput); if(!$.cf._isValid(bIncludeTime)) bIncludeTime = true; if(!$.cf._isValid(bSetMeridiem)) bSetMeridiem = true; } else { if (Object.prototype.toString.call(oDTP.oData.dCurrentDate) === "[object Date]" && isFinite(oDTP.oData.dCurrentDate)) dTemp = new Date(oDTP.oData.dCurrentDate); else dTemp = new Date(); if(!$.cf._isValid(bIncludeTime)) bIncludeTime = (oDTP.oData.bTimeMode || oDTP.oData.bDateTimeMode); if(!$.cf._isValid(bSetMeridiem)) bSetMeridiem = oDTP.oData.bIs12Hour; } oDTV.iCurrentDay = dTemp.getDate(); oDTV.iCurrentMonth = dTemp.getMonth(); oDTV.iCurrentYear = dTemp.getFullYear(); oDTV.iCurrentWeekday = dTemp.getDay(); if(bIncludeTime) { oDTV.iCurrentHour = dTemp.getHours(); oDTV.iCurrentMinutes = dTemp.getMinutes(); oDTV.iCurrentSeconds = dTemp.getSeconds(); if(bSetMeridiem) { oDTV.sCurrentMeridiem = oDTP._determineMeridiemFromHourAndMinutes(oDTV.iCurrentHour, oDTV.iCurrentMinutes); } } if(bValidInput) return oDTV; else oDTP.oData = $.extend(oDTP.oData, oDTV); }, _getValuesFromInputBoxes: function() { var oDTP = this; if(oDTP.oData.bDateMode || oDTP.oData.bDateTimeMode) { var sMonth, iMonth; sMonth = $(oDTP.element).find(".month .dtpicker-compValue").val(); if(sMonth.length > 1) sMonth = sMonth.charAt(0).toUpperCase() + sMonth.slice(1); iMonth = oDTP.settings.shortMonthNames.indexOf(sMonth); if(iMonth !== -1) { oDTP.oData.iCurrentMonth = parseInt(iMonth); } else { if(sMonth.match("^[+|-]?[0-9]+$")) { oDTP.oData.iCurrentMonth = parseInt(sMonth - 1); } } oDTP.oData.iCurrentDay = parseInt($(oDTP.element).find(".day .dtpicker-compValue").val()) || oDTP.oData.iCurrentDay; oDTP.oData.iCurrentYear = parseInt($(oDTP.element).find(".year .dtpicker-compValue").val()) || oDTP.oData.iCurrentYear; } if(oDTP.oData.bTimeMode || oDTP.oData.bDateTimeMode) { var iTempHour, iTempMinutes, iTempSeconds, sMeridiem; iTempHour = parseInt($(oDTP.element).find(".hour .dtpicker-compValue").val()); iTempMinutes = oDTP._adjustMinutes(parseInt($(oDTP.element).find(".minutes .dtpicker-compValue").val())); iTempSeconds = oDTP._adjustMinutes(parseInt($(oDTP.element).find(".seconds .dtpicker-compValue").val())); oDTP.oData.iCurrentHour = isNaN(iTempHour) ? oDTP.oData.iCurrentHour : iTempHour; oDTP.oData.iCurrentMinutes = isNaN(iTempMinutes) ? oDTP.oData.iCurrentMinutes : iTempMinutes; oDTP.oData.iCurrentSeconds = isNaN(iTempSeconds) ? oDTP.oData.iCurrentSeconds : iTempSeconds; if(oDTP.oData.iCurrentSeconds > 59) { oDTP.oData.iCurrentMinutes += oDTP.oData.iCurrentSeconds / 60; oDTP.oData.iCurrentSeconds = oDTP.oData.iCurrentSeconds % 60; } if(oDTP.oData.iCurrentMinutes > 59) { oDTP.oData.iCurrentHour += oDTP.oData.iCurrentMinutes / 60; oDTP.oData.iCurrentMinutes = oDTP.oData.iCurrentMinutes % 60; } if(oDTP.oData.bIs12Hour) { if(oDTP.oData.iCurrentHour > 12) oDTP.oData.iCurrentHour = (oDTP.oData.iCurrentHour % 12); } else { if(oDTP.oData.iCurrentHour > 23) oDTP.oData.iCurrentHour = (oDTP.oData.iCurrentHour % 23); } if(oDTP.oData.bIs12Hour) { sMeridiem = $(oDTP.element).find(".meridiem .dtpicker-compValue").val(); if($.cf._compare(sMeridiem, "AM") || $.cf._compare(sMeridiem, "PM")) oDTP.oData.sCurrentMeridiem = sMeridiem; if($.cf._compare(oDTP.oData.sCurrentMeridiem, "PM")) { if(oDTP.oData.iCurrentHour !== 12 && oDTP.oData.iCurrentHour < 13) oDTP.oData.iCurrentHour += 12; } if($.cf._compare(oDTP.oData.sCurrentMeridiem, "AM") && oDTP.oData.iCurrentHour === 12) oDTP.oData.iCurrentHour = 0; } } }, _setCurrentDate: function() { var oDTP = this; if(oDTP.oData.bTimeMode || oDTP.oData.bDateTimeMode) { if(oDTP.oData.iCurrentSeconds > 59) { oDTP.oData.iCurrentMinutes += oDTP.oData.iCurrentSeconds / 60; oDTP.oData.iCurrentSeconds = oDTP.oData.iCurrentSeconds % 60; } else if(oDTP.oData.iCurrentSeconds < 0) { oDTP.oData.iCurrentMinutes -= oDTP.settings.minuteInterval; oDTP.oData.iCurrentSeconds += 60; } oDTP.oData.iCurrentMinutes = oDTP._adjustMinutes(oDTP.oData.iCurrentMinutes); oDTP.oData.iCurrentSeconds = oDTP._adjustSeconds(oDTP.oData.iCurrentSeconds); } var dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0), bGTMaxDate = false, bLTMinDate = false, sFormat, oDate, oFormattedDate, oFormattedTime, sDate, sTime, sDateTime; if(oDTP.oData.dMaxValue !== null) bGTMaxDate = (dTempDate.getTime() > oDTP.oData.dMaxValue.getTime()); if(oDTP.oData.dMinValue !== null) bLTMinDate = (dTempDate.getTime() < oDTP.oData.dMinValue.getTime()); if(bGTMaxDate || bLTMinDate) { var bCDGTMaxDate = false, bCDLTMinDate = false; if(oDTP.oData.dMaxValue !== null) bCDGTMaxDate = (oDTP.oData.dCurrentDate.getTime() > oDTP.oData.dMaxValue.getTime()); if(oDTP.oData.dMinValue !== null) bCDLTMinDate = (oDTP.oData.dCurrentDate.getTime() < oDTP.oData.dMinValue.getTime()); if(!(bCDGTMaxDate || bCDLTMinDate)) dTempDate = new Date(oDTP.oData.dCurrentDate); else { if(bCDGTMaxDate) { dTempDate = new Date(oDTP.oData.dMaxValue); console.log("Info : Date/Time/DateTime you entered is later than Maximum value, so DateTimePicker is showing Maximum value in Input Field."); } if(bCDLTMinDate) { dTempDate = new Date(oDTP.oData.dMinValue); console.log("Info : Date/Time/DateTime you entered is earlier than Minimum value, so DateTimePicker is showing Minimum value in Input Field."); } console.log("Please enter proper Date/Time/DateTime values."); } } oDTP.oData.dCurrentDate = new Date(dTempDate); oDTP._setVariablesForDate(); oDate = {}; sDate = ""; sTime = ""; sDateTime = ""; if(oDTP.oData.bDateMode || oDTP.oData.bDateTimeMode) { if(oDTP.oData.bDateMode && (oDTP.oData.bArrMatchFormat[4] || oDTP.oData.bArrMatchFormat[5] || oDTP.oData.bArrMatchFormat[6])) oDTP.oData.iCurrentDay = 1; oFormattedDate = oDTP._formatDate(); $(oDTP.element).find(".day .dtpicker-compValue").val(oFormattedDate.dd); if(oDTP.oData.bDateMode) { if(oDTP.oData.bArrMatchFormat[4] || oDTP.oData.bArrMatchFormat[7]) // "MM-yyyy" $(oDTP.element).find(".month .dtpicker-compValue").val(oFormattedDate.MM); else if(oDTP.oData.bArrMatchFormat[6]) // "MMMM yyyy" $(oDTP.element).find(".month .dtpicker-compValue").val(oFormattedDate.month); else $(oDTP.element).find(".month .dtpicker-compValue").val(oFormattedDate.monthShort); } else $(oDTP.element).find(".month .dtpicker-compValue").val(oFormattedDate.monthShort); $(oDTP.element).find(".year .dtpicker-compValue").val(oFormattedDate.yyyy); if(oDTP.settings.formatHumanDate) { oDate = $.extend(oDate, oFormattedDate); } else { if(oDTP.oData.bDateMode && (oDTP.oData.bArrMatchFormat[4] || oDTP.oData.bArrMatchFormat[5] || oDTP.oData.bArrMatchFormat[6] || oDTP.oData.bArrMatchFormat[7])) { if(oDTP.oData.bArrMatchFormat[4]) sDate = oFormattedDate.MM + oDTP.settings.monthYearSeparator + oFormattedDate.yyyy; else if(oDTP.oData.bArrMatchFormat[5]) sDate = oFormattedDate.monthShort + oDTP.settings.monthYearSeparator + oFormattedDate.yyyy; else if(oDTP.oData.bArrMatchFormat[6]) sDate = oFormattedDate.month + oDTP.settings.monthYearSeparator + oFormattedDate.yyyy; else if(oDTP.oData.bArrMatchFormat[7]) sDate = oFormattedDate.yyyy + oDTP.settings.monthYearSeparator + oFormattedDate.MM; } else sDate = oFormattedDate.dayShort + ", " + oFormattedDate.month + " " + oFormattedDate.dd + ", " + oFormattedDate.yyyy; } } if(oDTP.oData.bTimeMode || oDTP.oData.bDateTimeMode) { oFormattedTime = oDTP._formatTime(); if(oDTP.oData.bIs12Hour) $(oDTP.element).find(".meridiem .dtpicker-compValue").val(oDTP.oData.sCurrentMeridiem); $(oDTP.element).find(".hour .dtpicker-compValue").val(oFormattedTime.hour); $(oDTP.element).find(".minutes .dtpicker-compValue").val(oFormattedTime.mm); $(oDTP.element).find(".seconds .dtpicker-compValue").val(oFormattedTime.ss); if(oDTP.settings.formatHumanDate) { oDate = $.extend(oDate, oFormattedTime); } else { var bShowSecondsTime = (oDTP.oData.bTimeMode && ( oDTP.oData.bArrMatchFormat[0] || oDTP.oData.bArrMatchFormat[1])), bShowSecondsDateTime = (oDTP.oData.bDateTimeMode && (oDTP.oData.bArrMatchFormat[0] || oDTP.oData.bArrMatchFormat[1] || oDTP.oData.bArrMatchFormat[2] || oDTP.oData.bArrMatchFormat[3] || oDTP.oData.bArrMatchFormat[4] || oDTP.oData.bArrMatchFormat[5] || oDTP.oData.bArrMatchFormat[6] || oDTP.oData.bArrMatchFormat[7])); if(bShowSecondsTime || bShowSecondsDateTime) sTime = oFormattedTime.hour + oDTP.settings.timeSeparator + oFormattedTime.mm + oDTP.settings.timeSeparator + oFormattedTime.ss; else sTime = oFormattedTime.hour + oDTP.settings.timeSeparator + oFormattedTime.mm; if(oDTP.oData.bIs12Hour) sTime += oDTP.settings.timeMeridiemSeparator + oDTP.oData.sCurrentMeridiem; } } if(oDTP.settings.formatHumanDate) { if(oDTP.oData.bDateTimeMode) sFormat = oDTP.oData.sDateFormat; else if(oDTP.oData.bDateMode) sFormat = oDTP.oData.sTimeFormat; else if(oDTP.oData.bTimeMode) sFormat = oDTP.oData.sDateTimeFormat; sDateTime = oDTP.settings.formatHumanDate.call(oDTP, oDate, oDTP.settings.mode, sFormat); } else { if(oDTP.oData.bDateTimeMode) sDateTime = sDate + oDTP.settings.dateTimeSeparator + sTime; else if(oDTP.oData.bDateMode) sDateTime = sDate; else if(oDTP.oData.bTimeMode) sDateTime = sTime; } $(oDTP.element).find(".dtpicker-value").html(sDateTime); oDTP._setButtons(); }, _formatDate: function(oDTVP) { var oDTP = this; var oDTV = {}, sDay, sYear, iMonth, sMonth, sMonthShort, sMonthFull, iDayOfTheWeek, sDayOfTheWeek, sDayOfTheWeekFull; if($.cf._isValid(oDTVP)) oDTV = $.extend({}, oDTVP); else { oDTV.iCurrentDay = oDTP.oData.iCurrentDay; oDTV.iCurrentMonth = oDTP.oData.iCurrentMonth; oDTV.iCurrentYear = oDTP.oData.iCurrentYear; oDTV.iCurrentWeekday = oDTP.oData.iCurrentWeekday; } sDay = oDTV.iCurrentDay; sDay = (sDay < 10) ? ("0" + sDay) : sDay; iMonth = oDTV.iCurrentMonth; sMonth = oDTV.iCurrentMonth + 1; sMonth = (sMonth < 10) ? ("0" + sMonth) : sMonth; sMonthShort = oDTP.settings.shortMonthNames[iMonth]; sMonthFull = oDTP.settings.fullMonthNames[iMonth]; sYear = oDTV.iCurrentYear; iDayOfTheWeek = oDTV.iCurrentWeekday; sDayOfTheWeek = oDTP.settings.shortDayNames[iDayOfTheWeek]; sDayOfTheWeekFull = oDTP.settings.fullDayNames[iDayOfTheWeek]; return { "dd": sDay, "MM": sMonth, "monthShort": sMonthShort, "month": sMonthFull, "yyyy": sYear, "dayShort": sDayOfTheWeek, "day": sDayOfTheWeekFull }; }, _formatTime: function(oDTVP) { var oDTP = this; var oDTV = {}, iHour24, sHour24, iHour12, sHour12, sHour, sMinutes, sSeconds; if($.cf._isValid(oDTVP)) oDTV = $.extend({}, oDTVP); else { oDTV.iCurrentHour = oDTP.oData.iCurrentHour; oDTV.iCurrentMinutes = oDTP.oData.iCurrentMinutes; oDTV.iCurrentSeconds = oDTP.oData.iCurrentSeconds; oDTV.sCurrentMeridiem = oDTP.oData.sCurrentMeridiem; } iHour24 = oDTV.iCurrentHour; sHour24 = (iHour24 < 10) ? ("0" + iHour24) : iHour24; sHour = sHour24; iHour12 = oDTV.iCurrentHour; if(iHour12 > 12) iHour12 -= 12; if(sHour === "00") iHour12 = 12; sHour12 = (iHour12 < 10) ? ("0" + iHour12) : iHour12; if(oDTP.oData.bIs12Hour) sHour = sHour12; sMinutes = oDTV.iCurrentMinutes; sMinutes = (sMinutes < 10) ? ("0" + sMinutes) : sMinutes; sSeconds = oDTV.iCurrentSeconds; sSeconds = (sSeconds < 10) ? ("0" + sSeconds) : sSeconds; return { "H": iHour24, "HH": sHour24, "h": iHour12, "hh": sHour12, "hour": sHour, "m": oDTV.iCurrentMinutes, "mm": sMinutes, "s": oDTV.iCurrentSeconds, "ss": sSeconds, "ME": oDTV.sCurrentMeridiem }; }, _setButtons: function() { var oDTP = this; $(oDTP.element).find(".dtpicker-compButton").removeClass("dtpicker-compButtonDisable").addClass("dtpicker-compButtonEnable"); var dTempDate; if(oDTP.oData.dMaxValue !== null) { if(oDTP.oData.bTimeMode) { // Decrement Hour if((oDTP.oData.iCurrentHour + 1) > oDTP.oData.dMaxValue.getHours() || ((oDTP.oData.iCurrentHour + 1) === oDTP.oData.dMaxValue.getHours() && oDTP.oData.iCurrentMinutes > oDTP.oData.dMaxValue.getMinutes())) $(oDTP.element).find(".hour .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Decrement Minutes if(oDTP.oData.iCurrentHour >= oDTP.oData.dMaxValue.getHours() && (oDTP.oData.iCurrentMinutes + 1) > oDTP.oData.dMaxValue.getMinutes()) $(oDTP.element).find(".minutes .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); } else { // Increment Day dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, (oDTP.oData.iCurrentDay + 1), oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() > oDTP.oData.dMaxValue.getTime()) $(oDTP.element).find(".day .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Increment Month dTempDate = new Date(oDTP.oData.iCurrentYear, (oDTP.oData.iCurrentMonth + 1), oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() > oDTP.oData.dMaxValue.getTime()) $(oDTP.element).find(".month .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Increment Year dTempDate = new Date((oDTP.oData.iCurrentYear + 1), oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() > oDTP.oData.dMaxValue.getTime()) $(oDTP.element).find(".year .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Increment Hour dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, (oDTP.oData.iCurrentHour + 1), oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() > oDTP.oData.dMaxValue.getTime()) $(oDTP.element).find(".hour .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Increment Minutes dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, (oDTP.oData.iCurrentMinutes + 1), oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() > oDTP.oData.dMaxValue.getTime()) $(oDTP.element).find(".minutes .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Increment Seconds dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, (oDTP.oData.iCurrentSeconds + 1), 0); if(dTempDate.getTime() > oDTP.oData.dMaxValue.getTime()) $(oDTP.element).find(".seconds .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); } } if(oDTP.oData.dMinValue !== null) { if(oDTP.oData.bTimeMode) { // Decrement Hour if((oDTP.oData.iCurrentHour - 1) < oDTP.oData.dMinValue.getHours() || ((oDTP.oData.iCurrentHour - 1) === oDTP.oData.dMinValue.getHours() && oDTP.oData.iCurrentMinutes < oDTP.oData.dMinValue.getMinutes())) $(oDTP.element).find(".hour .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Decrement Minutes if(oDTP.oData.iCurrentHour <= oDTP.oData.dMinValue.getHours() && (oDTP.oData.iCurrentMinutes - 1) < oDTP.oData.dMinValue.getMinutes()) $(oDTP.element).find(".minutes .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); } else { // Decrement Day dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, (oDTP.oData.iCurrentDay - 1), oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() < oDTP.oData.dMinValue.getTime()) $(oDTP.element).find(".day .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Decrement Month dTempDate = new Date(oDTP.oData.iCurrentYear, (oDTP.oData.iCurrentMonth - 1), oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() < oDTP.oData.dMinValue.getTime()) $(oDTP.element).find(".month .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Decrement Year dTempDate = new Date((oDTP.oData.iCurrentYear - 1), oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() < oDTP.oData.dMinValue.getTime()) $(oDTP.element).find(".year .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Decrement Hour dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, (oDTP.oData.iCurrentHour - 1), oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() < oDTP.oData.dMinValue.getTime()) $(oDTP.element).find(".hour .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Decrement Minutes dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, (oDTP.oData.iCurrentMinutes - 1), oDTP.oData.iCurrentSeconds, 0); if(dTempDate.getTime() < oDTP.oData.dMinValue.getTime()) $(oDTP.element).find(".minutes .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); // Decrement Seconds dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, oDTP.oData.iCurrentHour, oDTP.oData.iCurrentMinutes, (oDTP.oData.iCurrentSeconds - 1), 0); if(dTempDate.getTime() < oDTP.oData.dMinValue.getTime()) $(oDTP.element).find(".seconds .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); } } if(oDTP.oData.bIs12Hour) { var iTempHour, iTempMinutes; if(oDTP.oData.dMaxValue !== null || oDTP.oData.dMinValue !== null) { iTempHour = oDTP.oData.iCurrentHour; if($.cf._compare(oDTP.oData.sCurrentMeridiem, "AM")) iTempHour += 12; else if($.cf._compare(oDTP.oData.sCurrentMeridiem, "PM")) iTempHour -= 12; dTempDate = new Date(oDTP.oData.iCurrentYear, oDTP.oData.iCurrentMonth, oDTP.oData.iCurrentDay, iTempHour, oDTP.oData.iCurrentMinutes, oDTP.oData.iCurrentSeconds, 0); if(oDTP.oData.dMaxValue !== null) { if(oDTP.oData.bTimeMode) { iTempMinutes = oDTP.oData.iCurrentMinutes; if(iTempHour > oDTP.oData.dMaxValue.getHours() || (iTempHour === oDTP.oData.dMaxValue.getHours() && iTempMinutes > oDTP.oData.dMaxValue.getMinutes())) $(oDTP.element).find(".meridiem .dtpicker-compButton").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); } else { if(dTempDate.getTime() > oDTP.oData.dMaxValue.getTime()) $(oDTP.element).find(".meridiem .dtpicker-compButton").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); } } if(oDTP.oData.dMinValue !== null) { if(oDTP.oData.bTimeMode) { iTempMinutes = oDTP.oData.iCurrentMinutes; if(iTempHour < oDTP.oData.dMinValue.getHours() || (iTempHour === oDTP.oData.dMinValue.getHours() && iTempMinutes < oDTP.oData.dMinValue.getMinutes())) $(oDTP.element).find(".meridiem .dtpicker-compButton").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); } else { if(dTempDate.getTime() < oDTP.oData.dMinValue.getTime()) $(oDTP.element).find(".meridiem .dtpicker-compButton").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"); } } } } }, // Public Method setIsPopup: function(bIsPopup) { var oDTP = this; if(!oDTP.settings.isInline) { oDTP.settings.isPopup = bIsPopup; if($(oDTP.element).css("display") !== "none") oDTP._hidePicker(0); if(oDTP.settings.isPopup) { $(oDTP.element).addClass("dtpicker-mobile"); $(oDTP.element).css({position: "fixed", top: 0, left: 0, width: "100%", height: "100%"}); } else { $(oDTP.element).removeClass("dtpicker-mobile"); if(oDTP.oData.oInputElement !== null) { var iElemTop = $(oDTP.oData.oInputElement).offset().top + $(oDTP.oData.oInputElement).outerHeight(), iElemLeft = $(oDTP.oData.oInputElement).offset().left, iElemWidth = $(oDTP.oData.oInputElement).outerWidth(); $(oDTP.element).css({position: "absolute", top: iElemTop, left: iElemLeft, width: iElemWidth, height: "auto"}); } } } }, _compareDates: function(dDate1, dDate2) { dDate1 = new Date(dDate1.getDate(), dDate1.getMonth(), dDate1.getFullYear(), 0, 0, 0, 0); var iDateDiff = (dDate1.getTime() - dDate2.getTime()) / 864E5; return (iDateDiff === 0) ? iDateDiff: (iDateDiff/Math.abs(iDateDiff)); }, _compareTime: function(dTime1, dTime2) { var iTimeMatch = 0; if((dTime1.getHours() === dTime2.getHours()) && (dTime1.getMinutes() === dTime2.getMinutes())) iTimeMatch = 1; // 1 = Exact Match else { if(dTime1.getHours() < dTime2.getHours()) iTimeMatch = 2; // time1 < time2 else if(dTime1.getHours() > dTime2.getHours()) iTimeMatch = 3; // time1 > time2 else if(dTime1.getHours() === dTime2.getHours()) { if(dTime1.getMinutes() < dTime2.getMinutes()) iTimeMatch = 2; // time1 < time2 else if(dTime1.getMinutes() > dTime2.getMinutes()) iTimeMatch = 3; // time1 > time2 } } return iTimeMatch; }, _compareDateTime: function(dDate1, dDate2) { var iDateTimeDiff = (dDate1.getTime() - dDate2.getTime()) / 6E4; return (iDateTimeDiff === 0) ? iDateTimeDiff: (iDateTimeDiff/Math.abs(iDateTimeDiff)); }, _determineMeridiemFromHourAndMinutes: function(iHour, iMinutes) { if(iHour > 12 || (iHour === 12 && iMinutes >= 0)) { return "PM"; } else { return "AM"; } }, // Public Method setLanguage: function(sLanguage) { var oDTP = this; oDTP.settings = $.extend({}, $.DateTimePicker.defaults, $.DateTimePicker.i18n[sLanguage], oDTP.options); oDTP.settings.language = sLanguage; oDTP._setDateFormatArray(); // Set DateFormatArray oDTP._setTimeFormatArray(); // Set TimeFormatArray oDTP._setDateTimeFormatArray(); // Set DateTimeFormatArray return oDTP; } }; })); ```
/content/code_sandbox/public/vendor/datetimepicker/src/DateTimePicker.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
29,908
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ /* language: Czech file: DateTimePicker-i18n-cs author: aiphee (path_to_url */ (function ($) { $.DateTimePicker.i18n["cs"] = $.extend($.DateTimePicker.i18n["cs"], { language: "cs", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", shortDayNames: ["Ne", "Po", "t", "St", "t", "P", "So"], fullDayNames: ["Nedle", "Pondl", "ter", "Steda", "tvrtek", "Ptek", "Sobota"], shortMonthNames: ["Led", "no", "Be", "Dub", "Kv", "er", "vc", "Srp", "Z", "j", "Lis", "Pro"], fullMonthNames: ["Leden", "nor", "Bezen", "Duben", "Kvten", "erven", "ervenec", "Srpen", "Z", "jen", "Listopad", "Prosinec"], titleContentDate: "Nastavit datum", titleContentTime: "Nastavit as", titleContentDateTime: "Nastavit datum a as", setButtonContent: "Nastavit", clearButtonContent: "Resetovat" }); })(jQuery); ```
/content/code_sandbox/public/vendor/datetimepicker/src/i18n/DateTimePicker-i18n-cs.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
374
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ /* language: Italiano file: DateTimePicker-i18n-it author: Cristian Segattini */ (function ($) { $.DateTimePicker.i18n["it"] = $.extend($.DateTimePicker.i18n["it"], { language: "it", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", shortDayNames: ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"], fullDayNames: ["Domenica", "Luned", "Marted", "Mercoled", "Gioved", "Venerd", "Sabato"], shortMonthNames: ["Gen", "Feb", "Mar", "Apr", "Mag", "Giu", "Lug", "Ago", "Set", "Ott", "Nov", "Dic"], fullMonthNames: ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"], titleContentDate: "Imposta Data", titleContentTime: "Imposta Ora", titleContentDateTime: "Imposta Data & Ora", setButtonContent: "Imposta", clearButtonContent: "Pulisci" }); })(jQuery); ```
/content/code_sandbox/public/vendor/datetimepicker/src/i18n/DateTimePicker-i18n-it.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
380
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ /* language: Ukrainian file: DateTimePicker-i18n-uk author: Valery Bogdanov (path_to_url */ (function ($) { $.DateTimePicker.i18n["uk"] = $.extend($.DateTimePicker.i18n["uk"], { language: "uk", dateTimeFormat: "dd-MM-yyyy HH:mm", dateFormat: "dd-MM-yyyy", timeFormat: "HH:mm", shortDayNames: ["", "", "", "", "", "", ""], fullDayNames: ["", "", "", "", "", "", ""], shortMonthNames: ["", "", "", "", "", "", "", "", "", "", "", ""], fullMonthNames: ["", "", "", "", "", "", "", "", "", "", "", ""], fullDayNames: ["", "", "", "", "", "'", ""], shortMonthNames: ["", "", "", "", "", "", "", "", "", "", "", ""], fullMonthNames: ["", "", "", "", "", "", "", "", "", "", "", ""], titleContentDate: " ", titleContentTime: " ", titleContentDateTime: " ", setButtonContent: "", clearButtonContent: "", formatHumanDate: function(oDate, sMode, sFormat) { if(sMode === "date") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ " " + oDate.yyyy; else if(sMode === "time") return oDate.HH + ":" + oDate.mm + ":" + oDate.ss; else if(sMode === "datetime") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ " " + oDate.yyyy + ", " + oDate.HH + ":" + oDate.mm + ":" + oDate.ss; } }); })(jQuery); ```
/content/code_sandbox/public/vendor/datetimepicker/src/i18n/DateTimePicker-i18n-uk.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
454
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ Array.prototype.indexOf||(Array.prototype.indexOf=function(t){var r=this.length,n=Number(arguments[1])||0;for((n=n<0?Math.ceil(n):Math.floor(n))<0&&(n+=r);n<r;n++)if(n in this&&this[n]===t)return n;return-1}),jQuery.fn.fadeIn=function(){this.show()},jQuery.fn.fadeOut=function(){this.hide()}; ```
/content/code_sandbox/public/vendor/datetimepicker/dist/DateTimePicker-ltie9.min.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
147
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ /* language: German file: DateTimePicker-i18n-de author: Lu, Feng (path_to_url */ (function ($) { $.DateTimePicker.i18n["de"] = $.extend($.DateTimePicker.i18n["de"], { language: "de", dateTimeFormat: "dd-MMM-yyyy HH:mm:ss", dateFormat: "dd-MMM-yyyy", timeFormat: "HH:mm:ss", shortDayNames: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"], fullDayNames: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"], shortMonthNames: ["Jan", "Feb", "Mr", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"], fullMonthNames: ["Januar", "Februar", "Mrz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"], titleContentDate: "Datum auswhlen", titleContentTime: "Zeit auswhlen", titleContentDateTime: "Datum & Zeit auswhlen", setButtonContent: "Auswhlen", clearButtonContent: "Zurcksetzen", formatHumanDate: function(oDate, sMode, sFormat) { if(sMode === "date") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ ", " + oDate.yyyy; else if(sMode === "time") return oDate.HH + ":" + oDate.mm + ":" + oDate.ss; else if(sMode === "datetime") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ ", " + oDate.yyyy + " " + oDate.HH + ":" + oDate.mm + ":" + oDate.ss; } }); })(jQuery); ```
/content/code_sandbox/public/vendor/datetimepicker/src/i18n/DateTimePicker-i18n-de.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
522
```css .dtpicker-cont{top:25%}.dtpicker-overlay{zoom:1!important} ```
/content/code_sandbox/public/vendor/datetimepicker/dist/DateTimePicker-ltie9.min.css
css
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
20
```css .dtpicker-overlay{z-index:2000;display:none;min-width:300px;background:rgba(0,0,0,.2);font-size:12px;-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.dtpicker-mobile{position:fixed;top:0;left:0;width:100%;height:100%}.dtpicker-overlay *{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-ms-box-sizing:border-box;-webkit-tap-highlight-color:transparent}.dtpicker-bg{width:100%;height:100%;font-family:Arial}.dtpicker-cont{border:1px solid #ecf0f1}.dtpicker-mobile .dtpicker-cont{position:relative;top:50%;-webkit-transform:translateY(-50%);-moz-transform:translateY(-50%);-o-transform:translateY(-50%);-ms-transform:translateY(-50%);transform:translateY(-50%);border:none}.dtpicker-content{margin:0 auto;padding:1em 0;max-width:500px;background:#fff}.dtpicker-mobile .dtpicker-content{width:97%}.dtpicker-subcontent{position:relative}.dtpicker-header{margin:.2em 1em}.dtpicker-header .dtpicker-title{color:#2980b9;text-align:center;font-size:1.1em}.dtpicker-header .dtpicker-close{position:absolute;top:-.7em;right:.3em;padding:.5em .5em 1em 1em;color:#ff3b30;font-size:1.5em;cursor:pointer}.dtpicker-header .dtpicker-close:hover{color:#ff3b30}.dtpicker-header .dtpicker-value{padding:.8em .2em .2em .2em;color:#ff3b30;text-align:center;font-size:1.4em}.dtpicker-components{overflow:hidden;margin:1em 1em;font-size:1.3em}.dtpicker-components *{margin:0;padding:0}.dtpicker-components .dtpicker-compOutline{display:inline-block;float:left}.dtpicker-comp2{width:50%}.dtpicker-comp3{width:33.3%}.dtpicker-comp4{width:25%}.dtpicker-comp5{width:20%}.dtpicker-comp6{width:16.66%}.dtpicker-comp7{width:14.285%}.dtpicker-components .dtpicker-comp{margin:2%;text-align:center}.dtpicker-components .dtpicker-comp>*{display:block;height:30px;color:#2980b9;text-align:center;line-height:30px}.dtpicker-components .dtpicker-comp>:hover{color:#2980b9}.dtpicker-components .dtpicker-compButtonEnable{opacity:1}.dtpicker-components .dtpicker-compButtonDisable{opacity:.5}.dtpicker-components .dtpicker-compButton{background:#fff;font-size:140%;cursor:pointer}.dtpicker-components .dtpicker-compValue{margin:.4em 0;width:100%;border:none;background:#fff;font-size:100%;-webkit-appearance:none;-moz-appearance:none}.dtpicker-overlay .dtpicker-compValue:focus{outline:0;background:#f2fcff}.dtpicker-buttonCont{overflow:hidden;margin:.2em 1em}.dtpicker-buttonCont .dtpicker-button{display:block;padding:.6em 0;width:47%;background:#ff3b30;color:#fff;text-align:center;font-size:1.3em;cursor:pointer}.dtpicker-buttonCont .dtpicker-button:hover{color:#fff}.dtpicker-singleButton .dtpicker-button{margin:.2em auto}.dtpicker-twoButtons .dtpicker-buttonSet{float:left}.dtpicker-twoButtons .dtpicker-buttonClear{float:right} ```
/content/code_sandbox/public/vendor/datetimepicker/dist/DateTimePicker.min.css
css
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
865
```javascript /* your_sha256_hash------------- jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile Version 0.1.38 Contributors : path_to_url Repository : path_to_url Documentation : path_to_url your_sha256_hash------------- */ Object.keys||(Object.keys=function(t){var e=[];for(var a in t)t.hasOwnProperty(a)&&e.push(a);return e}),$.DateTimePicker=$.DateTimePicker||{name:"DateTimePicker",i18n:{},defaults:{mode:"date",defaultDate:null,dateSeparator:"-",timeSeparator:":",timeMeridiemSeparator:" ",dateTimeSeparator:" ",monthYearSeparator:" ",dateTimeFormat:"dd-MM-yyyy HH:mm",dateFormat:"dd-MM-yyyy",timeFormat:"HH:mm",maxDate:null,minDate:null,maxTime:null,minTime:null,maxDateTime:null,minDateTime:null,shortDayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],fullDayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortMonthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],fullMonthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],labels:null,minuteInterval:1,roundOffMinutes:!0,secondsInterval:1,roundOffSeconds:!0,showHeader:!0,titleContentDate:"Set Date",titleContentTime:"Set Time",titleContentDateTime:"Set Date & Time",buttonsToDisplay:["HeaderCloseButton","SetButton","ClearButton"],setButtonContent:"Set",clearButtonContent:"Clear",incrementButtonContent:"+",decrementButtonContent:"-",setValueInTextboxOnEveryClick:!1,readonlyInputs:!1,animationDuration:400,touchHoldInterval:300,captureTouchHold:!1,mouseHoldInterval:50,captureMouseHold:!1,isPopup:!0,parentElement:"body",isInline:!1,inputElement:null,language:"",init:null,addEventHandlers:null,beforeShow:null,afterShow:null,beforeHide:null,afterHide:null,buttonClicked:null,settingValueOfElement:null,formatHumanDate:null,parseDateTimeString:null,formatDateTimeString:null},dataObject:{dCurrentDate:new Date,iCurrentDay:0,iCurrentMonth:0,iCurrentYear:0,iCurrentHour:0,iCurrentMinutes:0,iCurrentSeconds:0,sCurrentMeridiem:"",iMaxNumberOfDays:0,sDateFormat:"",sTimeFormat:"",sDateTimeFormat:"",dMinValue:null,dMaxValue:null,sArrInputDateFormats:[],sArrInputTimeFormats:[],sArrInputDateTimeFormats:[],bArrMatchFormat:[],bDateMode:!1,bTimeMode:!1,bDateTimeMode:!1,oInputElement:null,iTabIndex:0,bElemFocused:!1,bIs12Hour:!1,sTouchButton:null,iTouchStart:null,oTimeInterval:null,bIsTouchDevice:"ontouchstart"in document.documentElement}},$.cf={_isValid:function(t){return null!=t&&""!==t},_compare:function(t,e){return null!=t&&null!=e&&t.toLowerCase()===e.toLowerCase()}},function(t){"function"==typeof define&&define.amd?define(["jquery"],t):"object"==typeof exports?module.exports=t(require("jquery")):t(jQuery)}(function(b){"use strict";function o(t,e){this.element=t;var a;a=b.cf._isValid(e)&&b.cf._isValid(e.language)?e.language:b.DateTimePicker.defaults.language,this.settings=b.extend({},b.DateTimePicker.defaults,b.DateTimePicker.i18n[a],e),this.options=e,this.oData=b.extend({},b.DateTimePicker.dataObject),this._defaults=b.DateTimePicker.defaults,this._name=b.DateTimePicker.name,this.init()}b.fn.DateTimePicker=function(t){var e,a,r=b(this).data(),n=r?Object.keys(r):[];if("string"!=typeof t)return this.each(function(){b.removeData(this,"plugin_DateTimePicker"),b.data(this,"plugin_DateTimePicker")||b.data(this,"plugin_DateTimePicker",new o(this,t))});if(b.cf._isValid(r))if("destroy"===t){if(0<n.length)for(e in n)if(-1!==(a=n[e]).search("plugin_DateTimePicker")){b(document).unbind("click.DateTimePicker keydown.DateTimePicker keyup.DateTimePicker"),b(this).children().remove(),b(this).removeData(),b(this).unbind(),b(this).removeClass("dtpicker-overlay dtpicker-mobile dtpicker-inline"),r=r[a];break}}else if("object"===t&&0<n.length)for(e in n)if(-1!==(a=n[e]).search("plugin_DateTimePicker"))return r[a]},o.prototype={init:function(){var t=this;t._setDateFormatArray(),t._setTimeFormatArray(),t._setDateTimeFormatArray(),void 0!==b(t.element).data("parentelement")&&(t.settings.parentElement=b(t.element).data("parentelement")),t.settings.isPopup&&!t.settings.isInline&&(t._createPicker(),b(t.element).addClass("dtpicker-mobile")),t.settings.isInline&&(t._createPicker(),t._showPicker(t.settings.inputElement)),t.settings.init&&t.settings.init.call(t),t._addEventHandlersForInput()},_setDateFormatArray:function(){var t=this;t.oData.sArrInputDateFormats=[];var e="";e="dd"+t.settings.dateSeparator+"MM"+t.settings.dateSeparator+"yyyy",t.oData.sArrInputDateFormats.push(e),e="MM"+t.settings.dateSeparator+"dd"+t.settings.dateSeparator+"yyyy",t.oData.sArrInputDateFormats.push(e),e="yyyy"+t.settings.dateSeparator+"MM"+t.settings.dateSeparator+"dd",t.oData.sArrInputDateFormats.push(e),e="dd"+t.settings.dateSeparator+"MMM"+t.settings.dateSeparator+"yyyy",t.oData.sArrInputDateFormats.push(e),e="MM"+t.settings.monthYearSeparator+"yyyy",t.oData.sArrInputDateFormats.push(e),e="MMM"+t.settings.monthYearSeparator+"yyyy",t.oData.sArrInputDateFormats.push(e),e="MMMM"+t.settings.monthYearSeparator+"yyyy",t.oData.sArrInputDateFormats.push(e),e="yyyy"+t.settings.monthYearSeparator+"MM",t.oData.sArrInputDateFormats.push(e)},_setTimeFormatArray:function(){var t=this;t.oData.sArrInputTimeFormats=[];var e="";e="hh"+t.settings.timeSeparator+"mm"+t.settings.timeSeparator+"ss"+t.settings.timeMeridiemSeparator+"AA",t.oData.sArrInputTimeFormats.push(e),e="HH"+t.settings.timeSeparator+"mm"+t.settings.timeSeparator+"ss",t.oData.sArrInputTimeFormats.push(e),e="hh"+t.settings.timeSeparator+"mm"+t.settings.timeMeridiemSeparator+"AA",t.oData.sArrInputTimeFormats.push(e),e="HH"+t.settings.timeSeparator+"mm",t.oData.sArrInputTimeFormats.push(e)},_setDateTimeFormatArray:function(){var t=this;t.oData.sArrInputDateTimeFormats=[];var e="",a="",r="";e="dd"+t.settings.dateSeparator+"MM"+t.settings.dateSeparator+"yyyy",a="HH"+t.settings.timeSeparator+"mm"+t.settings.timeSeparator+"ss",r=e+t.settings.dateTimeSeparator+a,t.oData.sArrInputDateTimeFormats.push(r),e="dd"+t.settings.dateSeparator+"MM"+t.settings.dateSeparator+"yyyy",a="hh"+t.settings.timeSeparator+"mm"+t.settings.timeSeparator+"ss"+t.settings.timeMeridiemSeparator+"AA",r=e+t.settings.dateTimeSeparator+a,t.oData.sArrInputDateTimeFormats.push(r),e="MM"+t.settings.dateSeparator+"dd"+t.settings.dateSeparator+"yyyy",a="HH"+t.settings.timeSeparator+"mm"+t.settings.timeSeparator+"ss",r=e+t.settings.dateTimeSeparator+a,t.oData.sArrInputDateTimeFormats.push(r),e="MM"+t.settings.dateSeparator+"dd"+t.settings.dateSeparator+"yyyy",a="hh"+t.settings.timeSeparator+"mm"+t.settings.timeSeparator+"ss"+t.settings.timeMeridiemSeparator+"AA",r=e+t.settings.dateTimeSeparator+a,t.oData.sArrInputDateTimeFormats.push(r),e="yyyy"+t.settings.dateSeparator+"MM"+t.settings.dateSeparator+"dd",a="HH"+t.settings.timeSeparator+"mm"+t.settings.timeSeparator+"ss",r=e+t.settings.dateTimeSeparator+a,t.oData.sArrInputDateTimeFormats.push(r),e="yyyy"+t.settings.dateSeparator+"MM"+t.settings.dateSeparator+"dd",a="hh"+t.settings.timeSeparator+"mm"+t.settings.timeSeparator+"ss"+t.settings.timeMeridiemSeparator+"AA",r=e+t.settings.dateTimeSeparator+a,t.oData.sArrInputDateTimeFormats.push(r),e="dd"+t.settings.dateSeparator+"MMM"+t.settings.dateSeparator+"yyyy",a="hh"+t.settings.timeSeparator+"mm"+t.settings.timeSeparator+"ss",r=e+t.settings.dateTimeSeparator+a,t.oData.sArrInputDateTimeFormats.push(r),e="dd"+t.settings.dateSeparator+"MMM"+t.settings.dateSeparator+"yyyy",a="hh"+t.settings.timeSeparator+"mm"+t.settings.timeSeparator+"ss"+t.settings.timeMeridiemSeparator+"AA",r=e+t.settings.dateTimeSeparator+a,t.oData.sArrInputDateTimeFormats.push(r),e="dd"+t.settings.dateSeparator+"MM"+t.settings.dateSeparator+"yyyy",a="HH"+t.settings.timeSeparator+"mm",r=e+t.settings.dateTimeSeparator+a,t.oData.sArrInputDateTimeFormats.push(r),e="dd"+t.settings.dateSeparator+"MM"+t.settings.dateSeparator+"yyyy",a="hh"+t.settings.timeSeparator+"mm"+t.settings.timeMeridiemSeparator+"AA",r=e+t.settings.dateTimeSeparator+a,t.oData.sArrInputDateTimeFormats.push(r),e="MM"+t.settings.dateSeparator+"dd"+t.settings.dateSeparator+"yyyy",a="HH"+t.settings.timeSeparator+"mm",r=e+t.settings.dateTimeSeparator+a,t.oData.sArrInputDateTimeFormats.push(r),e="MM"+t.settings.dateSeparator+"dd"+t.settings.dateSeparator+"yyyy",a="hh"+t.settings.timeSeparator+"mm"+t.settings.timeMeridiemSeparator+"AA",r=e+t.settings.dateTimeSeparator+a,t.oData.sArrInputDateTimeFormats.push(r),e="yyyy"+t.settings.dateSeparator+"MM"+t.settings.dateSeparator+"dd",a="HH"+t.settings.timeSeparator+"mm",r=e+t.settings.dateTimeSeparator+a,t.oData.sArrInputDateTimeFormats.push(r),e="yyyy"+t.settings.dateSeparator+"MM"+t.settings.dateSeparator+"dd",a="hh"+t.settings.timeSeparator+"mm"+t.settings.timeMeridiemSeparator+"AA",r=e+t.settings.dateTimeSeparator+a,t.oData.sArrInputDateTimeFormats.push(r),e="dd"+t.settings.dateSeparator+"MMM"+t.settings.dateSeparator+"yyyy",a="hh"+t.settings.timeSeparator+"mm",r=e+t.settings.dateTimeSeparator+a,t.oData.sArrInputDateTimeFormats.push(r),e="dd"+t.settings.dateSeparator+"MMM"+t.settings.dateSeparator+"yyyy",a="hh"+t.settings.timeSeparator+"mm"+t.settings.timeMeridiemSeparator+"AA",r=e+t.settings.dateTimeSeparator+a,t.oData.sArrInputDateTimeFormats.push(r)},_matchFormat:function(t,e){var a=this;a.oData.bArrMatchFormat=[],a.oData.bDateMode=!1,a.oData.bTimeMode=!1,a.oData.bDateTimeMode=!1;var r,n=[];for(t=b.cf._isValid(t)?t:a.settings.mode,b.cf._compare(t,"date")?(e=b.cf._isValid(e)?e:a.oData.sDateFormat,a.oData.bDateMode=!0,n=a.oData.sArrInputDateFormats):b.cf._compare(t,"time")?(e=b.cf._isValid(e)?e:a.oData.sTimeFormat,a.oData.bTimeMode=!0,n=a.oData.sArrInputTimeFormats):b.cf._compare(t,"datetime")&&(e=b.cf._isValid(e)?e:a.oData.sDateTimeFormat,a.oData.bDateTimeMode=!0,n=a.oData.sArrInputDateTimeFormats),r=0;r<n.length;r++)a.oData.bArrMatchFormat.push(b.cf._compare(e,n[r]))},_setMatchFormat:function(t,e,a){0<t&&this._matchFormat(e,a)},_createPicker:function(){var e=this;e.settings.isInline?b(e.element).addClass("dtpicker-inline"):(b(e.element).addClass("dtpicker-overlay"),b(".dtpicker-overlay").click(function(t){e._hidePicker("")}));b(e.element).html("<div class='dtpicker-bg'><div class='dtpicker-cont'><div class='dtpicker-content'><div class='dtpicker-subcontent'></div></div></div></div>")},_addEventHandlersForInput:function(){var t=this;if(!t.settings.isInline){t.oData.oInputElement=null,b(t.settings.parentElement).find("input[type='date'], input[type='time'], input[type='datetime']").each(function(){b(this).attr("data-field",b(this).attr("type")),b(this).attr("type","text")});var e="[data-field='date'], [data-field='time'], [data-field='datetime']";b(t.settings.parentElement).off("focus",e,t._inputFieldFocus).on("focus",e,{obj:t},t._inputFieldFocus),b(t.settings.parentElement).off("click",e,t._inputFieldClick).on("click",e,{obj:t},t._inputFieldClick)}t.settings.addEventHandlers&&t.settings.addEventHandlers.call(t)},_inputFieldFocus:function(t){var e=t.data.obj;e.showDateTimePicker(this),e.oData.bMouseDown=!1},_inputFieldClick:function(t){var e=t.data.obj;b.cf._compare(b(this).prop("tagName"),"input")||e.showDateTimePicker(this),t.stopPropagation()},getDateObjectForInputField:function(t){var e=this;if(b.cf._isValid(t)){var a,r=e._getValueOfElement(t),n=b(t).data("field"),o="";return b.cf._isValid(n)||(n=e.settings.mode),e.settings.formatDateTimeString?a=e.settings.parseDateTimeString.call(e,r,n,o,b(t)):(o=b(t).data("format"),b.cf._isValid(o)||(b.cf._compare(n,"date")?o=e.settings.dateFormat:b.cf._compare(n,"time")?o=e.settings.timeFormat:b.cf._compare(n,"datetime")&&(o=e.settings.dateTimeFormat)),e._matchFormat(n,o),b.cf._compare(n,"date")?a=e._parseDate(r):b.cf._compare(n,"time")?a=e._parseTime(r):b.cf._compare(n,"datetime")&&(a=e._parseDateTime(r))),a}},setDateTimeStringInInputField:function(t,n){var e,o=this;n=n||o.oData.dCurrentDate,b.cf._isValid(t)?(e=[],"string"==typeof t?e.push(t):"object"==typeof t&&(e=t)):e=b.cf._isValid(o.settings.parentElement)?b(o.settings.parentElement).find("[data-field='date'], [data-field='time'], [data-field='datetime']"):b("[data-field='date'], [data-field='time'], [data-field='datetime']"),e.each(function(){var t,e,a,r;t=b(this).data("field"),b.cf._isValid(t)||(t=o.settings.mode),a=!(e="Custom"),o.settings.formatDateTimeString||(e=b(this).data("format"),b.cf._isValid(e)||(b.cf._compare(t,"date")?e=o.settings.dateFormat:b.cf._compare(t,"time")?e=o.settings.timeFormat:b.cf._compare(t,"datetime")&&(e=o.settings.dateTimeFormat)),a=o.getIs12Hour(t,e)),r=o._setOutput(t,e,a,n,this),o._setValueOfElement(r,b(this))})},getDateTimeStringInFormat:function(t,e,a){return this._setOutput(t,e,this.getIs12Hour(t,e),a)},showDateTimePicker:function(t){null!==this.oData.oInputElement?this.settings.isInline||this._hidePicker(0,t):this._showPicker(t)},_setButtonAction:function(t){var e=this;null!==e.oData.oInputElement&&(e._setValueOfElement(e._setOutput()),t?(e.settings.buttonClicked&&e.settings.buttonClicked.call(e,"TAB",e.oData.oInputElement),e.settings.isInline||e._hidePicker(0)):e.settings.isInline||e._hidePicker(""))},_setOutput:function(t,e,a,r,n){var o=this;r=b.cf._isValid(r)?r:o.oData.dCurrentDate,a=a||o.oData.bIs12Hour;var i,s=o._setVariablesForDate(r,!0,!0),m="",u=o._formatDate(s),c=o._formatTime(s),d=b.extend({},u,c),D="",l="",p=Function.length;return o.settings.formatDateTimeString?m=o.settings.formatDateTimeString.call(o,d,t,e,n):(o._setMatchFormat(p,t,e),o.oData.bDateMode?o.oData.bArrMatchFormat[0]?m=d.dd+o.settings.dateSeparator+d.MM+o.settings.dateSeparator+d.yyyy:o.oData.bArrMatchFormat[1]?m=d.MM+o.settings.dateSeparator+d.dd+o.settings.dateSeparator+d.yyyy:o.oData.bArrMatchFormat[2]?m=d.yyyy+o.settings.dateSeparator+d.MM+o.settings.dateSeparator+d.dd:o.oData.bArrMatchFormat[3]?m=d.dd+o.settings.dateSeparator+d.monthShort+o.settings.dateSeparator+d.yyyy:o.oData.bArrMatchFormat[4]?m=d.MM+o.settings.monthYearSeparator+d.yyyy:o.oData.bArrMatchFormat[5]?m=d.monthShort+o.settings.monthYearSeparator+d.yyyy:o.oData.bArrMatchFormat[6]?m=d.month+o.settings.monthYearSeparator+d.yyyy:o.oData.bArrMatchFormat[7]&&(m=d.yyyy+o.settings.monthYearSeparator+d.MM):o.oData.bTimeMode?o.oData.bArrMatchFormat[0]?m=d.hh+o.settings.timeSeparator+d.mm+o.settings.timeSeparator+d.ss+o.settings.timeMeridiemSeparator+d.ME:o.oData.bArrMatchFormat[1]?m=d.HH+o.settings.timeSeparator+d.mm+o.settings.timeSeparator+d.ss:o.oData.bArrMatchFormat[2]?m=d.hh+o.settings.timeSeparator+d.mm+o.settings.timeMeridiemSeparator+d.ME:o.oData.bArrMatchFormat[3]&&(m=d.HH+o.settings.timeSeparator+d.mm):o.oData.bDateTimeMode&&(o.oData.bArrMatchFormat[0]||o.oData.bArrMatchFormat[1]||o.oData.bArrMatchFormat[8]||o.oData.bArrMatchFormat[9]?D=d.dd+o.settings.dateSeparator+d.MM+o.settings.dateSeparator+d.yyyy:o.oData.bArrMatchFormat[2]||o.oData.bArrMatchFormat[3]||o.oData.bArrMatchFormat[10]||o.oData.bArrMatchFormat[11]?D=d.MM+o.settings.dateSeparator+d.dd+o.settings.dateSeparator+d.yyyy:o.oData.bArrMatchFormat[4]||o.oData.bArrMatchFormat[5]||o.oData.bArrMatchFormat[12]||o.oData.bArrMatchFormat[13]?D=d.yyyy+o.settings.dateSeparator+d.MM+o.settings.dateSeparator+d.dd:(o.oData.bArrMatchFormat[6]||o.oData.bArrMatchFormat[7]||o.oData.bArrMatchFormat[14]||o.oData.bArrMatchFormat[15])&&(D=d.dd+o.settings.dateSeparator+d.monthShort+o.settings.dateSeparator+d.yyyy),i=o.oData.bArrMatchFormat[0]||o.oData.bArrMatchFormat[1]||o.oData.bArrMatchFormat[2]||o.oData.bArrMatchFormat[3]||o.oData.bArrMatchFormat[4]||o.oData.bArrMatchFormat[5]||o.oData.bArrMatchFormat[6]||o.oData.bArrMatchFormat[7],l=a?i?d.hh+o.settings.timeSeparator+d.mm+o.settings.timeSeparator+d.ss+o.settings.timeMeridiemSeparator+d.ME:d.hh+o.settings.timeSeparator+d.mm+o.settings.timeMeridiemSeparator+d.ME:i?d.HH+o.settings.timeSeparator+d.mm+o.settings.timeSeparator+d.ss:d.HH+o.settings.timeSeparator+d.mm,""!==D&&""!==l&&(m=D+o.settings.dateTimeSeparator+l)),o._setMatchFormat(p)),m},_clearButtonAction:function(){null!==this.oData.oInputElement&&this._setValueOfElement(""),this.settings.isInline||this._hidePicker("")},_setOutputOnIncrementOrDecrement:function(){b.cf._isValid(this.oData.oInputElement)&&this.settings.setValueInTextboxOnEveryClick&&this._setValueOfElement(this._setOutput())},_showPicker:function(t){var e=this;if(null===e.oData.oInputElement){e.oData.oInputElement=t,e.oData.iTabIndex=parseInt(b(t).attr("tabIndex"));var a,r,n,o,i,s,m,u,c=b(t).data("field")||"",d=b(t).data("min")||"",D=b(t).data("max")||"",l=b(t).data("format")||"",p=b(t).data("view")||"",h=b(t).data("startend")||"",M=b(t).data("startendelem")||"",g=e._getValueOfElement(t)||"";if(""!==p&&(b.cf._compare(p,"Popup")?e.setIsPopup(!0):e.setIsPopup(!1)),!e.settings.isPopup&&!e.settings.isInline){e._createPicker();var f=b(e.oData.oInputElement).offset().top+b(e.oData.oInputElement).outerHeight(),C=b(e.oData.oInputElement).offset().left,y=b(e.oData.oInputElement).outerWidth();b(e.element).css({position:"absolute",top:f,left:C,width:y,height:"auto"})}e.settings.beforeShow&&e.settings.beforeShow.call(e,t),c=b.cf._isValid(c)?c:e.settings.mode,e.settings.mode=c,b.cf._isValid(l)||(b.cf._compare(c,"date")?l=e.settings.dateFormat:b.cf._compare(c,"time")?l=e.settings.timeFormat:b.cf._compare(c,"datetime")&&(l=e.settings.dateTimeFormat)),e._matchFormat(c,l),e.oData.dMinValue=null,e.oData.dMaxValue=null,e.oData.bIs12Hour=!1,e.oData.bDateMode?(a=d||e.settings.minDate,r=D||e.settings.maxDate,e.oData.sDateFormat=l,b.cf._isValid(a)&&(e.oData.dMinValue=e._parseDate(a)),b.cf._isValid(r)&&(e.oData.dMaxValue=e._parseDate(r)),""!==h&&(b.cf._compare(h,"start")||b.cf._compare(h,"end"))&&""!==M&&1<=b(M).length&&""!==(n=e._getValueOfElement(b(M)))&&(o=e.settings.parseDateTimeString?e.settings.parseDateTimeString.call(e,n,c,l,b(M)):e._parseDate(n),b.cf._compare(h,"start")?b.cf._isValid(r)?e._compareDates(o,e.oData.dMaxValue)<0&&(e.oData.dMaxValue=new Date(o)):e.oData.dMaxValue=new Date(o):b.cf._compare(h,"end")&&(b.cf._isValid(a)?0<e._compareDates(o,e.oData.dMinValue)&&(e.oData.dMinValue=new Date(o)):e.oData.dMinValue=new Date(o))),e.settings.parseDateTimeString?e.oData.dCurrentDate=e.settings.parseDateTimeString.call(e,g,c,l,b(t)):e.oData.dCurrentDate=e._parseDate(g),e.oData.dCurrentDate.setHours(0),e.oData.dCurrentDate.setMinutes(0),e.oData.dCurrentDate.setSeconds(0)):e.oData.bTimeMode?(a=d||e.settings.minTime,r=D||e.settings.maxTime,e.oData.sTimeFormat=l,e.oData.bIs12Hour=e.getIs12Hour(),b.cf._isValid(a)&&(e.oData.dMinValue=e._parseTime(a),b.cf._isValid(r)||(e.oData.sTimeFormat===e.oData.sArrInputTimeFormats[0]?r="11:59:59 PM":e.oData.sTimeFormat===e.oData.sArrInputTimeFormats[1]?r="23:59:59":e.oData.sTimeFormat===e.oData.sArrInputTimeFormats[2]?r="11:59 PM":e.oData.sTimeFormat===e.oData.sArrInputTimeFormats[3]&&(r="23:59"),e.oData.dMaxValue=e._parseTime(r))),b.cf._isValid(r)&&(e.oData.dMaxValue=e._parseTime(r),b.cf._isValid(a)||(e.oData.sTimeFormat===e.oData.sArrInputTimeFormats[0]?a="12:00:00 AM":e.oData.sTimeFormat===e.oData.sArrInputTimeFormats[1]?a="00:00:00":e.oData.sTimeFormat===e.oData.sArrInputTimeFormats[2]?a="12:00 AM":e.oData.sTimeFormat===e.oData.sArrInputTimeFormats[3]&&(a="00:00"),e.oData.dMinValue=e._parseTime(a))),""!==h&&(b.cf._compare(h,"start")||b.cf._compare(h,"end"))&&""!==M&&1<=b(M).length&&""!==(i=e._getValueOfElement(b(M)))&&(e.settings.parseDateTimeString?o=e.settings.parseDateTimeString.call(e,i,c,l,b(M)):s=e._parseTime(i),b.cf._compare(h,"start")?(s.setMinutes(s.getMinutes()-1),b.cf._isValid(r)?2===e._compareTime(s,e.oData.dMaxValue)&&(e.oData.dMaxValue=new Date(s)):e.oData.dMaxValue=new Date(s)):b.cf._compare(h,"end")&&(s.setMinutes(s.getMinutes()+1),b.cf._isValid(a)?3===e._compareTime(s,e.oData.dMinValue)&&(e.oData.dMinValue=new Date(s)):e.oData.dMinValue=new Date(s))),e.settings.parseDateTimeString?e.oData.dCurrentDate=e.settings.parseDateTimeString.call(e,g,c,l,b(t)):e.oData.dCurrentDate=e._parseTime(g)):e.oData.bDateTimeMode&&(a=d||e.settings.minDateTime,r=D||e.settings.maxDateTime,e.oData.sDateTimeFormat=l,e.oData.bIs12Hour=e.getIs12Hour(),b.cf._isValid(a)&&(e.oData.dMinValue=e._parseDateTime(a)),b.cf._isValid(r)&&(e.oData.dMaxValue=e._parseDateTime(r)),""!==h&&(b.cf._compare(h,"start")||b.cf._compare(h,"end"))&&""!==M&&1<=b(M).length&&""!==(m=e._getValueOfElement(b(M)))&&(u=e.settings.parseDateTimeString?e.settings.parseDateTimeString.call(e,m,c,l,b(M)):e._parseDateTime(m),b.cf._compare(h,"start")?b.cf._isValid(r)?e._compareDateTime(u,e.oData.dMaxValue)<0&&(e.oData.dMaxValue=new Date(u)):e.oData.dMaxValue=new Date(u):b.cf._compare(h,"end")&&(b.cf._isValid(a)?0<e._compareDateTime(u,e.oData.dMinValue)&&(e.oData.dMinValue=new Date(u)):e.oData.dMinValue=new Date(u))),e.settings.parseDateTimeString?e.oData.dCurrentDate=e.settings.parseDateTimeString.call(e,g,c,l,b(t)):e.oData.dCurrentDate=e._parseDateTime(g)),e._setVariablesForDate(),e._modifyPicker(),b(e.element).fadeIn(e.settings.animationDuration),e.settings.afterShow&&setTimeout(function(){e.settings.afterShow.call(e,t)},e.settings.animationDuration)}},_hidePicker:function(t,e){var a=this,r=a.oData.oInputElement;a.settings.beforeHide&&a.settings.beforeHide.call(a,r),b.cf._isValid(t)||(t=a.settings.animationDuration),b.cf._isValid(a.oData.oInputElement)&&(b(a.oData.oInputElement).blur(),a.oData.oInputElement=null),b(a.element).fadeOut(t),0===t?b(a.element).find(".dtpicker-subcontent").html(""):setTimeout(function(){b(a.element).find(".dtpicker-subcontent").html("")},t),b(document).unbind("click.DateTimePicker keydown.DateTimePicker keyup.DateTimePicker"),a.settings.afterHide&&(0===t?a.settings.afterHide.call(a,r):setTimeout(function(){a.settings.afterHide.call(a,r)},t)),b.cf._isValid(e)&&a._showPicker(e)},_modifyPicker:function(){var t,e,a=this,r=[];a.oData.bDateMode?(t=a.settings.titleContentDate,e=3,a.oData.bArrMatchFormat[0]?r=["day","month","year"]:a.oData.bArrMatchFormat[1]?r=["month","day","year"]:a.oData.bArrMatchFormat[2]?r=["year","month","day"]:a.oData.bArrMatchFormat[3]?r=["day","month","year"]:a.oData.bArrMatchFormat[4]?(e=2,r=["month","year"]):a.oData.bArrMatchFormat[5]?(e=2,r=["month","year"]):a.oData.bArrMatchFormat[6]?(e=2,r=["month","year"]):a.oData.bArrMatchFormat[7]&&(e=2,r=["year","month"])):a.oData.bTimeMode?(t=a.settings.titleContentTime,a.oData.bArrMatchFormat[0]?(e=4,r=["hour","minutes","seconds","meridiem"]):a.oData.bArrMatchFormat[1]?(e=3,r=["hour","minutes","seconds"]):a.oData.bArrMatchFormat[2]?(e=3,r=["hour","minutes","meridiem"]):a.oData.bArrMatchFormat[3]&&(e=2,r=["hour","minutes"])):a.oData.bDateTimeMode&&(t=a.settings.titleContentDateTime,a.oData.bArrMatchFormat[0]?(e=6,r=["day","month","year","hour","minutes","seconds"]):a.oData.bArrMatchFormat[1]?(e=7,r=["day","month","year","hour","minutes","seconds","meridiem"]):a.oData.bArrMatchFormat[2]?(e=6,r=["month","day","year","hour","minutes","seconds"]):a.oData.bArrMatchFormat[3]?(e=7,r=["month","day","year","hour","minutes","seconds","meridiem"]):a.oData.bArrMatchFormat[4]?(e=6,r=["year","month","day","hour","minutes","seconds"]):a.oData.bArrMatchFormat[5]?(e=7,r=["year","month","day","hour","minutes","seconds","meridiem"]):a.oData.bArrMatchFormat[6]?(e=6,r=["day","month","year","hour","minutes","seconds"]):a.oData.bArrMatchFormat[7]?(e=7,r=["day","month","year","hour","minutes","seconds","meridiem"]):a.oData.bArrMatchFormat[8]?(e=5,r=["day","month","year","hour","minutes"]):a.oData.bArrMatchFormat[9]?(e=6,r=["day","month","year","hour","minutes","meridiem"]):a.oData.bArrMatchFormat[10]?(e=5,r=["month","day","year","hour","minutes"]):a.oData.bArrMatchFormat[11]?(e=6,r=["month","day","year","hour","minutes","meridiem"]):a.oData.bArrMatchFormat[12]?(e=5,r=["year","month","day","hour","minutes"]):a.oData.bArrMatchFormat[13]?(e=6,r=["year","month","day","hour","minutes","meridiem"]):a.oData.bArrMatchFormat[14]?(e=5,r=["day","month","year","hour","minutes"]):a.oData.bArrMatchFormat[15]&&(e=6,r=["day","month","year","hour","minutes","meridiem"]));var n,o="dtpicker-comp"+e,i=!1,s=!1,m=!1;for(n=0;n<a.settings.buttonsToDisplay.length;n++)b.cf._compare(a.settings.buttonsToDisplay[n],"HeaderCloseButton")?i=!0:b.cf._compare(a.settings.buttonsToDisplay[n],"SetButton")?s=!0:b.cf._compare(a.settings.buttonsToDisplay[n],"ClearButton")&&(m=!0);var u="";a.settings.showHeader&&(u+="<div class='dtpicker-header'>",u+="<div class='dtpicker-title'>"+t+"</div>",i&&(u+="<a class='dtpicker-close'>&times;</a>"),u+="<div class='dtpicker-value'></div>",u+="</div>");var c="";for(c+="<div class='dtpicker-components'>",n=0;n<e;n++){var d=r[n];c+="<div class='dtpicker-compOutline "+o+"'>",c+="<div class='dtpicker-comp "+d+"'>",c+="<a class='dtpicker-compButton increment'>"+a.settings.incrementButtonContent+"</a>",a.settings.readonlyInputs?c+="<input type='text' class='dtpicker-compValue' readonly>":c+="<input type='text' class='dtpicker-compValue'>",c+="<a class='dtpicker-compButton decrement'>"+a.settings.decrementButtonContent+"</a>",a.settings.labels&&(c+="<div class='dtpicker-label'>"+a.settings.labels[d]+"</div>"),c+="</div>",c+="</div>"}c+="</div>";var D="";D+="<div class='dtpicker-buttonCont"+(s&&m?" dtpicker-twoButtons":" dtpicker-singleButton")+"'>",s&&(D+="<a class='dtpicker-button dtpicker-buttonSet'>"+a.settings.setButtonContent+"</a>"),m&&(D+="<a class='dtpicker-button dtpicker-buttonClear'>"+a.settings.clearButtonContent+"</a>");var l=u+c+(D+="</div>");b(a.element).find(".dtpicker-subcontent").html(l),a._setCurrentDate(),a._addEventHandlersForPicker()},_addEventHandlersForPicker:function(){var e,a,r=this;if(r.settings.isInline||b(document).on("click.DateTimePicker",function(t){r.oData.bElemFocused&&r._hidePicker("")}),b(document).on("keydown.DateTimePicker",function(t){if(a=parseInt(t.keyCode?t.keyCode:t.which),!b(".dtpicker-compValue").is(":focus")&&9===a)return r._setButtonAction(!0),b("[tabIndex="+(r.oData.iTabIndex+1)+"]").focus(),!1;if(b(".dtpicker-compValue").is(":focus")){if(38===a)return e=b(".dtpicker-compValue:focus").parent().attr("class"),r._incrementDecrementActionsUsingArrowAndMouse(e,"inc"),!1;if(40===a)return e=b(".dtpicker-compValue:focus").parent().attr("class"),r._incrementDecrementActionsUsingArrowAndMouse(e,"dec"),!1}}),r.settings.isInline||b(document).on("keydown.DateTimePicker",function(t){a=parseInt(t.keyCode?t.keyCode:t.which),b(".dtpicker-compValue").is(":focus")||9===a||r._hidePicker("")}),b(".dtpicker-cont *").click(function(t){t.stopPropagation()}),r.settings.readonlyInputs||(b(".dtpicker-compValue").not(".month .dtpicker-compValue, .meridiem .dtpicker-compValue").keyup(function(){this.value=this.value.replace(/[^0-9\.]/g,"")}),b(".dtpicker-compValue").focus(function(){r.oData.bElemFocused=!0,b(this).select()}),b(".dtpicker-compValue").blur(function(){r._getValuesFromInputBoxes(),r._setCurrentDate(),r.oData.bElemFocused=!1;var t=b(this).parent().parent();setTimeout(function(){t.is(":last-child")&&!r.oData.bElemFocused&&r._setButtonAction(!1)},50)}),b(".dtpicker-compValue").keyup(function(t){var e,a=b(this),r=a.val(),n=r.length;a.parent().hasClass("day")||a.parent().hasClass("hour")||a.parent().hasClass("minutes")||a.parent().hasClass("meridiem")?2<n&&(e=r.slice(0,2),a.val(e)):a.parent().hasClass("month")?3<n&&(e=r.slice(0,3),a.val(e)):a.parent().hasClass("year")&&4<n&&(e=r.slice(0,4),a.val(e)),9===parseInt(t.keyCode?t.keyCode:t.which)&&b(this).select()})),b(r.element).find(".dtpicker-compValue").on("mousewheel DOMMouseScroll onmousewheel",function(t){if(b(".dtpicker-compValue").is(":focus"))return 0<Math.max(-1,Math.min(1,t.originalEvent.wheelDelta))?(e=b(".dtpicker-compValue:focus").parent().attr("class"),r._incrementDecrementActionsUsingArrowAndMouse(e,"inc")):(e=b(".dtpicker-compValue:focus").parent().attr("class"),r._incrementDecrementActionsUsingArrowAndMouse(e,"dec")),!1}),b(r.element).find(".dtpicker-close").click(function(t){r.settings.buttonClicked&&r.settings.buttonClicked.call(r,"CLOSE",r.oData.oInputElement),r.settings.isInline||r._hidePicker("")}),b(r.element).find(".dtpicker-buttonSet").click(function(t){r.settings.buttonClicked&&r.settings.buttonClicked.call(r,"SET",r.oData.oInputElement),r._setButtonAction(!1)}),b(r.element).find(".dtpicker-buttonClear").click(function(t){r.settings.buttonClicked&&r.settings.buttonClicked.call(r,"CLEAR",r.oData.oInputElement),r._clearButtonAction()}),r.settings.captureTouchHold||r.settings.captureMouseHold){var t="";r.settings.captureTouchHold&&r.oData.bIsTouchDevice&&(t+="touchstart touchmove touchend "),r.settings.captureMouseHold&&(t+="mousedown mouseup"),b(".dtpicker-cont *").on(t,function(t){r._clearIntervalForTouchEvents()}),r._bindTouchEvents("day"),r._bindTouchEvents("month"),r._bindTouchEvents("year"),r._bindTouchEvents("hour"),r._bindTouchEvents("minutes"),r._bindTouchEvents("seconds")}else b(r.element).find(".day .increment, .day .increment *").click(function(t){r.oData.iCurrentDay++,r._setCurrentDate(),r._setOutputOnIncrementOrDecrement()}),b(r.element).find(".day .decrement, .day .decrement *").click(function(t){r.oData.iCurrentDay--,r._setCurrentDate(),r._setOutputOnIncrementOrDecrement()}),b(r.element).find(".month .increment, .month .increment *").click(function(t){r.oData.iCurrentMonth++,r._setCurrentDate(),r._setOutputOnIncrementOrDecrement()}),b(r.element).find(".month .decrement, .month .decrement *").click(function(t){r.oData.iCurrentMonth--,r._setCurrentDate(),r._setOutputOnIncrementOrDecrement()}),b(r.element).find(".year .increment, .year .increment *").click(function(t){r.oData.iCurrentYear++,r._setCurrentDate(),r._setOutputOnIncrementOrDecrement()}),b(r.element).find(".year .decrement, .year .decrement *").click(function(t){r.oData.iCurrentYear--,r._setCurrentDate(),r._setOutputOnIncrementOrDecrement()}),b(r.element).find(".hour .increment, .hour .increment *").click(function(t){r.oData.iCurrentHour++,r._setCurrentDate(),r._setOutputOnIncrementOrDecrement()}),b(r.element).find(".hour .decrement, .hour .decrement *").click(function(t){r.oData.iCurrentHour--,r._setCurrentDate(),r._setOutputOnIncrementOrDecrement()}),b(r.element).find(".minutes .increment, .minutes .increment *").click(function(t){r.oData.iCurrentMinutes+=r.settings.minuteInterval,r._setCurrentDate(),r._setOutputOnIncrementOrDecrement()}),b(r.element).find(".minutes .decrement, .minutes .decrement *").click(function(t){r.oData.iCurrentMinutes-=r.settings.minuteInterval,r._setCurrentDate(),r._setOutputOnIncrementOrDecrement()}),b(r.element).find(".seconds .increment, .seconds .increment *").click(function(t){r.oData.iCurrentSeconds+=r.settings.secondsInterval,r._setCurrentDate(),r._setOutputOnIncrementOrDecrement()}),b(r.element).find(".seconds .decrement, .seconds .decrement *").click(function(t){r.oData.iCurrentSeconds-=r.settings.secondsInterval,r._setCurrentDate(),r._setOutputOnIncrementOrDecrement()});b(r.element).find(".meridiem .dtpicker-compButton, .meridiem .dtpicker-compButton *").click(function(t){b.cf._compare(r.oData.sCurrentMeridiem,"AM")?(r.oData.sCurrentMeridiem="PM",r.oData.iCurrentHour+=12):b.cf._compare(r.oData.sCurrentMeridiem,"PM")&&(r.oData.sCurrentMeridiem="AM",r.oData.iCurrentHour-=12),r._setCurrentDate(),r._setOutputOnIncrementOrDecrement()})},_adjustMinutes:function(t){var e=this;return e.settings.roundOffMinutes&&1!==e.settings.minuteInterval&&(t=t%e.settings.minuteInterval?t-t%e.settings.minuteInterval+e.settings.minuteInterval:t),t},_adjustSeconds:function(t){var e=this;return e.settings.roundOffSeconds&&1!==e.settings.secondsInterval&&(t=t%e.settings.secondsInterval?t-t%e.settings.secondsInterval+e.settings.secondsInterval:t),t},_getValueOfElement:function(t){return b.cf._compare(b(t).prop("tagName"),"INPUT")?b(t).val():b(t).html()},_setValueOfElement:function(t,e){var a=this;b.cf._isValid(e)||(e=b(a.oData.oInputElement)),b.cf._compare(e.prop("tagName"),"INPUT")?e.val(t):e.html(t);var r=a.getDateObjectForInputField(e);return a.settings.settingValueOfElement&&a.settings.settingValueOfElement.call(a,t,r,e),e.change(),t},_bindTouchEvents:function(e){var a=this;b(a.element).find("."+e+" .increment, ."+e+" .increment *").on("touchstart mousedown",function(t){t.stopPropagation(),b.cf._isValid(a.oData.sTouchButton)||(a.oData.iTouchStart=(new Date).getTime(),a.oData.sTouchButton=e+"-inc",a._setIntervalForTouchEvents())}),b(a.element).find("."+e+" .increment, ."+e+" .increment *").on("touchend mouseup",function(t){t.stopPropagation(),a._clearIntervalForTouchEvents()}),b(a.element).find("."+e+" .decrement, ."+e+" .decrement *").on("touchstart mousedown",function(t){t.stopPropagation(),b.cf._isValid(a.oData.sTouchButton)||(a.oData.iTouchStart=(new Date).getTime(),a.oData.sTouchButton=e+"-dec",a._setIntervalForTouchEvents())}),b(a.element).find("."+e+" .decrement, ."+e+" .decrement *").on("touchend mouseup",function(t){t.stopPropagation(),a._clearIntervalForTouchEvents()})},_setIntervalForTouchEvents:function(){var t,e=this,a=e.oData.bIsTouchDevice?e.settings.touchHoldInterval:e.settings.mouseHoldInterval;b.cf._isValid(e.oData.oTimeInterval)||(e.oData.oTimeInterval=setInterval(function(){t=(new Date).getTime()-e.oData.iTouchStart,a<t&&b.cf._isValid(e.oData.sTouchButton)&&("day-inc"===e.oData.sTouchButton?e.oData.iCurrentDay++:"day-dec"===e.oData.sTouchButton?e.oData.iCurrentDay--:"month-inc"===e.oData.sTouchButton?e.oData.iCurrentMonth++:"month-dec"===e.oData.sTouchButton?e.oData.iCurrentMonth--:"year-inc"===e.oData.sTouchButton?e.oData.iCurrentYear++:"year-dec"===e.oData.sTouchButton?e.oData.iCurrentYear--:"hour-inc"===e.oData.sTouchButton?e.oData.iCurrentHour++:"hour-dec"===e.oData.sTouchButton?e.oData.iCurrentHour--:"minute-inc"===e.oData.sTouchButton?e.oData.iCurrentMinutes+=e.settings.minuteInterval:"minute-dec"===e.oData.sTouchButton?e.oData.iCurrentMinutes-=e.settings.minuteInterval:"second-inc"===e.oData.sTouchButton?e.oData.iCurrentSeconds+=e.settings.secondsInterval:"second-dec"===e.oData.sTouchButton&&(e.oData.iCurrentSeconds-=e.settings.secondsInterval),e._setCurrentDate(),e._setOutputOnIncrementOrDecrement(),e.oData.iTouchStart=(new Date).getTime())},a))},_clearIntervalForTouchEvents:function(){var t=this;clearInterval(t.oData.oTimeInterval),b.cf._isValid(t.oData.sTouchButton)&&(t.oData.sTouchButton=null,t.oData.iTouchStart=0),t.oData.oTimeInterval=null},_incrementDecrementActionsUsingArrowAndMouse:function(t,e){var a=this;t.includes("day")?"inc"===e?a.oData.iCurrentDay++:"dec"===e&&a.oData.iCurrentDay--:t.includes("month")?"inc"===e?a.oData.iCurrentMonth++:"dec"===e&&a.oData.iCurrentMonth--:t.includes("year")?"inc"===e?a.oData.iCurrentYear++:"dec"===e&&a.oData.iCurrentYear--:t.includes("hour")?"inc"===e?a.oData.iCurrentHour++:"dec"===e&&a.oData.iCurrentHour--:t.includes("minutes")?"inc"===e?a.oData.iCurrentMinutes+=a.settings.minuteInterval:"dec"===e&&(a.oData.iCurrentMinutes-=a.settings.minuteInterval):t.includes("seconds")&&("inc"===e?a.oData.iCurrentSeconds+=a.settings.secondsInterval:"dec"===e&&(a.oData.iCurrentSeconds-=a.settings.secondsInterval)),a._setCurrentDate(),a._setOutputOnIncrementOrDecrement()},_parseDate:function(t){var e,a=this,r=a.settings.defaultDate?new Date(a.settings.defaultDate):new Date,n=r.getDate(),o=r.getMonth(),i=r.getFullYear();b.cf._isValid(t)&&("string"==typeof t?(e=a.oData.bArrMatchFormat[4]||a.oData.bArrMatchFormat[5]||a.oData.bArrMatchFormat[6]?t.split(a.settings.monthYearSeparator):t.split(a.settings.dateSeparator),a.oData.bArrMatchFormat[0]?(n=parseInt(e[0]),o=parseInt(e[1]-1),i=parseInt(e[2])):a.oData.bArrMatchFormat[1]?(o=parseInt(e[0]-1),n=parseInt(e[1]),i=parseInt(e[2])):a.oData.bArrMatchFormat[2]?(i=parseInt(e[0]),o=parseInt(e[1]-1),n=parseInt(e[2])):a.oData.bArrMatchFormat[3]?(n=parseInt(e[0]),o=a._getShortMonthIndex(e[1]),i=parseInt(e[2])):a.oData.bArrMatchFormat[4]?(n=1,o=parseInt(e[0])-1,i=parseInt(e[1])):a.oData.bArrMatchFormat[5]?(n=1,o=a._getShortMonthIndex(e[0]),i=parseInt(e[1])):a.oData.bArrMatchFormat[6]?(n=1,o=a._getFullMonthIndex(e[0]),i=parseInt(e[1])):a.oData.bArrMatchFormat[7]&&(n=1,o=parseInt(e[1])-1,i=parseInt(e[0]))):(n=t.getDate(),o=t.getMonth(),i=t.getFullYear()));return r=new Date(i,o,n,0,0,0,0)},_parseTime:function(t){var e,a,r,n=this,o=n.settings.defaultDate?new Date(n.settings.defaultDate):new Date,i=o.getDate(),s=o.getMonth(),m=o.getFullYear(),u=o.getHours(),c=o.getMinutes(),d=o.getSeconds(),D=n.oData.bArrMatchFormat[0]||n.oData.bArrMatchFormat[1];return d=D?n._adjustSeconds(d):0,b.cf._isValid(t)&&("string"==typeof t?(n.oData.bIs12Hour&&(t=(e=t.split(n.settings.timeMeridiemSeparator))[0],a=e[1],b.cf._compare(a,"AM")||b.cf._compare(a,"PM")||(a="")),r=t.split(n.settings.timeSeparator),u=parseInt(r[0]),c=parseInt(r[1]),D&&(d=parseInt(r[2]),d=n._adjustSeconds(d)),12===u&&b.cf._compare(a,"AM")?u=0:u<12&&b.cf._compare(a,"PM")&&(u+=12)):(u=t.getHours(),c=t.getMinutes(),D&&(d=t.getSeconds(),d=n._adjustSeconds(d)))),c=n._adjustMinutes(c),o=new Date(m,s,i,u,c,d,0)},_parseDateTime:function(t){var e,a,r,n,o,i=this,s=i.settings.defaultDate?new Date(i.settings.defaultDate):new Date,m=s.getDate(),u=s.getMonth(),c=s.getFullYear(),d=s.getHours(),D=s.getMinutes(),l=s.getSeconds(),p="",h=i.oData.bArrMatchFormat[0]||i.oData.bArrMatchFormat[1]||i.oData.bArrMatchFormat[2]||i.oData.bArrMatchFormat[3]||i.oData.bArrMatchFormat[4]||i.oData.bArrMatchFormat[5]||i.oData.bArrMatchFormat[6]||i.oData.bArrMatchFormat[7];return l=h?i._adjustSeconds(l):0,b.cf._isValid(t)&&("string"==typeof t?(a=(e=t.split(i.settings.dateTimeSeparator))[0].split(i.settings.dateSeparator),i.oData.bArrMatchFormat[0]||i.oData.bArrMatchFormat[1]||i.oData.bArrMatchFormat[8]||i.oData.bArrMatchFormat[9]?(m=parseInt(a[0]),u=parseInt(a[1]-1),c=parseInt(a[2])):i.oData.bArrMatchFormat[2]||i.oData.bArrMatchFormat[3]||i.oData.bArrMatchFormat[10]||i.oData.bArrMatchFormat[11]?(u=parseInt(a[0]-1),m=parseInt(a[1]),c=parseInt(a[2])):i.oData.bArrMatchFormat[4]||i.oData.bArrMatchFormat[5]||i.oData.bArrMatchFormat[12]||i.oData.bArrMatchFormat[13]?(c=parseInt(a[0]),u=parseInt(a[1]-1),m=parseInt(a[2])):(i.oData.bArrMatchFormat[6]||i.oData.bArrMatchFormat[7]||i.oData.bArrMatchFormat[14]||i.oData.bArrMatchFormat[15])&&(m=parseInt(a[0]),u=i._getShortMonthIndex(a[1]),c=parseInt(a[2])),r=e[1],b.cf._isValid(r)&&(i.oData.bIs12Hour&&(p=b.cf._compare(i.settings.dateTimeSeparator,i.settings.timeMeridiemSeparator)&&3===e.length?e[2]:(r=(n=r.split(i.settings.timeMeridiemSeparator))[0],n[1]),b.cf._compare(p,"AM")||b.cf._compare(p,"PM")||(p="")),o=r.split(i.settings.timeSeparator),d=parseInt(o[0]),D=parseInt(o[1]),h&&(l=parseInt(o[2])),12===d&&b.cf._compare(p,"AM")?d=0:d<12&&b.cf._compare(p,"PM")&&(d+=12))):(m=t.getDate(),u=t.getMonth(),c=t.getFullYear(),d=t.getHours(),D=t.getMinutes(),h&&(l=t.getSeconds(),l=i._adjustSeconds(l)))),D=i._adjustMinutes(D),s=new Date(c,u,m,d,D,l,0)},_getShortMonthIndex:function(t){for(var e=0;e<this.settings.shortMonthNames.length;e++)if(b.cf._compare(t,this.settings.shortMonthNames[e]))return e},_getFullMonthIndex:function(t){for(var e=0;e<this.settings.fullMonthNames.length;e++)if(b.cf._compare(t,this.settings.fullMonthNames[e]))return e},getIs12Hour:function(t,e){var a=this,r=!1,n=Function.length;return a._setMatchFormat(n,t,e),a.oData.bTimeMode?r=a.oData.bArrMatchFormat[0]||a.oData.bArrMatchFormat[2]:a.oData.bDateTimeMode&&(r=a.oData.bArrMatchFormat[1]||a.oData.bArrMatchFormat[3]||a.oData.bArrMatchFormat[5]||a.oData.bArrMatchFormat[7]||a.oData.bArrMatchFormat[9]||a.oData.bArrMatchFormat[11]||a.oData.bArrMatchFormat[13]||a.oData.bArrMatchFormat[15]),a._setMatchFormat(n),r},_setVariablesForDate:function(t,e,a){var r,n=this,o={},i=b.cf._isValid(t);if(i?(r=new Date(t),b.cf._isValid(e)||(e=!0),b.cf._isValid(a)||(a=!0)):(r="[object Date]"===Object.prototype.toString.call(n.oData.dCurrentDate)&&isFinite(n.oData.dCurrentDate)?new Date(n.oData.dCurrentDate):new Date,b.cf._isValid(e)||(e=n.oData.bTimeMode||n.oData.bDateTimeMode),b.cf._isValid(a)||(a=n.oData.bIs12Hour)),o.iCurrentDay=r.getDate(),o.iCurrentMonth=r.getMonth(),o.iCurrentYear=r.getFullYear(),o.iCurrentWeekday=r.getDay(),e&&(o.iCurrentHour=r.getHours(),o.iCurrentMinutes=r.getMinutes(),o.iCurrentSeconds=r.getSeconds(),a&&(o.sCurrentMeridiem=n._determineMeridiemFromHourAndMinutes(o.iCurrentHour,o.iCurrentMinutes))),i)return o;n.oData=b.extend(n.oData,o)},_getValuesFromInputBoxes:function(){var t,e,a,r,n,o,i=this;(i.oData.bDateMode||i.oData.bDateTimeMode)&&(1<(t=b(i.element).find(".month .dtpicker-compValue").val()).length&&(t=t.charAt(0).toUpperCase()+t.slice(1)),-1!==(e=i.settings.shortMonthNames.indexOf(t))?i.oData.iCurrentMonth=parseInt(e):t.match("^[+|-]?[0-9]+$")&&(i.oData.iCurrentMonth=parseInt(t-1)),i.oData.iCurrentDay=parseInt(b(i.element).find(".day .dtpicker-compValue").val())||i.oData.iCurrentDay,i.oData.iCurrentYear=parseInt(b(i.element).find(".year .dtpicker-compValue").val())||i.oData.iCurrentYear);(i.oData.bTimeMode||i.oData.bDateTimeMode)&&(a=parseInt(b(i.element).find(".hour .dtpicker-compValue").val()),r=i._adjustMinutes(parseInt(b(i.element).find(".minutes .dtpicker-compValue").val())),n=i._adjustMinutes(parseInt(b(i.element).find(".seconds .dtpicker-compValue").val())),i.oData.iCurrentHour=isNaN(a)?i.oData.iCurrentHour:a,i.oData.iCurrentMinutes=isNaN(r)?i.oData.iCurrentMinutes:r,i.oData.iCurrentSeconds=isNaN(n)?i.oData.iCurrentSeconds:n,59<i.oData.iCurrentSeconds&&(i.oData.iCurrentMinutes+=i.oData.iCurrentSeconds/60,i.oData.iCurrentSeconds=i.oData.iCurrentSeconds%60),59<i.oData.iCurrentMinutes&&(i.oData.iCurrentHour+=i.oData.iCurrentMinutes/60,i.oData.iCurrentMinutes=i.oData.iCurrentMinutes%60),i.oData.bIs12Hour?12<i.oData.iCurrentHour&&(i.oData.iCurrentHour=i.oData.iCurrentHour%12):23<i.oData.iCurrentHour&&(i.oData.iCurrentHour=i.oData.iCurrentHour%23),i.oData.bIs12Hour&&(o=b(i.element).find(".meridiem .dtpicker-compValue").val(),(b.cf._compare(o,"AM")||b.cf._compare(o,"PM"))&&(i.oData.sCurrentMeridiem=o),b.cf._compare(i.oData.sCurrentMeridiem,"PM")&&12!==i.oData.iCurrentHour&&i.oData.iCurrentHour<13&&(i.oData.iCurrentHour+=12),b.cf._compare(i.oData.sCurrentMeridiem,"AM")&&12===i.oData.iCurrentHour&&(i.oData.iCurrentHour=0)))},_setCurrentDate:function(){var t=this;(t.oData.bTimeMode||t.oData.bDateTimeMode)&&(59<t.oData.iCurrentSeconds?(t.oData.iCurrentMinutes+=t.oData.iCurrentSeconds/60,t.oData.iCurrentSeconds=t.oData.iCurrentSeconds%60):t.oData.iCurrentSeconds<0&&(t.oData.iCurrentMinutes-=t.settings.minuteInterval,t.oData.iCurrentSeconds+=60),t.oData.iCurrentMinutes=t._adjustMinutes(t.oData.iCurrentMinutes),t.oData.iCurrentSeconds=t._adjustSeconds(t.oData.iCurrentSeconds));var e,a,r,n,o,i,s,m=new Date(t.oData.iCurrentYear,t.oData.iCurrentMonth,t.oData.iCurrentDay,t.oData.iCurrentHour,t.oData.iCurrentMinutes,t.oData.iCurrentSeconds,0),u=!1,c=!1;if(null!==t.oData.dMaxValue&&(u=m.getTime()>t.oData.dMaxValue.getTime()),null!==t.oData.dMinValue&&(c=m.getTime()<t.oData.dMinValue.getTime()),u||c){var d=!1,D=!1;null!==t.oData.dMaxValue&&(d=t.oData.dCurrentDate.getTime()>t.oData.dMaxValue.getTime()),null!==t.oData.dMinValue&&(D=t.oData.dCurrentDate.getTime()<t.oData.dMinValue.getTime()),d||D?(d&&(m=new Date(t.oData.dMaxValue)),D&&(m=new Date(t.oData.dMinValue))):m=new Date(t.oData.dCurrentDate)}if(t.oData.dCurrentDate=new Date(m),t._setVariablesForDate(),a={},s=i=o="",(t.oData.bDateMode||t.oData.bDateTimeMode)&&(t.oData.bDateMode&&(t.oData.bArrMatchFormat[4]||t.oData.bArrMatchFormat[5]||t.oData.bArrMatchFormat[6])&&(t.oData.iCurrentDay=1),r=t._formatDate(),b(t.element).find(".day .dtpicker-compValue").val(r.dd),t.oData.bDateMode?t.oData.bArrMatchFormat[4]||t.oData.bArrMatchFormat[7]?b(t.element).find(".month .dtpicker-compValue").val(r.MM):t.oData.bArrMatchFormat[6]?b(t.element).find(".month .dtpicker-compValue").val(r.month):b(t.element).find(".month .dtpicker-compValue").val(r.monthShort):b(t.element).find(".month .dtpicker-compValue").val(r.monthShort),b(t.element).find(".year .dtpicker-compValue").val(r.yyyy),t.settings.formatHumanDate?a=b.extend(a,r):t.oData.bDateMode&&(t.oData.bArrMatchFormat[4]||t.oData.bArrMatchFormat[5]||t.oData.bArrMatchFormat[6]||t.oData.bArrMatchFormat[7])?t.oData.bArrMatchFormat[4]?o=r.MM+t.settings.monthYearSeparator+r.yyyy:t.oData.bArrMatchFormat[5]?o=r.monthShort+t.settings.monthYearSeparator+r.yyyy:t.oData.bArrMatchFormat[6]?o=r.month+t.settings.monthYearSeparator+r.yyyy:t.oData.bArrMatchFormat[7]&&(o=r.yyyy+t.settings.monthYearSeparator+r.MM):o=r.dayShort+", "+r.month+" "+r.dd+", "+r.yyyy),t.oData.bTimeMode||t.oData.bDateTimeMode)if(n=t._formatTime(),t.oData.bIs12Hour&&b(t.element).find(".meridiem .dtpicker-compValue").val(t.oData.sCurrentMeridiem),b(t.element).find(".hour .dtpicker-compValue").val(n.hour),b(t.element).find(".minutes .dtpicker-compValue").val(n.mm),b(t.element).find(".seconds .dtpicker-compValue").val(n.ss),t.settings.formatHumanDate)a=b.extend(a,n);else{var l=t.oData.bTimeMode&&(t.oData.bArrMatchFormat[0]||t.oData.bArrMatchFormat[1]),p=t.oData.bDateTimeMode&&(t.oData.bArrMatchFormat[0]||t.oData.bArrMatchFormat[1]||t.oData.bArrMatchFormat[2]||t.oData.bArrMatchFormat[3]||t.oData.bArrMatchFormat[4]||t.oData.bArrMatchFormat[5]||t.oData.bArrMatchFormat[6]||t.oData.bArrMatchFormat[7]);i=l||p?n.hour+t.settings.timeSeparator+n.mm+t.settings.timeSeparator+n.ss:n.hour+t.settings.timeSeparator+n.mm,t.oData.bIs12Hour&&(i+=t.settings.timeMeridiemSeparator+t.oData.sCurrentMeridiem)}t.settings.formatHumanDate?(t.oData.bDateTimeMode?e=t.oData.sDateFormat:t.oData.bDateMode?e=t.oData.sTimeFormat:t.oData.bTimeMode&&(e=t.oData.sDateTimeFormat),s=t.settings.formatHumanDate.call(t,a,t.settings.mode,e)):t.oData.bDateTimeMode?s=o+t.settings.dateTimeSeparator+i:t.oData.bDateMode?s=o:t.oData.bTimeMode&&(s=i),b(t.element).find(".dtpicker-value").html(s),t._setButtons()},_formatDate:function(t){var e,a,r,n,o,i,s,m=this,u={};return b.cf._isValid(t)?u=b.extend({},t):(u.iCurrentDay=m.oData.iCurrentDay,u.iCurrentMonth=m.oData.iCurrentMonth,u.iCurrentYear=m.oData.iCurrentYear,u.iCurrentWeekday=m.oData.iCurrentWeekday),e=(e=u.iCurrentDay)<10?"0"+e:e,r=u.iCurrentMonth,n=(n=u.iCurrentMonth+1)<10?"0"+n:n,o=m.settings.shortMonthNames[r],i=m.settings.fullMonthNames[r],a=u.iCurrentYear,s=u.iCurrentWeekday,{dd:e,MM:n,monthShort:o,month:i,yyyy:a,dayShort:m.settings.shortDayNames[s],day:m.settings.fullDayNames[s]}},_formatTime:function(t){var e,a,r,n,o,i,s,m=this,u={};return b.cf._isValid(t)?u=b.extend({},t):(u.iCurrentHour=m.oData.iCurrentHour,u.iCurrentMinutes=m.oData.iCurrentMinutes,u.iCurrentSeconds=m.oData.iCurrentSeconds,u.sCurrentMeridiem=m.oData.sCurrentMeridiem),o=a=(e=u.iCurrentHour)<10?"0"+e:e,12<(r=u.iCurrentHour)&&(r-=12),"00"===o&&(r=12),n=r<10?"0"+r:r,m.oData.bIs12Hour&&(o=n),i=(i=u.iCurrentMinutes)<10?"0"+i:i,s=(s=u.iCurrentSeconds)<10?"0"+s:s,{H:e,HH:a,h:r,hh:n,hour:o,m:u.iCurrentMinutes,mm:i,s:u.iCurrentSeconds,ss:s,ME:u.sCurrentMeridiem}},_setButtons:function(){var t,e,a,r=this;(b(r.element).find(".dtpicker-compButton").removeClass("dtpicker-compButtonDisable").addClass("dtpicker-compButtonEnable"),null!==r.oData.dMaxValue&&(r.oData.bTimeMode?((r.oData.iCurrentHour+1>r.oData.dMaxValue.getHours()||r.oData.iCurrentHour+1===r.oData.dMaxValue.getHours()&&r.oData.iCurrentMinutes>r.oData.dMaxValue.getMinutes())&&b(r.element).find(".hour .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"),r.oData.iCurrentHour>=r.oData.dMaxValue.getHours()&&r.oData.iCurrentMinutes+1>r.oData.dMaxValue.getMinutes()&&b(r.element).find(".minutes .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable")):((t=new Date(r.oData.iCurrentYear,r.oData.iCurrentMonth,r.oData.iCurrentDay+1,r.oData.iCurrentHour,r.oData.iCurrentMinutes,r.oData.iCurrentSeconds,0)).getTime()>r.oData.dMaxValue.getTime()&&b(r.element).find(".day .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"),(t=new Date(r.oData.iCurrentYear,r.oData.iCurrentMonth+1,r.oData.iCurrentDay,r.oData.iCurrentHour,r.oData.iCurrentMinutes,r.oData.iCurrentSeconds,0)).getTime()>r.oData.dMaxValue.getTime()&&b(r.element).find(".month .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"),(t=new Date(r.oData.iCurrentYear+1,r.oData.iCurrentMonth,r.oData.iCurrentDay,r.oData.iCurrentHour,r.oData.iCurrentMinutes,r.oData.iCurrentSeconds,0)).getTime()>r.oData.dMaxValue.getTime()&&b(r.element).find(".year .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"),(t=new Date(r.oData.iCurrentYear,r.oData.iCurrentMonth,r.oData.iCurrentDay,r.oData.iCurrentHour+1,r.oData.iCurrentMinutes,r.oData.iCurrentSeconds,0)).getTime()>r.oData.dMaxValue.getTime()&&b(r.element).find(".hour .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"),(t=new Date(r.oData.iCurrentYear,r.oData.iCurrentMonth,r.oData.iCurrentDay,r.oData.iCurrentHour,r.oData.iCurrentMinutes+1,r.oData.iCurrentSeconds,0)).getTime()>r.oData.dMaxValue.getTime()&&b(r.element).find(".minutes .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"),(t=new Date(r.oData.iCurrentYear,r.oData.iCurrentMonth,r.oData.iCurrentDay,r.oData.iCurrentHour,r.oData.iCurrentMinutes,r.oData.iCurrentSeconds+1,0)).getTime()>r.oData.dMaxValue.getTime()&&b(r.element).find(".seconds .increment").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"))),null!==r.oData.dMinValue&&(r.oData.bTimeMode?((r.oData.iCurrentHour-1<r.oData.dMinValue.getHours()||r.oData.iCurrentHour-1===r.oData.dMinValue.getHours()&&r.oData.iCurrentMinutes<r.oData.dMinValue.getMinutes())&&b(r.element).find(".hour .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"),r.oData.iCurrentHour<=r.oData.dMinValue.getHours()&&r.oData.iCurrentMinutes-1<r.oData.dMinValue.getMinutes()&&b(r.element).find(".minutes .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable")):((t=new Date(r.oData.iCurrentYear,r.oData.iCurrentMonth,r.oData.iCurrentDay-1,r.oData.iCurrentHour,r.oData.iCurrentMinutes,r.oData.iCurrentSeconds,0)).getTime()<r.oData.dMinValue.getTime()&&b(r.element).find(".day .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"),(t=new Date(r.oData.iCurrentYear,r.oData.iCurrentMonth-1,r.oData.iCurrentDay,r.oData.iCurrentHour,r.oData.iCurrentMinutes,r.oData.iCurrentSeconds,0)).getTime()<r.oData.dMinValue.getTime()&&b(r.element).find(".month .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"),(t=new Date(r.oData.iCurrentYear-1,r.oData.iCurrentMonth,r.oData.iCurrentDay,r.oData.iCurrentHour,r.oData.iCurrentMinutes,r.oData.iCurrentSeconds,0)).getTime()<r.oData.dMinValue.getTime()&&b(r.element).find(".year .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"),(t=new Date(r.oData.iCurrentYear,r.oData.iCurrentMonth,r.oData.iCurrentDay,r.oData.iCurrentHour-1,r.oData.iCurrentMinutes,r.oData.iCurrentSeconds,0)).getTime()<r.oData.dMinValue.getTime()&&b(r.element).find(".hour .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"),(t=new Date(r.oData.iCurrentYear,r.oData.iCurrentMonth,r.oData.iCurrentDay,r.oData.iCurrentHour,r.oData.iCurrentMinutes-1,r.oData.iCurrentSeconds,0)).getTime()<r.oData.dMinValue.getTime()&&b(r.element).find(".minutes .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"),(t=new Date(r.oData.iCurrentYear,r.oData.iCurrentMonth,r.oData.iCurrentDay,r.oData.iCurrentHour,r.oData.iCurrentMinutes,r.oData.iCurrentSeconds-1,0)).getTime()<r.oData.dMinValue.getTime()&&b(r.element).find(".seconds .decrement").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"))),r.oData.bIs12Hour)&&(null===r.oData.dMaxValue&&null===r.oData.dMinValue||(e=r.oData.iCurrentHour,b.cf._compare(r.oData.sCurrentMeridiem,"AM")?e+=12:b.cf._compare(r.oData.sCurrentMeridiem,"PM")&&(e-=12),t=new Date(r.oData.iCurrentYear,r.oData.iCurrentMonth,r.oData.iCurrentDay,e,r.oData.iCurrentMinutes,r.oData.iCurrentSeconds,0),null!==r.oData.dMaxValue&&(r.oData.bTimeMode?(a=r.oData.iCurrentMinutes,(e>r.oData.dMaxValue.getHours()||e===r.oData.dMaxValue.getHours()&&a>r.oData.dMaxValue.getMinutes())&&b(r.element).find(".meridiem .dtpicker-compButton").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable")):t.getTime()>r.oData.dMaxValue.getTime()&&b(r.element).find(".meridiem .dtpicker-compButton").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable")),null!==r.oData.dMinValue&&(r.oData.bTimeMode?(a=r.oData.iCurrentMinutes,(e<r.oData.dMinValue.getHours()||e===r.oData.dMinValue.getHours()&&a<r.oData.dMinValue.getMinutes())&&b(r.element).find(".meridiem .dtpicker-compButton").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable")):t.getTime()<r.oData.dMinValue.getTime()&&b(r.element).find(".meridiem .dtpicker-compButton").removeClass("dtpicker-compButtonEnable").addClass("dtpicker-compButtonDisable"))))},setIsPopup:function(t){var e=this;if(!e.settings.isInline)if(e.settings.isPopup=t,"none"!==b(e.element).css("display")&&e._hidePicker(0),e.settings.isPopup)b(e.element).addClass("dtpicker-mobile"),b(e.element).css({position:"fixed",top:0,left:0,width:"100%",height:"100%"});else if(b(e.element).removeClass("dtpicker-mobile"),null!==e.oData.oInputElement){var a=b(e.oData.oInputElement).offset().top+b(e.oData.oInputElement).outerHeight(),r=b(e.oData.oInputElement).offset().left,n=b(e.oData.oInputElement).outerWidth();b(e.element).css({position:"absolute",top:a,left:r,width:n,height:"auto"})}},_compareDates:function(t,e){var a=((t=new Date(t.getDate(),t.getMonth(),t.getFullYear(),0,0,0,0)).getTime()-e.getTime())/864e5;return 0==a?a:a/Math.abs(a)},_compareTime:function(t,e){var a=0;return t.getHours()===e.getHours()&&t.getMinutes()===e.getMinutes()?a=1:t.getHours()<e.getHours()?a=2:t.getHours()>e.getHours()?a=3:t.getHours()===e.getHours()&&(t.getMinutes()<e.getMinutes()?a=2:t.getMinutes()>e.getMinutes()&&(a=3)),a},_compareDateTime:function(t,e){var a=(t.getTime()-e.getTime())/6e4;return 0==a?a:a/Math.abs(a)},_determineMeridiemFromHourAndMinutes:function(t,e){return 12<t||12===t&&0<=e?"PM":"AM"},setLanguage:function(t){var e=this;return e.settings=b.extend({},b.DateTimePicker.defaults,b.DateTimePicker.i18n[t],e.options),e.settings.language=t,e._setDateFormatArray(),e._setTimeFormatArray(),e._setDateTimeFormatArray(),e}}}); ```
/content/code_sandbox/public/vendor/datetimepicker/dist/DateTimePicker.min.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
16,191
```html <!DOCTYPE html> <html> <head> <title>Example - Zepto</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="zepto-1.1.6-Custom.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker-zepto.js"></script> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" data-format="yyyy-MM-dd" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" data-format="hh:mm AA" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" data-format="yyyy-MM-dd hh:mm:ss AA" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker(); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/Basic-Zepto.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
358
```html <!DOCTYPE html> <html> <head> <title>Date Picker</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <p>Date : </p> <input type="text" data-field="date" readonly> <p>Time : </p> <input type="text" data-field="time" readonly> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker({ init: function() { var oDTP = this; oDTP.setDateTimeStringInInputField(); } }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/SetValueInInput.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
384
```html <!DOCTYPE html> <html> <head> <title>Period Range - Minimum Time Now</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <form> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="time" readonly> </form> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker( { timeFormat: "hh:mm AA", addEventHandlers: function() { var oDTP = this; oDTP.settings.minTime = oDTP.getDateTimeStringInFormat("Time", "hh:mm AA", new Date()); //oDTP.settings.maxTime = "11:59 PM"; } }); }); </script> <!-- Default dateFormat: "dd-MM-yyyy" dateFormat Options : 1. "dd-MM-yyyy" 2. "MM-dd-yyyy" 3. "yyyy-MM-dd" Specify (data-min & data-max) / (minDate & maxDate) values in the same dateFormat specified in settings parameters --> <!-- Default timeFormat: "HH:mm" timeFormat Options : 1. "HH:mm" 2. "hh:mm AA" Specify (data-min & data-max) / (minTime & maxTime) values in the same timeFormat specified in settings parameters --> <!-- Default dateTimeFormat: "dd-MM-yyyy HH:mm:ss" dateTimeFormat Options : 1. "dd-MM-yyyy HH:mm:ss" 2. "dd-MM-yyyy hh:mm:ss AA" 3. "MM-dd-yyyy HH:mm:ss" 4. "MM-dd-yyyy hh:mm:ss AA" 5. "yyyy-MM-dd HH:mm:ss" 6. "yyyy-MM-dd hh:mm:ss AA" Specify (data-min & data-max) / (minDateTime & maxDateTime) values in the same dateTimeFormat specified in settings parameters --> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/PeriodRange-MinNow.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
693
```html <!DOCTYPE html> <html> <head> <title>Custom Input Value</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } .btn { background: #FFFFFF; color: #A3A3CC; border: 2px solid #A3A3CC; border-radius: 5px; padding: 10px 20px; margin: 20px; font-size: 12px; cursor: pointer; } </style> </head> <body> <p>Date : </p> <input id="input-date" type="text" data-field="date" data-format="dd-MM-yyyy" value="2016-07-05" readonly> <div id="dateBox"></div> <script type="text/javascript"> $(document).ready(function() { var oDTP1; $("#dateBox").DateTimePicker( { addEventHandlers: function() { oDTP = this; oDTP.settings.maxDate = oDTP.getDateTimeStringInFormat("date", "dd-MM-yyyy", new Date()); }, parseDateTimeString: function(sDateTime, sMode, sFormat, oInputElement) { oDTP1 = this; console.log(sDateTime + " " + sMode); var dThisDate = new Date(), iArrDateTimeComps, sRegex; if($.cf._isValid(sDateTime)) { // "2016-10-26" sRegex = /(\d{1,4})(-)(\d{1,2})(-)(\d{1,2})/; iArrDateTimeComps = sDateTime.match(sRegex); dThisDate = new Date( parseInt(iArrDateTimeComps[1]), parseInt(iArrDateTimeComps[3]) - 1, parseInt(iArrDateTimeComps[5]), 0, 0, 0, 0 ); } return dThisDate; }, formatDateTimeString: function(oDate, sMode, sFormat, oInputElement) { oDTP1 = this; console.log("formatDateTimeString " + sFormat); console.log(oDate); if(sFormat === "yyyy-MM-dd") return oDate.yyyy + "-" + oDate.MM + "-" + oDate.dd; else if(sFormat === "dd-MM-yyyy") return oDate.dd + "-" + oDate.MM + "-" + oDate.yyyy; } }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicExamples-CustomInputValue-Issue125.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
778
```html <!DOCTYPE html> <html> <head> <title>View -- Popup</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker(); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/ViewPopup-Parameters.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
383
```html <!DOCTYPE html> <html> <head> <title>Format - Data Attributes</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" data-format="yyyy-MM-dd" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" data-format="hh:mm AA" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" data-format="yyyy-MM-dd hh:mm:ss AA" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker(); }); </script> <!-- Default dateFormat: "dd-MM-yyyy" dateFormat Options : 1. "dd-MM-yyyy" 2. "MM-dd-yyyy" 3. "yyyy-MM-dd" Specify data-min & data-max values in the same dateFormat specified in settings parameters --> <!-- Default timeFormat: "HH:mm" timeFormat Options : 1. "HH:mm" 2. "hh:mm AA" Specify data-min & data-max values in the same timeFormat specified in settings parameters --> <!-- Default dateTimeFormat: "dd-MM-yyyy HH:mm:ss" dateTimeFormat Options : 1. "dd-MM-yyyy HH:mm:ss" 2. "dd-MM-yyyy hh:mm:ss AA" 3. "MM-dd-yyyy HH:mm:ss" 4. "MM-dd-yyyy hh:mm:ss AA" 5. "yyyy-MM-dd HH:mm:ss" 6. "yyyy-MM-dd hh:mm:ss AA" Specify data-min & data-max values in the same dateTimeFormat specified in settings parameters --> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/Format-DataAttributes.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
668
```html <!DOCTYPE html> <html> <head> <title>TouchHold Gesture Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <p>Date : </p> <input type="text" data-field="date" readonly> <p>Time : </p> <input type="text" data-field="time" readonly> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker({ captureTouchHold: true, touchHoldInterval: 300 }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/Events-TouchHold.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
392
```html <!DOCTYPE html> <html> <head> <title>Custom Events</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } .pickerButton { background: #FFFFFF; color: #A3A3CC; border: 2px solid #A3A3CC; border-radius: 5px; padding: 10px 20px; margin: 20px; cursor: pointer; } .pickerButton:hover { color: #CCA3A3; border-color: #CCA3A3; } </style> </head> <body> <div class="container"> <div id="datePicker"> <p>Date : </p> <input type="text" data-field="date" readonly> <span class="pickerButton">Show</span> </div> <div id="timePicker"> <p>Time : </p> <input type="text" data-field="time" readonly> <span class="pickerButton">Show</span> </div> <div id="dateTimePicker"> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <span class="pickerButton">Show</span> </div> </div> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker( { addEventHandlers: function() { var dtPickerObj = this; $("input").attr("disabled", "disabled"); $("#datePicker .pickerButton").click(function(e) { e.stopPropagation(); dtPickerObj.showDateTimePicker($("#datePicker input")); }); $("#timePicker .pickerButton").click(function(e) { e.stopPropagation(); dtPickerObj.showDateTimePicker($("#timePicker input")); }); $("#dateTimePicker .pickerButton").click(function(e) { e.stopPropagation(); dtPickerObj.showDateTimePicker($("#dateTimePicker input")); }); } }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicExamples-CustomEvent.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
698
```html <!DOCTYPE html> <html> <head> <title>View -- Data Attributes</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" data-view="Popup" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" data-view="Popup" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" data-view="Popup" readonly> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" data-view="Dropdown" readonly> <p>Date : </p> <input type="text" data-field="date" data-view="Dropdown" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" data-view="Dropdown" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" data-view="Dropdown" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker(); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/View-DataAttributes.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
541
```html <!DOCTYPE html> <html> <head> <title>Seconds Interval</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <p>Time : (Format - "hh:mm:ss AA")</p> <input type="text" data-field="time" data-format="hh:mm:ss AA" readonly> <p>Time : (Format - "HH:mm:ss")</p> <input type="text" data-field="time" data-format="HH:mm:ss" readonly> <p>DateTime : (Format - "dd-MM-yyyy hh:mm:ss AA")</p> <input type="text" data-field="datetime" data-format="dd-MM-yyyy hh:mm:ss AA" readonly> <p>DateTime : (Format - "dd-MM-yyyy HH:mm:ss")</p> <input type="text" data-field="datetime" data-format="dd-MM-yyyy HH:mm:ss" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker({ secondsInterval: 5 }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicExamples-SecondsInterval.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
463
```html <!DOCTYPE html> <html> <head> <title>Basic Examples -- Elements Group</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } .group1 { border: 1px solid skyblue; margin: 20px; border-radius: 3px; } .group2 { border: 1px solid orange; margin: 20px; border-radius: 3px; } </style> </head> <body> <div class="group1"> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> </div> <div class="group2"> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> </div> <div id="dtBox1"></div> <div id="dtBox2"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox1").DateTimePicker( { parentElement: ".group1" }); $("#dtBox2").DateTimePicker( { dateFormat: "dd-MMM-yyyy", parentElement: ".group2" }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicExamples-ElementsGroup.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
654
```html <!DOCTYPE html> <html> <head> <title>Minute Interval</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker({ minuteInterval: 5 }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicExamples-MinuteInterval.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
317
```html <!DOCTYPE html> <html> <head> <title>Period Range - Minimum Date Today</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <form> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" readonly> </form> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker( { dateFormat: "dd-MMM-yyyy", addEventHandlers: function() { var oDTP = this; oDTP.settings.minDate = oDTP.getDateTimeStringInFormat("Date", "dd-MMM-yyyy", new Date()); } }); }); </script> <!-- Default dateFormat: "dd-MM-yyyy" dateFormat Options : 1. "dd-MM-yyyy" 2. "MM-dd-yyyy" 3. "yyyy-MM-dd" Specify (data-min & data-max) / (minDate & maxDate) values in the same dateFormat specified in settings parameters --> <!-- Default timeFormat: "HH:mm" timeFormat Options : 1. "HH:mm" 2. "hh:mm AA" Specify (data-min & data-max) / (minTime & maxTime) values in the same timeFormat specified in settings parameters --> <!-- Default dateTimeFormat: "dd-MM-yyyy HH:mm:ss" dateTimeFormat Options : 1. "dd-MM-yyyy HH:mm:ss" 2. "dd-MM-yyyy hh:mm:ss AA" 3. "MM-dd-yyyy HH:mm:ss" 4. "MM-dd-yyyy hh:mm:ss AA" 5. "yyyy-MM-dd HH:mm:ss" 6. "yyyy-MM-dd hh:mm:ss AA" Specify (data-min & data-max) / (minDateTime & maxDateTime) values in the same dateTimeFormat specified in settings parameters --> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/PeriodRange-MinToday.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
679
```html <!DOCTYPE html> <html> <head> <title>Format - Month Year</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <div class="separator-1"> <p>Format - "MM-yyyy"</p> <input type="text" data-field="date" data-format="MM-yyyy" readonly> <p>Format - "yyyy-MM"</p> <input type="text" data-field="date" data-format="yyyy-MM" readonly> </div> <div class="separator-2"> <p>Format - "MMM yyyy"</p> <input type="text" data-field="date" data-format="MMM yyyy" data-min="Jan 2015" data-max="Dec 2015" readonly> <p>Format - "MMMM yyyy"</p> <input type="text" data-field="date" data-format="MMMM yyyy" readonly> </div> <div id="dtBox-1"></div> <div id="dtBox-2"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox-1").DateTimePicker( { parentElement: ".separator-1", monthYearSeparator: "-" }); $("#dtBox-2").DateTimePicker( { parentElement: ".separator-2", defaultDate: "Jul 2015" }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/Format-MonthYear.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
533
```html <!DOCTYPE html> <html> <head> <title>Period Range - Parameters</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker({ defaultDate: new Date(2014, 5, 20, 0, 0, 0), minDate: "01-03-2012", maxDate: "01-03-2016", minTime: "09:00", maxTime: "19:30", minDateTime: "01-03-2012 08:30", maxDateTime: "01-03-2016 18:30" }); }); </script> <!-- Default dateFormat: "dd-MM-yyyy" dateFormat Options : 1. "dd-MM-yyyy" 2. "MM-dd-yyyy" 3. "yyyy-MM-dd" Specify minDate & maxDate values in the same dateFormat specified in settings parameters --> <!-- Default timeFormat: "HH:mm" timeFormat Options : 1. "HH:mm" 2. "hh:mm AA" Specify minTime & maxTime values in the same timeFormat specified in settings parameters --> <!-- Default dateTimeFormat: "dd-MM-yyyy HH:mm:ss" dateTimeFormat Options : 1. "dd-MM-yyyy HH:mm:ss" 2. "dd-MM-yyyy hh:mm:ss AA" 3. "MM-dd-yyyy HH:mm:ss" 4. "MM-dd-yyyy hh:mm:ss AA" 5. "yyyy-MM-dd HH:mm:ss" 6. "yyyy-MM-dd hh:mm:ss AA" Specify minDateTime & maxDateTime values in the same dateTimeFormat specified in settings parameters --> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/PeriodRange-Parameters.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
745
```html <!DOCTYPE html> <html> <head> <title>Human Date Formatting</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <p>Date : </p> <input type="text" data-field="date" readonly> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker( { formatHumanDate: function(oDate, sMode, sFormat) { if(sMode === "date") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ ", " + oDate.yyyy; else if(sMode === "time") return oDate.HH + ":" + oDate.mm + ":" + oDate.ss; else if(sMode === "datetime") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ ", " + oDate.yyyy + " " + oDate.HH + ":" + oDate.mm + ":" + oDate.ss; } }); }); </script> <!-- formatHumanDate - format Date displayed in the Header of the DateTimerPicker parameter : date attributes of parameter date dd : day of the month(two-digit) MM : month(two-digit) yyyy : year(four-digit), day : day of the week (as specified in fullDayNames settings), dayShort : day of the week (as specified in shortDayNames settings), month : month name(as specified in fullMonthNames settings), monthShort : short month name(as specified in shortMonthNames settings) --> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicExamples-HumanDateFormatting.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
625
```html <!DOCTYPE html> <html> <head> <title>DateTime Picker</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker(); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicDateTimePicker.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
306
```html <!DOCTYPE html> <html> <head> <title>View -- Based On Document Width</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { var bIsPopup = displayPopup(); $("#dtBox").DateTimePicker( { isPopup: bIsPopup, addEventHandlers: function() { var dtPickerObj = this; $(window).resize(function() { bIsPopup = displayPopup(); dtPickerObj.setIsPopup(bIsPopup); }); } }); }); function displayPopup() { if($(document).width() >= 768) return false; else return true; } </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/View-BasedOnDocumentWidth.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
501
```html <!DOCTYPE html> <html> <head> <title>Basic Examples -- Elements Group</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } .group1 { border: 1px solid skyblue; margin: 20px; border-radius: 3px; } .group2 { border: 1px solid orange; margin: 20px; border-radius: 3px; } </style> </head> <body> <div class="group1"> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> </div> <div class="group2"> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> </div> <div id="dtBox1" data-parentelement=".group1"></div> <div id="dtBox2" data-parentelement=".group2"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox1").DateTimePicker( { }); $("#dtBox2").DateTimePicker( { dateFormat: "dd-MMM-yyyy" }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicExamples-ElementsGroup-DataAttribute.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
652
```html <!DOCTYPE html> <html> <head> <title>Basic Examples -- Custom Input String</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } span[data-field] { border: 1px inset #DEDEDE; display: inline-block; width: 200px; height: 15px; line-height: 15px; font: -webkit-small-control; padding: 10px; margin-left: 20px; margin-bottom: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <!------------------------ Date Picker ------------------------> <p>Date : </p> <span data-field="date">Set Date</span> <!------------------------ Time Picker ------------------------> <p>Time : </p> <span data-field="time">Set Time</span> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <span data-field="datetime">Set DateTime</span> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" value="Set Date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" value="Set Time" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" value="Set DateTime" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker(); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicExamples-CustomInputString.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
581
```javascript /*! jQuery v3.1.0 | (c) jQuery Foundation | jquery.org/license */ !function(a,b){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){"use strict";var c=[],d=a.document,e=Object.getPrototypeOf,f=c.slice,g=c.concat,h=c.push,i=c.indexOf,j={},k=j.toString,l=j.hasOwnProperty,m=l.toString,n=m.call(Object),o={};function p(a,b){b=b||d;var c=b.createElement("script");c.text=a,b.head.appendChild(c).parentNode.removeChild(c)}var q="3.1.0",r=function(a,b){return new r.fn.init(a,b)},s=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,t=/^-ms-/,u=/-([a-z])/g,v=function(a,b){return b.toUpperCase()};r.fn=r.prototype={jquery:q,constructor:r,length:0,toArray:function(){return f.call(this)},get:function(a){return null!=a?a<0?this[a+this.length]:this[a]:f.call(this)},pushStack:function(a){var b=r.merge(this.constructor(),a);return b.prevObject=this,b},each:function(a){return r.each(this,a)},map:function(a){return this.pushStack(r.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(f.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(a<0?b:0);return this.pushStack(c>=0&&c<b?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:h,sort:c.sort,splice:c.splice},r.extend=r.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||r.isFunction(g)||(g={}),h===i&&(g=this,h--);h<i;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(r.isPlainObject(d)||(e=r.isArray(d)))?(e?(e=!1,f=c&&r.isArray(c)?c:[]):f=c&&r.isPlainObject(c)?c:{},g[b]=r.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},r.extend({expando:"jQuery"+(q+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===r.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){var b=r.type(a);return("number"===b||"string"===b)&&!isNaN(a-parseFloat(a))},isPlainObject:function(a){var b,c;return!(!a||"[object Object]"!==k.call(a))&&(!(b=e(a))||(c=l.call(b,"constructor")&&b.constructor,"function"==typeof c&&m.call(c)===n))},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?j[k.call(a)]||"object":typeof a},globalEval:function(a){p(a)},camelCase:function(a){return a.replace(t,"ms-").replace(u,v)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(w(a)){for(c=a.length;d<c;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(s,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(w(Object(a))?r.merge(c,"string"==typeof a?[a]:a):h.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:i.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;d<c;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;f<g;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,f=0,h=[];if(w(a))for(d=a.length;f<d;f++)e=b(a[f],f,c),null!=e&&h.push(e);else for(f in a)e=b(a[f],f,c),null!=e&&h.push(e);return g.apply([],h)},guid:1,proxy:function(a,b){var c,d,e;if("string"==typeof b&&(c=a[b],b=a,a=c),r.isFunction(a))return d=f.call(arguments,2),e=function(){return a.apply(b||this,d.concat(f.call(arguments)))},e.guid=a.guid=a.guid||r.guid++,e},now:Date.now,support:o}),"function"==typeof Symbol&&(r.fn[Symbol.iterator]=c[Symbol.iterator]),r.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){j["[object "+b+"]"]=b.toLowerCase()});function w(a){var b=!!a&&"length"in a&&a.length,c=r.type(a);return"function"!==c&&!r.isWindow(a)&&("array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a)}var x=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=function(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",M="\\["+K+"*("+L+")(?:"+K+"*([*^$|!~]?=)"+K+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+L+"))|)"+K+"*\\]",N=":("+L+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+M+")*)|.*)\\)|)",O=new RegExp(K+"+","g"),P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(N),U=new RegExp("^"+L+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L+"|[*])"),ATTR:new RegExp("^"+M),PSEUDO:new RegExp("^"+N),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),aa=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:d<0?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ba=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g,ca=function(a,b){return b?"\0"===a?"\ufffd":a.slice(0,-1)+"\\"+a.charCodeAt(a.length-1).toString(16)+" ":"\\"+a},da=function(){m()},ea=ta(function(a){return a.disabled===!0},{dir:"parentNode",next:"legend"});try{G.apply(D=H.call(v.childNodes),v.childNodes),D[v.childNodes.length].nodeType}catch(fa){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s=b&&b.ownerDocument,w=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==w&&9!==w&&11!==w)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==w&&(l=Z.exec(a)))if(f=l[1]){if(9===w){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(s&&(j=s.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(l[2])return G.apply(d,b.getElementsByTagName(a)),d;if((f=l[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==w)s=b,r=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(ba,ca):b.setAttribute("id",k=u),o=g(a),h=o.length;while(h--)o[h]="#"+k+" "+sa(o[h]);r=o.join(","),s=$.test(a)&&qa(b.parentNode)||b}if(r)try{return G.apply(d,s.querySelectorAll(r)),d}catch(x){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(P,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("fieldset");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&a.sourceIndex-b.sourceIndex;if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return function(b){return"label"in b&&b.disabled===a||"form"in b&&b.disabled===a||"form"in b&&b.disabled===!1&&(b.isDisabled===a||b.isDisabled!==!a&&("label"in b||!ea(b))!==a)}}function pa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function qa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return!!b&&"HTML"!==b.nodeName},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),v!==n&&(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(n.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){if("undefined"!=typeof b.getElementsByClassName&&p)return b.getElementsByClassName(a)},r=[],q=[],(c.qsa=Y.test(n.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){a.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+K+"*[*^$|!~]?="),2!==a.querySelectorAll(":enabled").length&&q.push(":enabled",":disabled"),o.appendChild(a).disabled=!0,2!==a.querySelectorAll(":disabled").length&&q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Y.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"*"),s.call(a,"[s!='']:x"),r.push("!=",N)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Y.test(o.compareDocumentPosition),t=b||Y.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?I(k,a)-I(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?I(k,a)-I(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?la(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(S,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.escape=function(a){return(a+"").replace(ba,ca)},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(_,aa),a[3]=(a[3]||a[4]||a[5]||"").replace(_,aa),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return V.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&T.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(_,aa).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:!b||(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(O," ")+" ").indexOf(c)>-1:"|="===b&&(e===c||e.slice(0,c.length+1)===c+"-"))}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(P,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(_,aa),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return U.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(_,aa).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:oa(!1),disabled:oa(!0),checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:pa(function(){return[0]}),last:pa(function(a,b){return[b-1]}),eq:pa(function(a,b,c){return[c<0?c+b:c]}),even:pa(function(a,b){for(var c=0;c<b;c+=2)a.push(c);return a}),odd:pa(function(a,b){for(var c=1;c<b;c+=2)a.push(c);return a}),lt:pa(function(a,b,c){for(var d=c<0?c+b:c;--d>=0;)a.push(d);return a}),gt:pa(function(a,b,c){for(var d=c<0?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function ra(){}ra.prototype=d.filters=d.pseudos,d.setFilters=new ra,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=Q.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function sa(a){for(var b=0,c=a.length,d="";b<c;b++)d+=a[b].value;return d}function ta(a,b,c){var d=b.dir,e=b.next,f=e||d,g=c&&"parentNode"===f,h=x++;return b.first?function(b,c,e){while(b=b[d])if(1===b.nodeType||g)return a(b,c,e)}:function(b,c,i){var j,k,l,m=[w,h];if(i){while(b=b[d])if((1===b.nodeType||g)&&a(b,c,i))return!0}else while(b=b[d])if(1===b.nodeType||g)if(l=b[u]||(b[u]={}),k=l[b.uniqueID]||(l[b.uniqueID]={}),e&&e===b.nodeName.toLowerCase())b=b[d]||b;else{if((j=k[f])&&j[0]===w&&j[1]===h)return m[2]=j[2];if(k[f]=m,m[2]=a(b,c,i))return!0}}}function ua(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function va(a,b,c){for(var d=0,e=b.length;d<e;d++)ga(a,b[d],c);return c}function wa(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;h<i;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function xa(a,b,c,d,e,f){return d&&!d[u]&&(d=xa(d)),e&&!e[u]&&(e=xa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||va(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:wa(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=wa(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=wa(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ya(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ta(function(a){return a===b},h,!0),l=ta(function(a){return I(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];i<f;i++)if(c=d.relative[a[i].type])m=[ta(ua(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;e<f;e++)if(d.relative[a[e].type])break;return xa(i>1&&ua(m),i>1&&sa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(P,"$1"),c,i<e&&ya(a.slice(i,e)),e<f&&ya(a=a.slice(e)),e<f&&sa(a))}m.push(c)}return ua(m)}function za(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=E.call(i));u=wa(u)}G.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&ga.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=ya(b[c]),f[u]?d.push(f):e.push(f);f=A(a,za(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(_,aa),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=V.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(_,aa),$.test(j[0].type)&&qa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&sa(j),!a)return G.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||$.test(a)&&qa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("fieldset"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){if(!c)return a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){if(!c&&"input"===a.nodeName.toLowerCase())return a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(J,function(a,b,c){var d;if(!c)return a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);r.find=x,r.expr=x.selectors,r.expr[":"]=r.expr.pseudos,r.uniqueSort=r.unique=x.uniqueSort,r.text=x.getText,r.isXMLDoc=x.isXML,r.contains=x.contains,r.escapeSelector=x.escape;var y=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&r(a).is(c))break;d.push(a)}return d},z=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},A=r.expr.match.needsContext,B=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i,C=/^.[^:#\[\.,]*$/;function D(a,b,c){if(r.isFunction(b))return r.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return r.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(C.test(b))return r.filter(b,a,c);b=r.filter(b,a)}return r.grep(a,function(a){return i.call(b,a)>-1!==c&&1===a.nodeType})}r.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?r.find.matchesSelector(d,a)?[d]:[]:r.find.matches(a,r.grep(b,function(a){return 1===a.nodeType}))},r.fn.extend({find:function(a){var b,c,d=this.length,e=this;if("string"!=typeof a)return this.pushStack(r(a).filter(function(){for(b=0;b<d;b++)if(r.contains(e[b],this))return!0}));for(c=this.pushStack([]),b=0;b<d;b++)r.find(a,e[b],c);return d>1?r.uniqueSort(c):c},filter:function(a){return this.pushStack(D(this,a||[],!1))},not:function(a){return this.pushStack(D(this,a||[],!0))},is:function(a){return!!D(this,"string"==typeof a&&A.test(a)?r(a):a||[],!1).length}});var E,F=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,G=r.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||E,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:F.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof r?b[0]:b,r.merge(this,r.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),B.test(e[1])&&r.isPlainObject(b))for(e in b)r.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&(this[0]=f,this.length=1),this}return a.nodeType?(this[0]=a,this.length=1,this):r.isFunction(a)?void 0!==c.ready?c.ready(a):a(r):r.makeArray(a,this)};G.prototype=r.fn,E=r(d);var H=/^(?:parents|prev(?:Until|All))/,I={children:!0,contents:!0,next:!0,prev:!0};r.fn.extend({has:function(a){var b=r(a,this),c=b.length;return this.filter(function(){for(var a=0;a<c;a++)if(r.contains(this,b[a]))return!0})},closest:function(a,b){var c,d=0,e=this.length,f=[],g="string"!=typeof a&&r(a);if(!A.test(a))for(;d<e;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&r.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?r.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?i.call(r(a),this[0]):i.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(r.uniqueSort(r.merge(this.get(),r(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function J(a,b){while((a=a[b])&&1!==a.nodeType);return a}r.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return y(a,"parentNode")},parentsUntil:function(a,b,c){return y(a,"parentNode",c)},next:function(a){return J(a,"nextSibling")},prev:function(a){return J(a,"previousSibling")},nextAll:function(a){return y(a,"nextSibling")},prevAll:function(a){return y(a,"previousSibling")},nextUntil:function(a,b,c){return y(a,"nextSibling",c)},prevUntil:function(a,b,c){return y(a,"previousSibling",c)},siblings:function(a){return z((a.parentNode||{}).firstChild,a)},children:function(a){return z(a.firstChild)},contents:function(a){return a.contentDocument||r.merge([],a.childNodes)}},function(a,b){r.fn[a]=function(c,d){var e=r.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=r.filter(d,e)),this.length>1&&(I[a]||r.uniqueSort(e),H.test(a)&&e.reverse()),this.pushStack(e)}});var K=/\S+/g;function L(a){var b={};return r.each(a.match(K)||[],function(a,c){b[c]=!0}),b}r.Callbacks=function(a){a="string"==typeof a?L(a):r.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)f[h].apply(c[0],c[1])===!1&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function d(b){r.each(b,function(b,c){r.isFunction(c)?a.unique&&j.has(c)||f.push(c):c&&c.length&&"string"!==r.type(c)&&d(c)})}(arguments),c&&!b&&i()),this},remove:function(){return r.each(arguments,function(a,b){var c;while((c=r.inArray(b,f,c))>-1)f.splice(c,1),c<=h&&h--}),this},has:function(a){return a?r.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||b||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j};function M(a){return a}function N(a){throw a}function O(a,b,c){var d;try{a&&r.isFunction(d=a.promise)?d.call(a).done(b).fail(c):a&&r.isFunction(d=a.then)?d.call(a,b,c):b.call(void 0,a)}catch(a){c.call(void 0,a)}}r.extend({Deferred:function(b){var c=[["notify","progress",r.Callbacks("memory"),r.Callbacks("memory"),2],["resolve","done",r.Callbacks("once memory"),r.Callbacks("once memory"),0,"resolved"],["reject","fail",r.Callbacks("once memory"),r.Callbacks("once memory"),1,"rejected"]],d="pending",e={state:function(){return d},always:function(){return f.done(arguments).fail(arguments),this},"catch":function(a){return e.then(null,a)},pipe:function(){var a=arguments;return r.Deferred(function(b){r.each(c,function(c,d){var e=r.isFunction(a[d[4]])&&a[d[4]];f[d[1]](function(){var a=e&&e.apply(this,arguments);a&&r.isFunction(a.promise)?a.promise().progress(b.notify).done(b.resolve).fail(b.reject):b[d[0]+"With"](this,e?[a]:arguments)})}),a=null}).promise()},then:function(b,d,e){var f=0;function g(b,c,d,e){return function(){var h=this,i=arguments,j=function(){var a,j;if(!(b<f)){if(a=d.apply(h,i),a===c.promise())throw new TypeError("Thenable self-resolution");j=a&&("object"==typeof a||"function"==typeof a)&&a.then,r.isFunction(j)?e?j.call(a,g(f,c,M,e),g(f,c,N,e)):(f++,j.call(a,g(f,c,M,e),g(f,c,N,e),g(f,c,M,c.notifyWith))):(d!==M&&(h=void 0,i=[a]),(e||c.resolveWith)(h,i))}},k=e?j:function(){try{j()}catch(a){r.Deferred.exceptionHook&&r.Deferred.exceptionHook(a,k.stackTrace),b+1>=f&&(d!==N&&(h=void 0,i=[a]),c.rejectWith(h,i))}};b?k():(r.Deferred.getStackHook&&(k.stackTrace=r.Deferred.getStackHook()),a.setTimeout(k))}}return r.Deferred(function(a){c[0][3].add(g(0,a,r.isFunction(e)?e:M,a.notifyWith)),c[1][3].add(g(0,a,r.isFunction(b)?b:M)),c[2][3].add(g(0,a,r.isFunction(d)?d:N))}).promise()},promise:function(a){return null!=a?r.extend(a,e):e}},f={};return r.each(c,function(a,b){var g=b[2],h=b[5];e[b[1]]=g.add,h&&g.add(function(){d=h},c[3-a][2].disable,c[0][2].lock),g.add(b[3].fire),f[b[0]]=function(){return f[b[0]+"With"](this===f?void 0:this,arguments),this},f[b[0]+"With"]=g.fireWith}),e.promise(f),b&&b.call(f,f),f},when:function(a){var b=arguments.length,c=b,d=Array(c),e=f.call(arguments),g=r.Deferred(),h=function(a){return function(c){d[a]=this,e[a]=arguments.length>1?f.call(arguments):c,--b||g.resolveWith(d,e)}};if(b<=1&&(O(a,g.done(h(c)).resolve,g.reject),"pending"===g.state()||r.isFunction(e[c]&&e[c].then)))return g.then();while(c--)O(e[c],h(c),g.reject);return g.promise()}});var P=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;r.Deferred.exceptionHook=function(b,c){a.console&&a.console.warn&&b&&P.test(b.name)&&a.console.warn("jQuery.Deferred exception: "+b.message,b.stack,c)},r.readyException=function(b){a.setTimeout(function(){throw b})};var Q=r.Deferred();r.fn.ready=function(a){return Q.then(a)["catch"](function(a){r.readyException(a)}),this},r.extend({isReady:!1,readyWait:1,holdReady:function(a){a?r.readyWait++:r.ready(!0)},ready:function(a){(a===!0?--r.readyWait:r.isReady)||(r.isReady=!0,a!==!0&&--r.readyWait>0||Q.resolveWith(d,[r]))}}),r.ready.then=Q.then;function R(){d.removeEventListener("DOMContentLoaded",R),a.removeEventListener("load",R),r.ready()}"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(r.ready):(d.addEventListener("DOMContentLoaded",R),a.addEventListener("load",R));var S=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===r.type(c)){e=!0;for(h in c)S(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0, r.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(r(a),c)})),b))for(;h<i;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},T=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function U(){this.expando=r.expando+U.uid++}U.uid=1,U.prototype={cache:function(a){var b=a[this.expando];return b||(b={},T(a)&&(a.nodeType?a[this.expando]=b:Object.defineProperty(a,this.expando,{value:b,configurable:!0}))),b},set:function(a,b,c){var d,e=this.cache(a);if("string"==typeof b)e[r.camelCase(b)]=c;else for(d in b)e[r.camelCase(d)]=b[d];return e},get:function(a,b){return void 0===b?this.cache(a):a[this.expando]&&a[this.expando][r.camelCase(b)]},access:function(a,b,c){return void 0===b||b&&"string"==typeof b&&void 0===c?this.get(a,b):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d=a[this.expando];if(void 0!==d){if(void 0!==b){r.isArray(b)?b=b.map(r.camelCase):(b=r.camelCase(b),b=b in d?[b]:b.match(K)||[]),c=b.length;while(c--)delete d[b[c]]}(void 0===b||r.isEmptyObject(d))&&(a.nodeType?a[this.expando]=void 0:delete a[this.expando])}},hasData:function(a){var b=a[this.expando];return void 0!==b&&!r.isEmptyObject(b)}};var V=new U,W=new U,X=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Y=/[A-Z]/g;function Z(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(Y,"-$&").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c||"false"!==c&&("null"===c?null:+c+""===c?+c:X.test(c)?JSON.parse(c):c)}catch(e){}W.set(a,b,c)}else c=void 0;return c}r.extend({hasData:function(a){return W.hasData(a)||V.hasData(a)},data:function(a,b,c){return W.access(a,b,c)},removeData:function(a,b){W.remove(a,b)},_data:function(a,b,c){return V.access(a,b,c)},_removeData:function(a,b){V.remove(a,b)}}),r.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=W.get(f),1===f.nodeType&&!V.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=r.camelCase(d.slice(5)),Z(f,d,e[d])));V.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){W.set(this,a)}):S(this,function(b){var c;if(f&&void 0===b){if(c=W.get(f,a),void 0!==c)return c;if(c=Z(f,a),void 0!==c)return c}else this.each(function(){W.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){W.remove(this,a)})}}),r.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=V.get(a,b),c&&(!d||r.isArray(c)?d=V.access(a,b,r.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=r.queue(a,b),d=c.length,e=c.shift(),f=r._queueHooks(a,b),g=function(){r.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return V.get(a,c)||V.access(a,c,{empty:r.Callbacks("once memory").add(function(){V.remove(a,[b+"queue",c])})})}}),r.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?r.queue(this[0],a):void 0===b?this:this.each(function(){var c=r.queue(this,a,b);r._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&r.dequeue(this,a)})},dequeue:function(a){return this.each(function(){r.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=r.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=V.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var $=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,_=new RegExp("^(?:([+-])=|)("+$+")([a-z%]*)$","i"),aa=["Top","Right","Bottom","Left"],ba=function(a,b){return a=b||a,"none"===a.style.display||""===a.style.display&&r.contains(a.ownerDocument,a)&&"none"===r.css(a,"display")},ca=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};function da(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return r.css(a,b,"")},i=h(),j=c&&c[3]||(r.cssNumber[b]?"":"px"),k=(r.cssNumber[b]||"px"!==j&&+i)&&_.exec(r.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,r.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var ea={};function fa(a){var b,c=a.ownerDocument,d=a.nodeName,e=ea[d];return e?e:(b=c.body.appendChild(c.createElement(d)),e=r.css(b,"display"),b.parentNode.removeChild(b),"none"===e&&(e="block"),ea[d]=e,e)}function ga(a,b){for(var c,d,e=[],f=0,g=a.length;f<g;f++)d=a[f],d.style&&(c=d.style.display,b?("none"===c&&(e[f]=V.get(d,"display")||null,e[f]||(d.style.display="")),""===d.style.display&&ba(d)&&(e[f]=fa(d))):"none"!==c&&(e[f]="none",V.set(d,"display",c)));for(f=0;f<g;f++)null!=e[f]&&(a[f].style.display=e[f]);return a}r.fn.extend({show:function(){return ga(this,!0)},hide:function(){return ga(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){ba(this)?r(this).show():r(this).hide()})}});var ha=/^(?:checkbox|radio)$/i,ia=/<([a-z][^\/\0>\x20\t\r\n\f]+)/i,ja=/^$|\/(?:java|ecma)script/i,ka={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ka.optgroup=ka.option,ka.tbody=ka.tfoot=ka.colgroup=ka.caption=ka.thead,ka.th=ka.td;function la(a,b){var c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&r.nodeName(a,b)?r.merge([a],c):c}function ma(a,b){for(var c=0,d=a.length;c<d;c++)V.set(a[c],"globalEval",!b||V.get(b[c],"globalEval"))}var na=/<|&#?\w+;/;function oa(a,b,c,d,e){for(var f,g,h,i,j,k,l=b.createDocumentFragment(),m=[],n=0,o=a.length;n<o;n++)if(f=a[n],f||0===f)if("object"===r.type(f))r.merge(m,f.nodeType?[f]:f);else if(na.test(f)){g=g||l.appendChild(b.createElement("div")),h=(ia.exec(f)||["",""])[1].toLowerCase(),i=ka[h]||ka._default,g.innerHTML=i[1]+r.htmlPrefilter(f)+i[2],k=i[0];while(k--)g=g.lastChild;r.merge(m,g.childNodes),g=l.firstChild,g.textContent=""}else m.push(b.createTextNode(f));l.textContent="",n=0;while(f=m[n++])if(d&&r.inArray(f,d)>-1)e&&e.push(f);else if(j=r.contains(f.ownerDocument,f),g=la(l.appendChild(f),"script"),j&&ma(g),c){k=0;while(f=g[k++])ja.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),o.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",o.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var pa=d.documentElement,qa=/^key/,ra=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,sa=/^([^.]*)(?:\.(.+)|)/;function ta(){return!0}function ua(){return!1}function va(){try{return d.activeElement}catch(a){}}function wa(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)wa(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=ua;else if(!e)return a;return 1===f&&(g=e,e=function(a){return r().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=r.guid++)),a.each(function(){r.event.add(this,b,e,d,c)})}r.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=V.get(a);if(q){c.handler&&(f=c,c=f.handler,e=f.selector),e&&r.find.matchesSelector(pa,e),c.guid||(c.guid=r.guid++),(i=q.events)||(i=q.events={}),(g=q.handle)||(g=q.handle=function(b){return"undefined"!=typeof r&&r.event.triggered!==b.type?r.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(K)||[""],j=b.length;while(j--)h=sa.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n&&(l=r.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=r.event.special[n]||{},k=r.extend({type:n,origType:p,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&r.expr.match.needsContext.test(e),namespace:o.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,o,g)!==!1||a.addEventListener&&a.addEventListener(n,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),r.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=V.hasData(a)&&V.get(a);if(q&&(i=q.events)){b=(b||"").match(K)||[""],j=b.length;while(j--)if(h=sa.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n){l=r.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+o.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&p!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,o,q.handle)!==!1||r.removeEvent(a,n,q.handle),delete i[n])}else for(n in i)r.event.remove(a,n+b[j],c,d,!0);r.isEmptyObject(i)&&V.remove(a,"handle events")}},dispatch:function(a){var b=r.event.fix(a),c,d,e,f,g,h,i=new Array(arguments.length),j=(V.get(this,"events")||{})[b.type]||[],k=r.event.special[b.type]||{};for(i[0]=b,c=1;c<arguments.length;c++)i[c]=arguments[c];if(b.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,b)!==!1){h=r.event.handlers.call(this,b,j),c=0;while((f=h[c++])&&!b.isPropagationStopped()){b.currentTarget=f.elem,d=0;while((g=f.handlers[d++])&&!b.isImmediatePropagationStopped())b.rnamespace&&!b.rnamespace.test(g.namespace)||(b.handleObj=g,b.data=g.data,e=((r.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(b.result=e)===!1&&(b.preventDefault(),b.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,b),b.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!==this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(d=[],c=0;c<h;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?r(e,this).index(i)>-1:r.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},addProp:function(a,b){Object.defineProperty(r.Event.prototype,a,{enumerable:!0,configurable:!0,get:r.isFunction(b)?function(){if(this.originalEvent)return b(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[a]},set:function(b){Object.defineProperty(this,a,{enumerable:!0,configurable:!0,writable:!0,value:b})}})},fix:function(a){return a[r.expando]?a:new r.Event(a)},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==va()&&this.focus)return this.focus(),!1},delegateType:"focusin"},blur:{trigger:function(){if(this===va()&&this.blur)return this.blur(),!1},delegateType:"focusout"},click:{trigger:function(){if("checkbox"===this.type&&this.click&&r.nodeName(this,"input"))return this.click(),!1},_default:function(a){return r.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}}},r.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)},r.Event=function(a,b){return this instanceof r.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ta:ua,this.target=a.target&&3===a.target.nodeType?a.target.parentNode:a.target,this.currentTarget=a.currentTarget,this.relatedTarget=a.relatedTarget):this.type=a,b&&r.extend(this,b),this.timeStamp=a&&a.timeStamp||r.now(),void(this[r.expando]=!0)):new r.Event(a,b)},r.Event.prototype={constructor:r.Event,isDefaultPrevented:ua,isPropagationStopped:ua,isImmediatePropagationStopped:ua,isSimulated:!1,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ta,a&&!this.isSimulated&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ta,a&&!this.isSimulated&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ta,a&&!this.isSimulated&&a.stopImmediatePropagation(),this.stopPropagation()}},r.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,"char":!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:function(a){var b=a.button;return null==a.which&&qa.test(a.type)?null!=a.charCode?a.charCode:a.keyCode:!a.which&&void 0!==b&&ra.test(a.type)?1&b?1:2&b?3:4&b?2:0:a.which}},r.event.addProp),r.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){r.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||r.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),r.fn.extend({on:function(a,b,c,d){return wa(this,a,b,c,d)},one:function(a,b,c,d){return wa(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,r(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return b!==!1&&"function"!=typeof b||(c=b,b=void 0),c===!1&&(c=ua),this.each(function(){r.event.remove(this,a,c,b)})}});var xa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,ya=/<script|<style|<link/i,za=/checked\s*(?:[^=]|=\s*.checked.)/i,Aa=/^true\/(.*)/,Ba=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function Ca(a,b){return r.nodeName(a,"table")&&r.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a:a}function Da(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function Ea(a){var b=Aa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Fa(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(V.hasData(a)&&(f=V.access(a),g=V.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;c<d;c++)r.event.add(b,e,j[e][c])}W.hasData(a)&&(h=W.access(a),i=r.extend({},h),W.set(b,i))}}function Ga(a,b){var c=b.nodeName.toLowerCase();"input"===c&&ha.test(a.type)?b.checked=a.checked:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}function Ha(a,b,c,d){b=g.apply([],b);var e,f,h,i,j,k,l=0,m=a.length,n=m-1,q=b[0],s=r.isFunction(q);if(s||m>1&&"string"==typeof q&&!o.checkClone&&za.test(q))return a.each(function(e){var f=a.eq(e);s&&(b[0]=q.call(this,e,f.html())),Ha(f,b,c,d)});if(m&&(e=oa(b,a[0].ownerDocument,!1,a,d),f=e.firstChild,1===e.childNodes.length&&(e=f),f||d)){for(h=r.map(la(e,"script"),Da),i=h.length;l<m;l++)j=e,l!==n&&(j=r.clone(j,!0,!0),i&&r.merge(h,la(j,"script"))),c.call(a[l],j,l);if(i)for(k=h[h.length-1].ownerDocument,r.map(h,Ea),l=0;l<i;l++)j=h[l],ja.test(j.type||"")&&!V.access(j,"globalEval")&&r.contains(k,j)&&(j.src?r._evalUrl&&r._evalUrl(j.src):p(j.textContent.replace(Ba,""),k))}return a}function Ia(a,b,c){for(var d,e=b?r.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||r.cleanData(la(d)),d.parentNode&&(c&&r.contains(d.ownerDocument,d)&&ma(la(d,"script")),d.parentNode.removeChild(d));return a}r.extend({htmlPrefilter:function(a){return a.replace(xa,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=r.contains(a.ownerDocument,a);if(!(o.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||r.isXMLDoc(a)))for(g=la(h),f=la(a),d=0,e=f.length;d<e;d++)Ga(f[d],g[d]);if(b)if(c)for(f=f||la(a),g=g||la(h),d=0,e=f.length;d<e;d++)Fa(f[d],g[d]);else Fa(a,h);return g=la(h,"script"),g.length>0&&ma(g,!i&&la(a,"script")),h},cleanData:function(a){for(var b,c,d,e=r.event.special,f=0;void 0!==(c=a[f]);f++)if(T(c)){if(b=c[V.expando]){if(b.events)for(d in b.events)e[d]?r.event.remove(c,d):r.removeEvent(c,d,b.handle);c[V.expando]=void 0}c[W.expando]&&(c[W.expando]=void 0)}}}),r.fn.extend({detach:function(a){return Ia(this,a,!0)},remove:function(a){return Ia(this,a)},text:function(a){return S(this,function(a){return void 0===a?r.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.appendChild(a)}})},prepend:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(r.cleanData(la(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null!=a&&a,b=null==b?a:b,this.map(function(){return r.clone(this,a,b)})},html:function(a){return S(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!ya.test(a)&&!ka[(ia.exec(a)||["",""])[1].toLowerCase()]){a=r.htmlPrefilter(a);try{for(;c<d;c++)b=this[c]||{},1===b.nodeType&&(r.cleanData(la(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return Ha(this,arguments,function(b){var c=this.parentNode;r.inArray(this,a)<0&&(r.cleanData(la(this)),c&&c.replaceChild(b,this))},a)}}),r.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){r.fn[a]=function(a){for(var c,d=[],e=r(a),f=e.length-1,g=0;g<=f;g++)c=g===f?this:this.clone(!0),r(e[g])[b](c),h.apply(d,c.get());return this.pushStack(d)}});var Ja=/^margin/,Ka=new RegExp("^("+$+")(?!px)[a-z%]+$","i"),La=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)};!function(){function b(){if(i){i.style.cssText="box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",i.innerHTML="",pa.appendChild(h);var b=a.getComputedStyle(i);c="1%"!==b.top,g="2px"===b.marginLeft,e="4px"===b.width,i.style.marginRight="50%",f="4px"===b.marginRight,pa.removeChild(h),i=null}}var c,e,f,g,h=d.createElement("div"),i=d.createElement("div");i.style&&(i.style.backgroundClip="content-box",i.cloneNode(!0).style.backgroundClip="",o.clearCloneStyle="content-box"===i.style.backgroundClip,h.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",h.appendChild(i),r.extend(o,{pixelPosition:function(){return b(),c},boxSizingReliable:function(){return b(),e},pixelMarginRight:function(){return b(),f},reliableMarginLeft:function(){return b(),g}}))}();function Ma(a,b,c){var d,e,f,g,h=a.style;return c=c||La(a),c&&(g=c.getPropertyValue(b)||c[b],""!==g||r.contains(a.ownerDocument,a)||(g=r.style(a,b)),!o.pixelMarginRight()&&Ka.test(g)&&Ja.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0!==g?g+"":g}function Na(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Oa=/^(none|table(?!-c[ea]).+)/,Pa={position:"absolute",visibility:"hidden",display:"block"},Qa={letterSpacing:"0",fontWeight:"400"},Ra=["Webkit","Moz","ms"],Sa=d.createElement("div").style;function Ta(a){if(a in Sa)return a;var b=a[0].toUpperCase()+a.slice(1),c=Ra.length;while(c--)if(a=Ra[c]+b,a in Sa)return a}function Ua(a,b,c){var d=_.exec(b);return d?Math.max(0,d[2]-(c||0))+(d[3]||"px"):b}function Va(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;f<4;f+=2)"margin"===c&&(g+=r.css(a,c+aa[f],!0,e)),d?("content"===c&&(g-=r.css(a,"padding"+aa[f],!0,e)),"margin"!==c&&(g-=r.css(a,"border"+aa[f]+"Width",!0,e))):(g+=r.css(a,"padding"+aa[f],!0,e),"padding"!==c&&(g+=r.css(a,"border"+aa[f]+"Width",!0,e)));return g}function Wa(a,b,c){var d,e=!0,f=La(a),g="border-box"===r.css(a,"boxSizing",!1,f);if(a.getClientRects().length&&(d=a.getBoundingClientRect()[b]),d<=0||null==d){if(d=Ma(a,b,f),(d<0||null==d)&&(d=a.style[b]),Ka.test(d))return d;e=g&&(o.boxSizingReliable()||d===a.style[b]),d=parseFloat(d)||0}return d+Va(a,b,c||(g?"border":"content"),e,f)+"px"}r.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ma(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=r.camelCase(b),i=a.style;return b=r.cssProps[h]||(r.cssProps[h]=Ta(h)||h),g=r.cssHooks[b]||r.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=_.exec(c))&&e[1]&&(c=da(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(r.cssNumber[h]?"":"px")),o.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=r.camelCase(b);return b=r.cssProps[h]||(r.cssProps[h]=Ta(h)||h),g=r.cssHooks[b]||r.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=Ma(a,b,d)),"normal"===e&&b in Qa&&(e=Qa[b]),""===c||c?(f=parseFloat(e),c===!0||isFinite(f)?f||0:e):e}}),r.each(["height","width"],function(a,b){r.cssHooks[b]={get:function(a,c,d){if(c)return!Oa.test(r.css(a,"display"))||a.getClientRects().length&&a.getBoundingClientRect().width?Wa(a,b,d):ca(a,Pa,function(){return Wa(a,b,d)})},set:function(a,c,d){var e,f=d&&La(a),g=d&&Va(a,b,d,"border-box"===r.css(a,"boxSizing",!1,f),f);return g&&(e=_.exec(c))&&"px"!==(e[3]||"px")&&(a.style[b]=c,c=r.css(a,b)),Ua(a,c,g)}}}),r.cssHooks.marginLeft=Na(o.reliableMarginLeft,function(a,b){if(b)return(parseFloat(Ma(a,"marginLeft"))||a.getBoundingClientRect().left-ca(a,{marginLeft:0},function(){return a.getBoundingClientRect().left}))+"px"}),r.each({margin:"",padding:"",border:"Width"},function(a,b){r.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];d<4;d++)e[a+aa[d]+b]=f[d]||f[d-2]||f[0];return e}},Ja.test(a)||(r.cssHooks[a+b].set=Ua)}),r.fn.extend({css:function(a,b){return S(this,function(a,b,c){var d,e,f={},g=0;if(r.isArray(b)){for(d=La(a),e=b.length;g<e;g++)f[b[g]]=r.css(a,b[g],!1,d);return f}return void 0!==c?r.style(a,b,c):r.css(a,b)},a,b,arguments.length>1)}});function Xa(a,b,c,d,e){return new Xa.prototype.init(a,b,c,d,e)}r.Tween=Xa,Xa.prototype={constructor:Xa,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||r.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(r.cssNumber[c]?"":"px")},cur:function(){var a=Xa.propHooks[this.prop];return a&&a.get?a.get(this):Xa.propHooks._default.get(this)},run:function(a){var b,c=Xa.propHooks[this.prop];return this.options.duration?this.pos=b=r.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Xa.propHooks._default.set(this),this}},Xa.prototype.init.prototype=Xa.prototype,Xa.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=r.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){r.fx.step[a.prop]?r.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[r.cssProps[a.prop]]&&!r.cssHooks[a.prop]?a.elem[a.prop]=a.now:r.style(a.elem,a.prop,a.now+a.unit)}}},Xa.propHooks.scrollTop=Xa.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},r.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},r.fx=Xa.prototype.init,r.fx.step={};var Ya,Za,$a=/^(?:toggle|show|hide)$/,_a=/queueHooks$/;function ab(){Za&&(a.requestAnimationFrame(ab),r.fx.tick())}function bb(){return a.setTimeout(function(){Ya=void 0}),Ya=r.now()}function cb(a,b){var c,d=0,e={height:a};for(b=b?1:0;d<4;d+=2-b)c=aa[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function db(a,b,c){for(var d,e=(gb.tweeners[b]||[]).concat(gb.tweeners["*"]),f=0,g=e.length;f<g;f++)if(d=e[f].call(c,b,a))return d}function eb(a,b,c){var d,e,f,g,h,i,j,k,l="width"in b||"height"in b,m=this,n={},o=a.style,p=a.nodeType&&ba(a),q=V.get(a,"fxshow");c.queue||(g=r._queueHooks(a,"fx"),null==g.unqueued&&(g.unqueued=0,h=g.empty.fire,g.empty.fire=function(){g.unqueued||h()}),g.unqueued++,m.always(function(){m.always(function(){g.unqueued--,r.queue(a,"fx").length||g.empty.fire()})}));for(d in b)if(e=b[d],$a.test(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}n[d]=q&&q[d]||r.style(a,d)}if(i=!r.isEmptyObject(b),i||!r.isEmptyObject(n)){l&&1===a.nodeType&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=q&&q.display,null==j&&(j=V.get(a,"display")),k=r.css(a,"display"),"none"===k&&(j?k=j:(ga([a],!0),j=a.style.display||j,k=r.css(a,"display"),ga([a]))),("inline"===k||"inline-block"===k&&null!=j)&&"none"===r.css(a,"float")&&(i||(m.done(function(){o.display=j}),null==j&&(k=o.display,j="none"===k?"":k)),o.display="inline-block")),c.overflow&&(o.overflow="hidden",m.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]})),i=!1;for(d in n)i||(q?"hidden"in q&&(p=q.hidden):q=V.access(a,"fxshow",{display:j}),f&&(q.hidden=!p),p&&ga([a],!0),m.done(function(){p||ga([a]),V.remove(a,"fxshow");for(d in n)r.style(a,d,n[d])})),i=db(p?q[d]:0,d,m),d in q||(q[d]=i.start,p&&(i.end=i.start,i.start=0))}}function fb(a,b){var c,d,e,f,g;for(c in a)if(d=r.camelCase(c),e=b[d],f=a[c],r.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=r.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function gb(a,b,c){var d,e,f=0,g=gb.prefilters.length,h=r.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Ya||bb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;g<i;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),f<1&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:r.extend({},b),opts:r.extend(!0,{specialEasing:{},easing:r.easing._default},c),originalProperties:b,originalOptions:c,startTime:Ya||bb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=r.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;c<d;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for(fb(k,j.opts.specialEasing);f<g;f++)if(d=gb.prefilters[f].call(j,a,k,j.opts))return r.isFunction(d.stop)&&(r._queueHooks(j.elem,j.opts.queue).stop=r.proxy(d.stop,d)),d;return r.map(k,db,j),r.isFunction(j.opts.start)&&j.opts.start.call(a,j),r.fx.timer(r.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}r.Animation=r.extend(gb,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return da(c.elem,a,_.exec(b),c),c}]},tweener:function(a,b){r.isFunction(a)?(b=a,a=["*"]):a=a.match(K);for(var c,d=0,e=a.length;d<e;d++)c=a[d],gb.tweeners[c]=gb.tweeners[c]||[],gb.tweeners[c].unshift(b)},prefilters:[eb],prefilter:function(a,b){b?gb.prefilters.unshift(a):gb.prefilters.push(a)}}),r.speed=function(a,b,c){var e=a&&"object"==typeof a?r.extend({},a):{complete:c||!c&&b||r.isFunction(a)&&a,duration:a,easing:c&&b||b&&!r.isFunction(b)&&b};return r.fx.off||d.hidden?e.duration=0:e.duration="number"==typeof e.duration?e.duration:e.duration in r.fx.speeds?r.fx.speeds[e.duration]:r.fx.speeds._default,null!=e.queue&&e.queue!==!0||(e.queue="fx"),e.old=e.complete,e.complete=function(){r.isFunction(e.old)&&e.old.call(this),e.queue&&r.dequeue(this,e.queue)},e},r.fn.extend({fadeTo:function(a,b,c,d){return this.filter(ba).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=r.isEmptyObject(a),f=r.speed(b,c,d),g=function(){var b=gb(this,r.extend({},a),f);(e||V.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=r.timers,g=V.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&_a.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||r.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=V.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=r.timers,g=d?d.length:0;for(c.finish=!0,r.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;b<g;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),r.each(["toggle","show","hide"],function(a,b){var c=r.fn[b];r.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(cb(b,!0),a,d,e)}}),r.each({slideDown:cb("show"),slideUp:cb("hide"),slideToggle:cb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){r.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),r.timers=[],r.fx.tick=function(){var a,b=0,c=r.timers;for(Ya=r.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||r.fx.stop(),Ya=void 0},r.fx.timer=function(a){r.timers.push(a),a()?r.fx.start():r.timers.pop()},r.fx.interval=13,r.fx.start=function(){Za||(Za=a.requestAnimationFrame?a.requestAnimationFrame(ab):a.setInterval(r.fx.tick,r.fx.interval))},r.fx.stop=function(){a.cancelAnimationFrame?a.cancelAnimationFrame(Za):a.clearInterval(Za),Za=null},r.fx.speeds={slow:600,fast:200,_default:400},r.fn.delay=function(b,c){return b=r.fx?r.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a=d.createElement("input"),b=d.createElement("select"),c=b.appendChild(d.createElement("option"));a.type="checkbox",o.checkOn=""!==a.value,o.optSelected=c.selected,a=d.createElement("input"),a.value="t",a.type="radio",o.radioValue="t"===a.value}();var hb,ib=r.expr.attrHandle;r.fn.extend({attr:function(a,b){return S(this,r.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){r.removeAttr(this,a)})}}),r.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?r.prop(a,b,c):(1===f&&r.isXMLDoc(a)||(e=r.attrHooks[b.toLowerCase()]||(r.expr.match.bool.test(b)?hb:void 0)),void 0!==c?null===c?void r.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=r.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!o.radioValue&&"radio"===b&&r.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d=0,e=b&&b.match(K); if(e&&1===a.nodeType)while(c=e[d++])a.removeAttribute(c)}}),hb={set:function(a,b,c){return b===!1?r.removeAttr(a,c):a.setAttribute(c,c),c}},r.each(r.expr.match.bool.source.match(/\w+/g),function(a,b){var c=ib[b]||r.find.attr;ib[b]=function(a,b,d){var e,f,g=b.toLowerCase();return d||(f=ib[g],ib[g]=e,e=null!=c(a,b,d)?g:null,ib[g]=f),e}});var jb=/^(?:input|select|textarea|button)$/i,kb=/^(?:a|area)$/i;r.fn.extend({prop:function(a,b){return S(this,r.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[r.propFix[a]||a]})}}),r.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&r.isXMLDoc(a)||(b=r.propFix[b]||b,e=r.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=r.find.attr(a,"tabindex");return b?parseInt(b,10):jb.test(a.nodeName)||kb.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),o.optSelected||(r.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),r.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){r.propFix[this.toLowerCase()]=this});var lb=/[\t\r\n\f]/g;function mb(a){return a.getAttribute&&a.getAttribute("class")||""}r.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).addClass(a.call(this,b,mb(this)))});if("string"==typeof a&&a){b=a.match(K)||[];while(c=this[i++])if(e=mb(c),d=1===c.nodeType&&(" "+e+" ").replace(lb," ")){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=r.trim(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).removeClass(a.call(this,b,mb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(K)||[];while(c=this[i++])if(e=mb(c),d=1===c.nodeType&&(" "+e+" ").replace(lb," ")){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=r.trim(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):r.isFunction(a)?this.each(function(c){r(this).toggleClass(a.call(this,c,mb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=r(this),f=a.match(K)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=mb(this),b&&V.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":V.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+mb(c)+" ").replace(lb," ").indexOf(b)>-1)return!0;return!1}});var nb=/\r/g,ob=/[\x20\t\r\n\f]+/g;r.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=r.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,r(this).val()):a,null==e?e="":"number"==typeof e?e+="":r.isArray(e)&&(e=r.map(e,function(a){return null==a?"":a+""})),b=r.valHooks[this.type]||r.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=r.valHooks[e.type]||r.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(nb,""):null==c?"":c)}}}),r.extend({valHooks:{option:{get:function(a){var b=r.find.attr(a,"value");return null!=b?b:r.trim(r.text(a)).replace(ob," ")}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type,g=f?null:[],h=f?e+1:d.length,i=e<0?h:f?e:0;i<h;i++)if(c=d[i],(c.selected||i===e)&&!c.disabled&&(!c.parentNode.disabled||!r.nodeName(c.parentNode,"optgroup"))){if(b=r(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=r.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=r.inArray(r.valHooks.option.get(d),f)>-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),r.each(["radio","checkbox"],function(){r.valHooks[this]={set:function(a,b){if(r.isArray(b))return a.checked=r.inArray(r(a).val(),b)>-1}},o.checkOn||(r.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var pb=/^(?:focusinfocus|focusoutblur)$/;r.extend(r.event,{trigger:function(b,c,e,f){var g,h,i,j,k,m,n,o=[e||d],p=l.call(b,"type")?b.type:b,q=l.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!pb.test(p+r.event.triggered)&&(p.indexOf(".")>-1&&(q=p.split("."),p=q.shift(),q.sort()),k=p.indexOf(":")<0&&"on"+p,b=b[r.expando]?b:new r.Event(p,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=q.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:r.makeArray(c,[b]),n=r.event.special[p]||{},f||!n.trigger||n.trigger.apply(e,c)!==!1)){if(!f&&!n.noBubble&&!r.isWindow(e)){for(j=n.delegateType||p,pb.test(j+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),i=h;i===(e.ownerDocument||d)&&o.push(i.defaultView||i.parentWindow||a)}g=0;while((h=o[g++])&&!b.isPropagationStopped())b.type=g>1?j:n.bindType||p,m=(V.get(h,"events")||{})[b.type]&&V.get(h,"handle"),m&&m.apply(h,c),m=k&&h[k],m&&m.apply&&T(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=p,f||b.isDefaultPrevented()||n._default&&n._default.apply(o.pop(),c)!==!1||!T(e)||k&&r.isFunction(e[p])&&!r.isWindow(e)&&(i=e[k],i&&(e[k]=null),r.event.triggered=p,e[p](),r.event.triggered=void 0,i&&(e[k]=i)),b.result}},simulate:function(a,b,c){var d=r.extend(new r.Event,c,{type:a,isSimulated:!0});r.event.trigger(d,null,b)}}),r.fn.extend({trigger:function(a,b){return this.each(function(){r.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];if(c)return r.event.trigger(a,b,c,!0)}}),r.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(a,b){r.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),r.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),o.focusin="onfocusin"in a,o.focusin||r.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){r.event.simulate(b,a.target,r.event.fix(a))};r.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=V.access(d,b);e||d.addEventListener(a,c,!0),V.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=V.access(d,b)-1;e?V.access(d,b,e):(d.removeEventListener(a,c,!0),V.remove(d,b))}}});var qb=a.location,rb=r.now(),sb=/\?/;r.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||r.error("Invalid XML: "+b),c};var tb=/\[\]$/,ub=/\r?\n/g,vb=/^(?:submit|button|image|reset|file)$/i,wb=/^(?:input|select|textarea|keygen)/i;function xb(a,b,c,d){var e;if(r.isArray(b))r.each(b,function(b,e){c||tb.test(a)?d(a,e):xb(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==r.type(b))d(a,b);else for(e in b)xb(a+"["+e+"]",b[e],c,d)}r.param=function(a,b){var c,d=[],e=function(a,b){var c=r.isFunction(b)?b():b;d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(null==c?"":c)};if(r.isArray(a)||a.jquery&&!r.isPlainObject(a))r.each(a,function(){e(this.name,this.value)});else for(c in a)xb(c,a[c],b,e);return d.join("&")},r.fn.extend({serialize:function(){return r.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=r.prop(this,"elements");return a?r.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!r(this).is(":disabled")&&wb.test(this.nodeName)&&!vb.test(a)&&(this.checked||!ha.test(a))}).map(function(a,b){var c=r(this).val();return null==c?null:r.isArray(c)?r.map(c,function(a){return{name:b.name,value:a.replace(ub,"\r\n")}}):{name:b.name,value:c.replace(ub,"\r\n")}}).get()}});var yb=/%20/g,zb=/#.*$/,Ab=/([?&])_=[^&]*/,Bb=/^(.*?):[ \t]*([^\r\n]*)$/gm,Cb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Db=/^(?:GET|HEAD)$/,Eb=/^\/\//,Fb={},Gb={},Hb="*/".concat("*"),Ib=d.createElement("a");Ib.href=qb.href;function Jb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(K)||[];if(r.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Kb(a,b,c,d){var e={},f=a===Gb;function g(h){var i;return e[h]=!0,r.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Lb(a,b){var c,d,e=r.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&r.extend(!0,a,d),a}function Mb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}if(f)return f!==i[0]&&i.unshift(f),c[f]}function Nb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}r.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:qb.href,type:"GET",isLocal:Cb.test(qb.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Hb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":r.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Lb(Lb(a,r.ajaxSettings),b):Lb(r.ajaxSettings,a)},ajaxPrefilter:Jb(Fb),ajaxTransport:Jb(Gb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m,n,o=r.ajaxSetup({},c),p=o.context||o,q=o.context&&(p.nodeType||p.jquery)?r(p):r.event,s=r.Deferred(),t=r.Callbacks("once memory"),u=o.statusCode||{},v={},w={},x="canceled",y={readyState:0,getResponseHeader:function(a){var b;if(k){if(!h){h={};while(b=Bb.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return k?g:null},setRequestHeader:function(a,b){return null==k&&(a=w[a.toLowerCase()]=w[a.toLowerCase()]||a,v[a]=b),this},overrideMimeType:function(a){return null==k&&(o.mimeType=a),this},statusCode:function(a){var b;if(a)if(k)y.always(a[y.status]);else for(b in a)u[b]=[u[b],a[b]];return this},abort:function(a){var b=a||x;return e&&e.abort(b),A(0,b),this}};if(s.promise(y),o.url=((b||o.url||qb.href)+"").replace(Eb,qb.protocol+"//"),o.type=c.method||c.type||o.method||o.type,o.dataTypes=(o.dataType||"*").toLowerCase().match(K)||[""],null==o.crossDomain){j=d.createElement("a");try{j.href=o.url,j.href=j.href,o.crossDomain=Ib.protocol+"//"+Ib.host!=j.protocol+"//"+j.host}catch(z){o.crossDomain=!0}}if(o.data&&o.processData&&"string"!=typeof o.data&&(o.data=r.param(o.data,o.traditional)),Kb(Fb,o,c,y),k)return y;l=r.event&&o.global,l&&0===r.active++&&r.event.trigger("ajaxStart"),o.type=o.type.toUpperCase(),o.hasContent=!Db.test(o.type),f=o.url.replace(zb,""),o.hasContent?o.data&&o.processData&&0===(o.contentType||"").indexOf("application/x-www-form-urlencoded")&&(o.data=o.data.replace(yb,"+")):(n=o.url.slice(f.length),o.data&&(f+=(sb.test(f)?"&":"?")+o.data,delete o.data),o.cache===!1&&(f=f.replace(Ab,""),n=(sb.test(f)?"&":"?")+"_="+rb++ +n),o.url=f+n),o.ifModified&&(r.lastModified[f]&&y.setRequestHeader("If-Modified-Since",r.lastModified[f]),r.etag[f]&&y.setRequestHeader("If-None-Match",r.etag[f])),(o.data&&o.hasContent&&o.contentType!==!1||c.contentType)&&y.setRequestHeader("Content-Type",o.contentType),y.setRequestHeader("Accept",o.dataTypes[0]&&o.accepts[o.dataTypes[0]]?o.accepts[o.dataTypes[0]]+("*"!==o.dataTypes[0]?", "+Hb+"; q=0.01":""):o.accepts["*"]);for(m in o.headers)y.setRequestHeader(m,o.headers[m]);if(o.beforeSend&&(o.beforeSend.call(p,y,o)===!1||k))return y.abort();if(x="abort",t.add(o.complete),y.done(o.success),y.fail(o.error),e=Kb(Gb,o,c,y)){if(y.readyState=1,l&&q.trigger("ajaxSend",[y,o]),k)return y;o.async&&o.timeout>0&&(i=a.setTimeout(function(){y.abort("timeout")},o.timeout));try{k=!1,e.send(v,A)}catch(z){if(k)throw z;A(-1,z)}}else A(-1,"No Transport");function A(b,c,d,h){var j,m,n,v,w,x=c;k||(k=!0,i&&a.clearTimeout(i),e=void 0,g=h||"",y.readyState=b>0?4:0,j=b>=200&&b<300||304===b,d&&(v=Mb(o,y,d)),v=Nb(o,v,y,j),j?(o.ifModified&&(w=y.getResponseHeader("Last-Modified"),w&&(r.lastModified[f]=w),w=y.getResponseHeader("etag"),w&&(r.etag[f]=w)),204===b||"HEAD"===o.type?x="nocontent":304===b?x="notmodified":(x=v.state,m=v.data,n=v.error,j=!n)):(n=x,!b&&x||(x="error",b<0&&(b=0))),y.status=b,y.statusText=(c||x)+"",j?s.resolveWith(p,[m,x,y]):s.rejectWith(p,[y,x,n]),y.statusCode(u),u=void 0,l&&q.trigger(j?"ajaxSuccess":"ajaxError",[y,o,j?m:n]),t.fireWith(p,[y,x]),l&&(q.trigger("ajaxComplete",[y,o]),--r.active||r.event.trigger("ajaxStop")))}return y},getJSON:function(a,b,c){return r.get(a,b,c,"json")},getScript:function(a,b){return r.get(a,void 0,b,"script")}}),r.each(["get","post"],function(a,b){r[b]=function(a,c,d,e){return r.isFunction(c)&&(e=e||d,d=c,c=void 0),r.ajax(r.extend({url:a,type:b,dataType:e,data:c,success:d},r.isPlainObject(a)&&a))}}),r._evalUrl=function(a){return r.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},r.fn.extend({wrapAll:function(a){var b;return this[0]&&(r.isFunction(a)&&(a=a.call(this[0])),b=r(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this},wrapInner:function(a){return r.isFunction(a)?this.each(function(b){r(this).wrapInner(a.call(this,b))}):this.each(function(){var b=r(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=r.isFunction(a);return this.each(function(c){r(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(a){return this.parent(a).not("body").each(function(){r(this).replaceWith(this.childNodes)}),this}}),r.expr.pseudos.hidden=function(a){return!r.expr.pseudos.visible(a)},r.expr.pseudos.visible=function(a){return!!(a.offsetWidth||a.offsetHeight||a.getClientRects().length)},r.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Ob={0:200,1223:204},Pb=r.ajaxSettings.xhr();o.cors=!!Pb&&"withCredentials"in Pb,o.ajax=Pb=!!Pb,r.ajaxTransport(function(b){var c,d;if(o.cors||Pb&&!b.crossDomain)return{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Ob[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}}),r.ajaxPrefilter(function(a){a.crossDomain&&(a.contents.script=!1)}),r.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return r.globalEval(a),a}}}),r.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),r.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=r("<script>").prop({charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&f("error"===a.type?404:200,a.type)}),d.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Qb=[],Rb=/(=)\?(?=&|$)|\?\?/;r.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Qb.pop()||r.expando+"_"+rb++;return this[a]=!0,a}}),r.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Rb.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Rb.test(b.data)&&"data");if(h||"jsonp"===b.dataTypes[0])return e=b.jsonpCallback=r.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Rb,"$1"+e):b.jsonp!==!1&&(b.url+=(sb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||r.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?r(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Qb.push(e)),g&&r.isFunction(f)&&f(g[0]),g=f=void 0}),"script"}),o.createHTMLDocument=function(){var a=d.implementation.createHTMLDocument("").body;return a.innerHTML="<form></form><form></form>",2===a.childNodes.length}(),r.parseHTML=function(a,b,c){if("string"!=typeof a)return[];"boolean"==typeof b&&(c=b,b=!1);var e,f,g;return b||(o.createHTMLDocument?(b=d.implementation.createHTMLDocument(""),e=b.createElement("base"),e.href=d.location.href,b.head.appendChild(e)):b=d),f=B.exec(a),g=!c&&[],f?[b.createElement(f[1])]:(f=oa([a],b,g),g&&g.length&&r(g).remove(),r.merge([],f.childNodes))},r.fn.load=function(a,b,c){var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=r.trim(a.slice(h)),a=a.slice(0,h)),r.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&r.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?r("<div>").append(r.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(this,f||[a.responseText,b,a])})}),this},r.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){r.fn[b]=function(a){return this.on(b,a)}}),r.expr.pseudos.animated=function(a){return r.grep(r.timers,function(b){return a===b.elem}).length};function Sb(a){return r.isWindow(a)?a:9===a.nodeType&&a.defaultView}r.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=r.css(a,"position"),l=r(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=r.css(a,"top"),i=r.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),r.isFunction(b)&&(b=b.call(a,c,r.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},r.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){r.offset.setOffset(this,a,b)});var b,c,d,e,f=this[0];if(f)return f.getClientRects().length?(d=f.getBoundingClientRect(),d.width||d.height?(e=f.ownerDocument,c=Sb(e),b=e.documentElement,{top:d.top+c.pageYOffset-b.clientTop,left:d.left+c.pageXOffset-b.clientLeft}):d):{top:0,left:0}},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===r.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),r.nodeName(a[0],"html")||(d=a.offset()),d={top:d.top+r.css(a[0],"borderTopWidth",!0),left:d.left+r.css(a[0],"borderLeftWidth",!0)}),{top:b.top-d.top-r.css(c,"marginTop",!0),left:b.left-d.left-r.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&"static"===r.css(a,"position"))a=a.offsetParent;return a||pa})}}),r.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c="pageYOffset"===b;r.fn[a]=function(d){return S(this,function(a,d,e){var f=Sb(a);return void 0===e?f?f[b]:a[d]:void(f?f.scrollTo(c?f.pageXOffset:e,c?e:f.pageYOffset):a[d]=e)},a,d,arguments.length)}}),r.each(["top","left"],function(a,b){r.cssHooks[b]=Na(o.pixelPosition,function(a,c){if(c)return c=Ma(a,b),Ka.test(c)?r(a).position()[b]+"px":c})}),r.each({Height:"height",Width:"width"},function(a,b){r.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){r.fn[d]=function(e,f){var g=arguments.length&&(c||"boolean"!=typeof e),h=c||(e===!0||f===!0?"margin":"border");return S(this,function(b,c,e){var f;return r.isWindow(b)?0===d.indexOf("outer")?b["inner"+a]:b.document.documentElement["client"+a]:9===b.nodeType?(f=b.documentElement,Math.max(b.body["scroll"+a],f["scroll"+a],b.body["offset"+a],f["offset"+a],f["client"+a])):void 0===e?r.css(b,c,h):r.style(b,c,e,h)},b,g?e:void 0,g)}})}),r.fn.extend({bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}}),r.parseJSON=JSON.parse,"function"==typeof define&&define.amd&&define("jquery",[],function(){return r});var Tb=a.jQuery,Ub=a.$;return r.noConflict=function(b){return a.$===r&&(a.$=Ub),b&&a.jQuery===r&&(a.jQuery=Tb),r},b||(a.jQuery=a.$=r),r}); ```
/content/code_sandbox/public/vendor/datetimepicker/demo/jquery-3.1.0.min.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
29,076
```javascript /* your_sha256_hash------------- Zepto 1.1.6 Custom Build Includes following Modules 1. zepto 2. event 3. ajax 4. form 5. ie 6. fx 7. fx_methods 8. data your_sha256_hash------------- */ var Zepto=function(){function a(a){return null==a?String(a):W[X.call(a)]||"object"}function b(b){return"function"==a(b)}function c(a){return null!=a&&a==a.window}function d(a){return null!=a&&a.nodeType==a.DOCUMENT_NODE}function e(b){return"object"==a(b)}function f(a){return e(a)&&!c(a)&&Object.getPrototypeOf(a)==Object.prototype}function g(a){return"number"==typeof a.length}function h(a){return E.call(a,function(a){return null!=a})}function i(a){return a.length>0?y.fn.concat.apply([],a):a}function j(a){return a.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function k(a){return a in I?I[a]:I[a]=new RegExp("(^|\\s)"+a+"(\\s|$)")}function l(a,b){return"number"!=typeof b||J[j(a)]?b:b+"px"}function m(a){var b,c;return H[a]||(b=G.createElement(a),G.body.appendChild(b),c=getComputedStyle(b,"").getPropertyValue("display"),b.parentNode.removeChild(b),"none"==c&&(c="block"),H[a]=c),H[a]}function n(a){return"children"in a?F.call(a.children):y.map(a.childNodes,function(a){return 1==a.nodeType?a:void 0})}function o(a,b){var c,d=a?a.length:0;for(c=0;d>c;c++)this[c]=a[c];this.length=d,this.selector=b||""}function p(a,b,c){for(x in b)c&&(f(b[x])||_(b[x]))?(f(b[x])&&!f(a[x])&&(a[x]={}),_(b[x])&&!_(a[x])&&(a[x]=[]),p(a[x],b[x],c)):b[x]!==w&&(a[x]=b[x])}function q(a,b){return null==b?y(a):y(a).filter(b)}function r(a,c,d,e){return b(c)?c.call(a,d,e):c}function s(a,b,c){null==c?a.removeAttribute(b):a.setAttribute(b,c)}function t(a,b){var c=a.className||"",d=c&&c.baseVal!==w;return b===w?d?c.baseVal:c:void(d?c.baseVal=b:a.className=b)}function u(a){try{return a?"true"==a||("false"==a?!1:"null"==a?null:+a+""==a?+a:/^[\[\{]/.test(a)?y.parseJSON(a):a):a}catch(b){return a}}function v(a,b){b(a);for(var c=0,d=a.childNodes.length;d>c;c++)v(a.childNodes[c],b)}var w,x,y,z,A,B,C=[],D=C.concat,E=C.filter,F=C.slice,G=window.document,H={},I={},J={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},K=/^\s*<(\w+|!)[^>]*>/,L=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,M=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,N=/^(?:body|html)$/i,O=/([A-Z])/g,P=["val","css","html","text","data","width","height","offset"],Q=["after","prepend","before","append"],R=G.createElement("table"),S=G.createElement("tr"),T={tr:G.createElement("tbody"),tbody:R,thead:R,tfoot:R,td:S,th:S,"*":G.createElement("div")},U=/complete|loaded|interactive/,V=/^[\w-]*$/,W={},X=W.toString,Y={},Z=G.createElement("div"),$={tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},_=Array.isArray||function(a){return a instanceof Array};return Y.matches=function(a,b){if(!b||!a||1!==a.nodeType)return!1;var c=a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.matchesSelector;if(c)return c.call(a,b);var d,e=a.parentNode,f=!e;return f&&(e=Z).appendChild(a),d=~Y.qsa(e,b).indexOf(a),f&&Z.removeChild(a),d},A=function(a){return a.replace(/-+(.)?/g,function(a,b){return b?b.toUpperCase():""})},B=function(a){return E.call(a,function(b,c){return a.indexOf(b)==c})},Y.fragment=function(a,b,c){var d,e,g;return L.test(a)&&(d=y(G.createElement(RegExp.$1))),d||(a.replace&&(a=a.replace(M,"<$1></$2>")),b===w&&(b=K.test(a)&&RegExp.$1),b in T||(b="*"),g=T[b],g.innerHTML=""+a,d=y.each(F.call(g.childNodes),function(){g.removeChild(this)})),f(c)&&(e=y(d),y.each(c,function(a,b){P.indexOf(a)>-1?e[a](b):e.attr(a,b)})),d},Y.Z=function(a,b){return new o(a,b)},Y.isZ=function(a){return a instanceof Y.Z},Y.init=function(a,c){var d;if(!a)return Y.Z();if("string"==typeof a)if(a=a.trim(),"<"==a[0]&&K.test(a))d=Y.fragment(a,RegExp.$1,c),a=null;else{if(c!==w)return y(c).find(a);d=Y.qsa(G,a)}else{if(b(a))return y(G).ready(a);if(Y.isZ(a))return a;if(_(a))d=h(a);else if(e(a))d=[a],a=null;else if(K.test(a))d=Y.fragment(a.trim(),RegExp.$1,c),a=null;else{if(c!==w)return y(c).find(a);d=Y.qsa(G,a)}}return Y.Z(d,a)},y=function(a,b){return Y.init(a,b)},y.extend=function(a){var b,c=F.call(arguments,1);return"boolean"==typeof a&&(b=a,a=c.shift()),c.forEach(function(c){p(a,c,b)}),a},Y.qsa=function(a,b){var c,d="#"==b[0],e=!d&&"."==b[0],f=d||e?b.slice(1):b,g=V.test(f);return a.getElementById&&g&&d?(c=a.getElementById(f))?[c]:[]:1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType?[]:F.call(g&&!d&&a.getElementsByClassName?e?a.getElementsByClassName(f):a.getElementsByTagName(b):a.querySelectorAll(b))},y.contains=G.documentElement.contains?function(a,b){return a!==b&&a.contains(b)}:function(a,b){for(;b&&(b=b.parentNode);)if(b===a)return!0;return!1},y.type=a,y.isFunction=b,y.isWindow=c,y.isArray=_,y.isPlainObject=f,y.isEmptyObject=function(a){var b;for(b in a)return!1;return!0},y.inArray=function(a,b,c){return C.indexOf.call(b,a,c)},y.camelCase=A,y.trim=function(a){return null==a?"":String.prototype.trim.call(a)},y.uuid=0,y.support={},y.expr={},y.noop=function(){},y.map=function(a,b){var c,d,e,f=[];if(g(a))for(d=0;d<a.length;d++)c=b(a[d],d),null!=c&&f.push(c);else for(e in a)c=b(a[e],e),null!=c&&f.push(c);return i(f)},y.each=function(a,b){var c,d;if(g(a)){for(c=0;c<a.length;c++)if(b.call(a[c],c,a[c])===!1)return a}else for(d in a)if(b.call(a[d],d,a[d])===!1)return a;return a},y.grep=function(a,b){return E.call(a,b)},window.JSON&&(y.parseJSON=JSON.parse),y.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){W["[object "+b+"]"]=b.toLowerCase()}),y.fn={constructor:Y.Z,length:0,forEach:C.forEach,reduce:C.reduce,push:C.push,sort:C.sort,splice:C.splice,indexOf:C.indexOf,concat:function(){var a,b,c=[];for(a=0;a<arguments.length;a++)b=arguments[a],c[a]=Y.isZ(b)?b.toArray():b;return D.apply(Y.isZ(this)?this.toArray():this,c)},map:function(a){return y(y.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return y(F.apply(this,arguments))},ready:function(a){return U.test(G.readyState)&&G.body?a(y):G.addEventListener("DOMContentLoaded",function(){a(y)},!1),this},get:function(a){return a===w?F.call(this):this[a>=0?a:a+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){null!=this.parentNode&&this.parentNode.removeChild(this)})},each:function(a){return C.every.call(this,function(b,c){return a.call(b,c,b)!==!1}),this},filter:function(a){return b(a)?this.not(this.not(a)):y(E.call(this,function(b){return Y.matches(b,a)}))},add:function(a,b){return y(B(this.concat(y(a,b))))},is:function(a){return this.length>0&&Y.matches(this[0],a)},not:function(a){var c=[];if(b(a)&&a.call!==w)this.each(function(b){a.call(this,b)||c.push(this)});else{var d="string"==typeof a?this.filter(a):g(a)&&b(a.item)?F.call(a):y(a);this.forEach(function(a){d.indexOf(a)<0&&c.push(a)})}return y(c)},has:function(a){return this.filter(function(){return e(a)?y.contains(this,a):y(this).find(a).size()})},eq:function(a){return-1===a?this.slice(a):this.slice(a,+a+1)},first:function(){var a=this[0];return a&&!e(a)?a:y(a)},last:function(){var a=this[this.length-1];return a&&!e(a)?a:y(a)},find:function(a){var b,c=this;return b=a?"object"==typeof a?y(a).filter(function(){var a=this;return C.some.call(c,function(b){return y.contains(b,a)})}):1==this.length?y(Y.qsa(this[0],a)):this.map(function(){return Y.qsa(this,a)}):y()},closest:function(a,b){var c=this[0],e=!1;for("object"==typeof a&&(e=y(a));c&&!(e?e.indexOf(c)>=0:Y.matches(c,a));)c=c!==b&&!d(c)&&c.parentNode;return y(c)},parents:function(a){for(var b=[],c=this;c.length>0;)c=y.map(c,function(a){return(a=a.parentNode)&&!d(a)&&b.indexOf(a)<0?(b.push(a),a):void 0});return q(b,a)},parent:function(a){return q(B(this.pluck("parentNode")),a)},children:function(a){return q(this.map(function(){return n(this)}),a)},contents:function(){return this.map(function(){return this.contentDocument||F.call(this.childNodes)})},siblings:function(a){return q(this.map(function(a,b){return E.call(n(b.parentNode),function(a){return a!==b})}),a)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(a){return y.map(this,function(b){return b[a]})},show:function(){return this.each(function(){"none"==this.style.display&&(this.style.display=""),"none"==getComputedStyle(this,"").getPropertyValue("display")&&(this.style.display=m(this.nodeName))})},replaceWith:function(a){return this.before(a).remove()},wrap:function(a){var c=b(a);if(this[0]&&!c)var d=y(a).get(0),e=d.parentNode||this.length>1;return this.each(function(b){y(this).wrapAll(c?a.call(this,b):e?d.cloneNode(!0):d)})},wrapAll:function(a){if(this[0]){y(this[0]).before(a=y(a));for(var b;(b=a.children()).length;)a=b.first();y(a).append(this)}return this},wrapInner:function(a){var c=b(a);return this.each(function(b){var d=y(this),e=d.contents(),f=c?a.call(this,b):a;e.length?e.wrapAll(f):d.append(f)})},unwrap:function(){return this.parent().each(function(){y(this).replaceWith(y(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(a){return this.each(function(){var b=y(this);(a===w?"none"==b.css("display"):a)?b.show():b.hide()})},prev:function(a){return y(this.pluck("previousElementSibling")).filter(a||"*")},next:function(a){return y(this.pluck("nextElementSibling")).filter(a||"*")},html:function(a){return 0 in arguments?this.each(function(b){var c=this.innerHTML;y(this).empty().append(r(this,a,b,c))}):0 in this?this[0].innerHTML:null},text:function(a){return 0 in arguments?this.each(function(b){var c=r(this,a,b,this.textContent);this.textContent=null==c?"":""+c}):0 in this?this[0].textContent:null},attr:function(a,b){var c;return"string"!=typeof a||1 in arguments?this.each(function(c){if(1===this.nodeType)if(e(a))for(x in a)s(this,x,a[x]);else s(this,a,r(this,b,c,this.getAttribute(a)))}):this.length&&1===this[0].nodeType?!(c=this[0].getAttribute(a))&&a in this[0]?this[0][a]:c:w},removeAttr:function(a){return this.each(function(){1===this.nodeType&&a.split(" ").forEach(function(a){s(this,a)},this)})},prop:function(a,b){return a=$[a]||a,1 in arguments?this.each(function(c){this[a]=r(this,b,c,this[a])}):this[0]&&this[0][a]},data:function(a,b){var c="data-"+a.replace(O,"-$1").toLowerCase(),d=1 in arguments?this.attr(c,b):this.attr(c);return null!==d?u(d):w},val:function(a){return 0 in arguments?this.each(function(b){this.value=r(this,a,b,this.value)}):this[0]&&(this[0].multiple?y(this[0]).find("option").filter(function(){return this.selected}).pluck("value"):this[0].value)},offset:function(a){if(a)return this.each(function(b){var c=y(this),d=r(this,a,b,c.offset()),e=c.offsetParent().offset(),f={top:d.top-e.top,left:d.left-e.left};"static"==c.css("position")&&(f.position="relative"),c.css(f)});if(!this.length)return null;if(!y.contains(G.documentElement,this[0]))return{top:0,left:0};var b=this[0].getBoundingClientRect();return{left:b.left+window.pageXOffset,top:b.top+window.pageYOffset,width:Math.round(b.width),height:Math.round(b.height)}},css:function(b,c){if(arguments.length<2){var d,e=this[0];if(!e)return;if(d=getComputedStyle(e,""),"string"==typeof b)return e.style[A(b)]||d.getPropertyValue(b);if(_(b)){var f={};return y.each(b,function(a,b){f[b]=e.style[A(b)]||d.getPropertyValue(b)}),f}}var g="";if("string"==a(b))c||0===c?g=j(b)+":"+l(b,c):this.each(function(){this.style.removeProperty(j(b))});else for(x in b)b[x]||0===b[x]?g+=j(x)+":"+l(x,b[x])+";":this.each(function(){this.style.removeProperty(j(x))});return this.each(function(){this.style.cssText+=";"+g})},index:function(a){return a?this.indexOf(y(a)[0]):this.parent().children().indexOf(this[0])},hasClass:function(a){return a?C.some.call(this,function(a){return this.test(t(a))},k(a)):!1},addClass:function(a){return a?this.each(function(b){if("className"in this){z=[];var c=t(this),d=r(this,a,b,c);d.split(/\s+/g).forEach(function(a){y(this).hasClass(a)||z.push(a)},this),z.length&&t(this,c+(c?" ":"")+z.join(" "))}}):this},removeClass:function(a){return this.each(function(b){if("className"in this){if(a===w)return t(this,"");z=t(this),r(this,a,b,z).split(/\s+/g).forEach(function(a){z=z.replace(k(a)," ")}),t(this,z.trim())}})},toggleClass:function(a,b){return a?this.each(function(c){var d=y(this),e=r(this,a,c,t(this));e.split(/\s+/g).forEach(function(a){(b===w?!d.hasClass(a):b)?d.addClass(a):d.removeClass(a)})}):this},scrollTop:function(a){if(this.length){var b="scrollTop"in this[0];return a===w?b?this[0].scrollTop:this[0].pageYOffset:this.each(b?function(){this.scrollTop=a}:function(){this.scrollTo(this.scrollX,a)})}},scrollLeft:function(a){if(this.length){var b="scrollLeft"in this[0];return a===w?b?this[0].scrollLeft:this[0].pageXOffset:this.each(b?function(){this.scrollLeft=a}:function(){this.scrollTo(a,this.scrollY)})}},position:function(){if(this.length){var a=this[0],b=this.offsetParent(),c=this.offset(),d=N.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(y(a).css("margin-top"))||0,c.left-=parseFloat(y(a).css("margin-left"))||0,d.top+=parseFloat(y(b[0]).css("border-top-width"))||0,d.left+=parseFloat(y(b[0]).css("border-left-width"))||0,{top:c.top-d.top,left:c.left-d.left}}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||G.body;a&&!N.test(a.nodeName)&&"static"==y(a).css("position");)a=a.offsetParent;return a})}},y.fn.detach=y.fn.remove,["width","height"].forEach(function(a){var b=a.replace(/./,function(a){return a[0].toUpperCase()});y.fn[a]=function(e){var f,g=this[0];return e===w?c(g)?g["inner"+b]:d(g)?g.documentElement["scroll"+b]:(f=this.offset())&&f[a]:this.each(function(b){g=y(this),g.css(a,r(this,e,b,g[a]()))})}}),Q.forEach(function(b,c){var d=c%2;y.fn[b]=function(){var b,e,f=y.map(arguments,function(c){return b=a(c),"object"==b||"array"==b||null==c?c:Y.fragment(c)}),g=this.length>1;return f.length<1?this:this.each(function(a,b){e=d?b:b.parentNode,b=0==c?b.nextSibling:1==c?b.firstChild:2==c?b:null;var h=y.contains(G.documentElement,e);f.forEach(function(a){if(g)a=a.cloneNode(!0);else if(!e)return y(a).remove();e.insertBefore(a,b),h&&v(a,function(a){null==a.nodeName||"SCRIPT"!==a.nodeName.toUpperCase()||a.type&&"text/javascript"!==a.type||a.src||window.eval.call(window,a.innerHTML)})})})},y.fn[d?b+"To":"insert"+(c?"Before":"After")]=function(a){return y(a)[b](this),this}}),Y.Z.prototype=o.prototype=y.fn,Y.uniq=B,Y.deserializeValue=u,y.zepto=Y,y}();window.Zepto=Zepto,void 0===window.$&&(window.$=Zepto),function(a){function b(a){return a._zid||(a._zid=m++)}function c(a,c,f,g){if(c=d(c),c.ns)var h=e(c.ns);return(q[b(a)]||[]).filter(function(a){return a&&(!c.e||a.e==c.e)&&(!c.ns||h.test(a.ns))&&(!f||b(a.fn)===b(f))&&(!g||a.sel==g)})}function d(a){var b=(""+a).split(".");return{e:b[0],ns:b.slice(1).sort().join(" ")}}function e(a){return new RegExp("(?:^| )"+a.replace(" "," .* ?")+"(?: |$)")}function f(a,b){return a.del&&!s&&a.e in t||!!b}function g(a){return u[a]||s&&t[a]||a}function h(c,e,h,i,k,m,n){var o=b(c),p=q[o]||(q[o]=[]);e.split(/\s/).forEach(function(b){if("ready"==b)return a(document).ready(h);var e=d(b);e.fn=h,e.sel=k,e.e in u&&(h=function(b){var c=b.relatedTarget;return!c||c!==this&&!a.contains(this,c)?e.fn.apply(this,arguments):void 0}),e.del=m;var o=m||h;e.proxy=function(a){if(a=j(a),!a.isImmediatePropagationStopped()){a.data=i;var b=o.apply(c,a._args==l?[a]:[a].concat(a._args));return b===!1&&(a.preventDefault(),a.stopPropagation()),b}},e.i=p.length,p.push(e),"addEventListener"in c&&c.addEventListener(g(e.e),e.proxy,f(e,n))})}function i(a,d,e,h,i){var j=b(a);(d||"").split(/\s/).forEach(function(b){c(a,b,e,h).forEach(function(b){delete q[j][b.i],"removeEventListener"in a&&a.removeEventListener(g(b.e),b.proxy,f(b,i))})})}function j(b,c){return(c||!b.isDefaultPrevented)&&(c||(c=b),a.each(y,function(a,d){var e=c[a];b[a]=function(){return this[d]=v,e&&e.apply(c,arguments)},b[d]=w}),(c.defaultPrevented!==l?c.defaultPrevented:"returnValue"in c?c.returnValue===!1:c.getPreventDefault&&c.getPreventDefault())&&(b.isDefaultPrevented=v)),b}function k(a){var b,c={originalEvent:a};for(b in a)x.test(b)||a[b]===l||(c[b]=a[b]);return j(c,a)}var l,m=1,n=Array.prototype.slice,o=a.isFunction,p=function(a){return"string"==typeof a},q={},r={},s="onfocusin"in window,t={focus:"focusin",blur:"focusout"},u={mouseenter:"mouseover",mouseleave:"mouseout"};r.click=r.mousedown=r.mouseup=r.mousemove="MouseEvents",a.event={add:h,remove:i},a.proxy=function(c,d){var e=2 in arguments&&n.call(arguments,2);if(o(c)){var f=function(){return c.apply(d,e?e.concat(n.call(arguments)):arguments)};return f._zid=b(c),f}if(p(d))return e?(e.unshift(c[d],c),a.proxy.apply(null,e)):a.proxy(c[d],c);throw new TypeError("expected function")},a.fn.bind=function(a,b,c){return this.on(a,b,c)},a.fn.unbind=function(a,b){return this.off(a,b)},a.fn.one=function(a,b,c,d){return this.on(a,b,c,d,1)};var v=function(){return!0},w=function(){return!1},x=/^([A-Z]|returnValue$|layer[XY]$|webkitMovement[XY]$)/,y={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};a.fn.delegate=function(a,b,c){return this.on(b,a,c)},a.fn.undelegate=function(a,b,c){return this.off(b,a,c)},a.fn.live=function(b,c){return a(document.body).delegate(this.selector,b,c),this},a.fn.die=function(b,c){return a(document.body).undelegate(this.selector,b,c),this},a.fn.on=function(b,c,d,e,f){var g,j,m=this;return b&&!p(b)?(a.each(b,function(a,b){m.on(a,c,d,b,f)}),m):(p(c)||o(e)||e===!1||(e=d,d=c,c=l),(e===l||d===!1)&&(e=d,d=l),e===!1&&(e=w),m.each(function(l,m){f&&(g=function(a){return i(m,a.type,e),e.apply(this,arguments)}),c&&(j=function(b){var d,f=a(b.target).closest(c,m).get(0);return f&&f!==m?(d=a.extend(k(b),{currentTarget:f,liveFired:m}),(g||e).apply(f,[d].concat(n.call(arguments,1)))):void 0}),h(m,b,e,d,c,j||g)}))},a.fn.off=function(b,c,d){var e=this;return b&&!p(b)?(a.each(b,function(a,b){e.off(a,c,b)}),e):(p(c)||o(d)||d===!1||(d=c,c=l),d===!1&&(d=w),e.each(function(){i(this,b,d,c)}))},a.fn.trigger=function(b,c){return b=p(b)||a.isPlainObject(b)?a.Event(b):j(b),b._args=c,this.each(function(){b.type in t&&"function"==typeof this[b.type]?this[b.type]():"dispatchEvent"in this?this.dispatchEvent(b):a(this).triggerHandler(b,c)})},a.fn.triggerHandler=function(b,d){var e,f;return this.each(function(g,h){e=k(p(b)?a.Event(b):b),e._args=d,e.target=h,a.each(c(h,b.type||b),function(a,b){return f=b.proxy(e),e.isImmediatePropagationStopped()?!1:void 0})}),f},"focusin focusout focus blur load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(b){a.fn[b]=function(a){return 0 in arguments?this.bind(b,a):this.trigger(b)}}),a.Event=function(a,b){p(a)||(b=a,a=b.type);var c=document.createEvent(r[a]||"Events"),d=!0;if(b)for(var e in b)"bubbles"==e?d=!!b[e]:c[e]=b[e];return c.initEvent(a,d,!0),j(c)}}(Zepto),function(a){function b(b,c,d){var e=a.Event(c);return a(b).trigger(e,d),!e.isDefaultPrevented()}function c(a,c,d,e){return a.global?b(c||s,d,e):void 0}function d(b){b.global&&0===a.active++&&c(b,null,"ajaxStart")}function e(b){b.global&&!--a.active&&c(b,null,"ajaxStop")}function f(a,b){var d=b.context;return b.beforeSend.call(d,a,b)===!1||c(b,d,"ajaxBeforeSend",[a,b])===!1?!1:void c(b,d,"ajaxSend",[a,b])}function g(a,b,d,e){var f=d.context,g="success";d.success.call(f,a,g,b),e&&e.resolveWith(f,[a,g,b]),c(d,f,"ajaxSuccess",[b,d,a]),i(g,b,d)}function h(a,b,d,e,f){var g=e.context;e.error.call(g,d,b,a),f&&f.rejectWith(g,[d,b,a]),c(e,g,"ajaxError",[d,e,a||b]),i(b,d,e)}function i(a,b,d){var f=d.context;d.complete.call(f,b,a),c(d,f,"ajaxComplete",[b,d]),e(d)}function j(){}function k(a){return a&&(a=a.split(";",2)[0]),a&&(a==x?"html":a==w?"json":u.test(a)?"script":v.test(a)&&"xml")||"text"}function l(a,b){return""==b?a:(a+"&"+b).replace(/[&?]{1,2}/,"?")}function m(b){b.processData&&b.data&&"string"!=a.type(b.data)&&(b.data=a.param(b.data,b.traditional)),!b.data||b.type&&"GET"!=b.type.toUpperCase()||(b.url=l(b.url,b.data),b.data=void 0)}function n(b,c,d,e){return a.isFunction(c)&&(e=d,d=c,c=void 0),a.isFunction(d)||(e=d,d=void 0),{url:b,data:c,success:d,dataType:e}}function o(b,c,d,e){var f,g=a.isArray(c),h=a.isPlainObject(c);a.each(c,function(c,i){f=a.type(i),e&&(c=d?e:e+"["+(h||"object"==f||"array"==f?c:"")+"]"),!e&&g?b.add(i.name,i.value):"array"==f||!d&&"object"==f?o(b,i,d,c):b.add(c,i)})}var p,q,r=0,s=window.document,t=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,u=/^(?:text|application)\/javascript/i,v=/^(?:text|application)\/xml/i,w="application/json",x="text/html",y=/^\s*$/,z=s.createElement("a");z.href=window.location.href,a.active=0,a.ajaxJSONP=function(b,c){if(!("type"in b))return a.ajax(b);var d,e,i=b.jsonpCallback,j=(a.isFunction(i)?i():i)||"jsonp"+ ++r,k=s.createElement("script"),l=window[j],m=function(b){a(k).triggerHandler("error",b||"abort")},n={abort:m};return c&&c.promise(n),a(k).on("load error",function(f,i){clearTimeout(e),a(k).off().remove(),"error"!=f.type&&d?g(d[0],n,b,c):h(null,i||"error",n,b,c),window[j]=l,d&&a.isFunction(l)&&l(d[0]),l=d=void 0}),f(n,b)===!1?(m("abort"),n):(window[j]=function(){d=arguments},k.src=b.url.replace(/\?(.+)=\?/,"?$1="+j),s.head.appendChild(k),b.timeout>0&&(e=setTimeout(function(){m("timeout")},b.timeout)),n)},a.ajaxSettings={type:"GET",beforeSend:j,success:j,error:j,complete:j,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript, application/x-javascript",json:w,xml:"application/xml, text/xml",html:x,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0},a.ajax=function(b){var c,e,i=a.extend({},b||{}),n=a.Deferred&&a.Deferred();for(p in a.ajaxSettings)void 0===i[p]&&(i[p]=a.ajaxSettings[p]);d(i),i.crossDomain||(c=s.createElement("a"),c.href=i.url,c.href=c.href,i.crossDomain=z.protocol+"//"+z.host!=c.protocol+"//"+c.host),i.url||(i.url=window.location.toString()),(e=i.url.indexOf("#"))>-1&&(i.url=i.url.slice(0,e)),m(i);var o=i.dataType,r=/\?.+=\?/.test(i.url);if(r&&(o="jsonp"),i.cache!==!1&&(b&&b.cache===!0||"script"!=o&&"jsonp"!=o)||(i.url=l(i.url,"_="+Date.now())),"jsonp"==o)return r||(i.url=l(i.url,i.jsonp?i.jsonp+"=?":i.jsonp===!1?"":"callback=?")),a.ajaxJSONP(i,n);var t,u=i.accepts[o],v={},w=function(a,b){v[a.toLowerCase()]=[a,b]},x=/^([\w-]+:)\/\//.test(i.url)?RegExp.$1:window.location.protocol,A=i.xhr(),B=A.setRequestHeader;if(n&&n.promise(A),i.crossDomain||w("X-Requested-With","XMLHttpRequest"),w("Accept",u||"*/*"),(u=i.mimeType||u)&&(u.indexOf(",")>-1&&(u=u.split(",",2)[0]),A.overrideMimeType&&A.overrideMimeType(u)),(i.contentType||i.contentType!==!1&&i.data&&"GET"!=i.type.toUpperCase())&&w("Content-Type",i.contentType||"application/x-www-form-urlencoded"),i.headers)for(q in i.headers)w(q,i.headers[q]);if(A.setRequestHeader=w,A.onreadystatechange=function(){if(4==A.readyState){A.onreadystatechange=j,clearTimeout(t);var b,c=!1;if(A.status>=200&&A.status<300||304==A.status||0==A.status&&"file:"==x){o=o||k(i.mimeType||A.getResponseHeader("content-type")),b=A.responseText;try{"script"==o?(1,eval)(b):"xml"==o?b=A.responseXML:"json"==o&&(b=y.test(b)?null:a.parseJSON(b))}catch(d){c=d}c?h(c,"parsererror",A,i,n):g(b,A,i,n)}else h(A.statusText||null,A.status?"error":"abort",A,i,n)}},f(A,i)===!1)return A.abort(),h(null,"abort",A,i,n),A;if(i.xhrFields)for(q in i.xhrFields)A[q]=i.xhrFields[q];var C="async"in i?i.async:!0;A.open(i.type,i.url,C,i.username,i.password);for(q in v)B.apply(A,v[q]);return i.timeout>0&&(t=setTimeout(function(){A.onreadystatechange=j,A.abort(),h(null,"timeout",A,i,n)},i.timeout)),A.send(i.data?i.data:null),A},a.get=function(){return a.ajax(n.apply(null,arguments))},a.post=function(){var b=n.apply(null,arguments);return b.type="POST",a.ajax(b)},a.getJSON=function(){var b=n.apply(null,arguments);return b.dataType="json",a.ajax(b)},a.fn.load=function(b,c,d){if(!this.length)return this;var e,f=this,g=b.split(/\s/),h=n(b,c,d),i=h.success;return g.length>1&&(h.url=g[0],e=g[1]),h.success=function(b){f.html(e?a("<div>").html(b.replace(t,"")).find(e):b),i&&i.apply(f,arguments)},a.ajax(h),this};var A=encodeURIComponent;a.param=function(b,c){var d=[];return d.add=function(b,c){a.isFunction(c)&&(c=c()),null==c&&(c=""),this.push(A(b)+"="+A(c))},o(d,b,c),d.join("&").replace(/%20/g,"+")}}(Zepto),function(a){a.fn.serializeArray=function(){var b,c,d=[],e=function(a){return a.forEach?a.forEach(e):void d.push({name:b,value:a})};return this[0]&&a.each(this[0].elements,function(d,f){c=f.type,b=f.name,b&&"fieldset"!=f.nodeName.toLowerCase()&&!f.disabled&&"submit"!=c&&"reset"!=c&&"button"!=c&&"file"!=c&&("radio"!=c&&"checkbox"!=c||f.checked)&&e(a(f).val())}),d},a.fn.serialize=function(){var a=[];return this.serializeArray().forEach(function(b){a.push(encodeURIComponent(b.name)+"="+encodeURIComponent(b.value))}),a.join("&")},a.fn.submit=function(b){if(0 in arguments)this.bind("submit",b);else if(this.length){var c=a.Event("submit");this.eq(0).trigger(c),c.isDefaultPrevented()||this.get(0).submit()}return this}}(Zepto),function(){try{getComputedStyle(void 0)}catch(a){var b=getComputedStyle;window.getComputedStyle=function(a){try{return b(a)}catch(c){return null}}}}(),function(a,b){function c(a){return a.replace(/([a-z])([A-Z])/,"$1-$2").toLowerCase()}function d(a){return e?e+a:a.toLowerCase()}var e,f,g,h,i,j,k,l,m,n,o="",p={Webkit:"webkit",Moz:"",O:"o"},q=document.createElement("div"),r=/^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i,s={};a.each(p,function(a,c){return q.style[a+"TransitionProperty"]!==b?(o="-"+a.toLowerCase()+"-",e=c,!1):void 0}),f=o+"transform",s[g=o+"transition-property"]=s[h=o+"transition-duration"]=s[j=o+"transition-delay"]=s[i=o+"transition-timing-function"]=s[k=o+"animation-name"]=s[l=o+"animation-duration"]=s[n=o+"animation-delay"]=s[m=o+"animation-timing-function"]="",a.fx={off:e===b&&q.style.transitionProperty===b,speeds:{_default:400,fast:200,slow:600},cssPrefix:o,transitionEnd:d("TransitionEnd"),animationEnd:d("AnimationEnd")},a.fn.animate=function(c,d,e,f,g){return a.isFunction(d)&&(f=d,e=b,d=b),a.isFunction(e)&&(f=e,e=b),a.isPlainObject(d)&&(e=d.easing,f=d.complete,g=d.delay,d=d.duration),d&&(d=("number"==typeof d?d:a.fx.speeds[d]||a.fx.speeds._default)/1e3),g&&(g=parseFloat(g)/1e3),this.anim(c,d,e,f,g)},a.fn.anim=function(d,e,o,p,q){var t,u,v,w={},x="",y=this,z=a.fx.transitionEnd,A=!1;if(e===b&&(e=a.fx.speeds._default/1e3),q===b&&(q=0),a.fx.off&&(e=0),"string"==typeof d)w[k]=d,w[l]=e+"s",w[n]=q+"s",w[m]=o||"linear",z=a.fx.animationEnd;else{u=[];for(t in d)r.test(t)?x+=t+"("+d[t]+") ":(w[t]=d[t],u.push(c(t)));x&&(w[f]=x,u.push(f)),e>0&&"object"==typeof d&&(w[g]=u.join(", "),w[h]=e+"s",w[j]=q+"s",w[i]=o||"linear")}return v=function(b){if("undefined"!=typeof b){if(b.target!==b.currentTarget)return;a(b.target).unbind(z,v)}else a(this).unbind(z,v);A=!0,a(this).css(s),p&&p.call(this)},e>0&&(this.bind(z,v),setTimeout(function(){A||v.call(y)},1e3*(e+q)+25)),this.size()&&this.get(0).clientLeft,this.css(w),0>=e&&setTimeout(function(){y.each(function(){v.call(this)})},0),this},q=null}(Zepto),function(a,b){function c(c,d,e,f,g){"function"!=typeof d||g||(g=d,d=b);var h={opacity:e};return f&&(h.scale=f,c.css(a.fx.cssPrefix+"transform-origin","0 0")),c.animate(h,d,null,g)}function d(b,d,e,f){return c(b,d,0,e,function(){g.call(a(this)),f&&f.call(this)})}var e=window.document,f=(e.documentElement,a.fn.show),g=a.fn.hide,h=a.fn.toggle;a.fn.show=function(a,d){return f.call(this),a===b?a=0:this.css("opacity",0),c(this,a,1,"1,1",d)},a.fn.hide=function(a,c){return a===b?g.call(this):d(this,a,"0,0",c)},a.fn.toggle=function(c,d){return c===b||"boolean"==typeof c?h.call(this,c):this.each(function(){var b=a(this);b["none"==b.css("display")?"show":"hide"](c,d)})},a.fn.fadeTo=function(a,b,d){return c(this,a,b,null,d)},a.fn.fadeIn=function(a,b){var c=this.css("opacity");return c>0?this.css("opacity",0):c=1,f.call(this).fadeTo(a,c,b)},a.fn.fadeOut=function(a,b){return d(this,a,null,b)},a.fn.fadeToggle=function(b,c){return this.each(function(){var d=a(this);d[0==d.css("opacity")||"none"==d.css("display")?"fadeIn":"fadeOut"](b,c)})}}(Zepto),function(a){function b(b,d){var i=b[h],j=i&&e[i];if(void 0===d)return j||c(b);if(j){if(d in j)return j[d];var k=g(d);if(k in j)return j[k]}return f.call(a(b),d)}function c(b,c,f){var i=b[h]||(b[h]=++a.uuid),j=e[i]||(e[i]=d(b));return void 0!==c&&(j[g(c)]=f),j}function d(b){var c={};return a.each(b.attributes||i,function(b,d){0==d.name.indexOf("data-")&&(c[g(d.name.replace("data-",""))]=a.zepto.deserializeValue(d.value))}),c}var e={},f=a.fn.data,g=a.camelCase,h=a.expando="Zepto"+ +new Date,i=[];a.fn.data=function(d,e){return void 0===e?a.isPlainObject(d)?this.each(function(b,e){a.each(d,function(a,b){c(e,a,b)})}):0 in this?b(this[0],d):void 0:this.each(function(){c(this,d,e)})},a.fn.removeData=function(b){return"string"==typeof b&&(b=b.split(/\s+/)),this.each(function(){var c=this[h],d=c&&e[c];d&&a.each(b||d,function(a){delete d[b?g(this):a]})})},["remove","empty"].forEach(function(b){var c=a.fn[b];a.fn[b]=function(){var a=this.find("*");return"remove"===b&&(a=a.add(this)),a.removeData(),c.call(this)}})}(Zepto); ```
/content/code_sandbox/public/vendor/datetimepicker/demo/zepto-1.1.6-Custom.min.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
9,575
```html <!DOCTYPE html> <html> <head> <title>TouchHold Gesture Example</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <p>Date : </p> <input type="text" data-field="date" readonly> <p>Time : </p> <input type="text" data-field="time" readonly> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker({ captureMouseHold: true, mouseHoldInterval: 10 }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/Events-MouseHold.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
391
```html <!DOCTYPE html> <html> <head> <title>jQuery DateTimePicker - Responsive flat design jQuery DateTime Picker plugin for Web & Mobile</title> <style> * { -webkit-box-sizing:border-box; -moz-box-sizing:border-box; -o-box-sizing:border-box; box-sizing:border-box; } html, body { background:#FFFFFF; font-size: 18px; } .jumbotron { background: #FFFFFF; padding-top: 30px; padding-bottom: 20px; text-align: center; font-size: 21px; font-weight: 200; font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; } .doc-header { color: #FF3B30; font-size: 50px; margin-top: 20px; margin-bottom: 10px; font-weight: 500; line-height: 1.1; } .doc-description { color: #22313F; line-height: 1.4; } .acc-container { width:90%; margin:30px auto; -webkit-border-radius:8px; -moz-border-radius:8px; -o-border-radius:8px; border-radius:8px; overflow:hidden; } .acc-container a { display: block; width:100%; margin:0 auto; padding:10px 15px; cursor:pointer; background:#F8F8F8; border-bottom:1px solid #EAEAEA; text-decoration: none; color: #666666; cursor:pointer; } .acc-container a:hover { color: #A82626; } .acc-container a p { color: #A82626; font-size: 60%; } .footer { text-align: center; } .footer a { color: #FF3B30; } .footer a:hover { color: #F2382E; } </style> </head> <body> <div class="jumbotron"> <h2 class="doc-header">DateTimePicker</h2> <p class="doc-description">Responsive flat design jQuery DateTime Picker plugin for Web & Mobile</p> </div> <div class="acc-container"> <a href="BasicExamples-InputText.htm"> Basic Usage of DateTimePicker with &lt;input type="text"&gt; </a> <a href="BasicExamples-InputHTML5.htm"> Basic Usage of DateTimePicker with &lt;input type="date"&gt; or &lt;input type="time"&gt; or &lt;input type="datetime"&gt; <p>* This does not work in IE versions less than 9</p> </a> <a href="BasicExamples-NonInputElement.htm"> Basic Usage of DateTimePicker without &lt;input type="text"&gt; </a> <a href="BasicExamples-CustomEvent.htm"> Show DateTimePicker on Event other than focus of Input Field </a> <a href="BasicExamples-HumanDateFormatting.htm"> Show DateTimePicker with a custom DateFormat in the DateTimePicker Header </a> <a href="BasicExamples-MinuteInterval.htm"> Increment/Decrement minutes with given Interval. </a> <a href="BasicExamples-SecondsInterval.htm"> Increment/Decrement seconds with given Interval. </a> <a href="Format-DataAttributes.htm"> DateFormat, TimeFormat or DateTimeFormat specified as a Data Attributes </a> <a href="Format-Parameters.htm"> DateFormat, TimeFormat or DateTimeFormat specified as Plugin Parameters </a> <a href="Format-Both.htm"> DateFormat, TimeFormat or DateTimeFormat specified as Plugin Parameters as well as Data Attribute. In this case, Data Attribute has a higher priority. </a> <a href="Format-MonthYear.htm"> "MM yyyy", "MMM yyyy" and "MMMM yyyy" formats. </a> <a href="PeriodRange-DataAttributes.htm"> Maximum and Minimum Date, Time or DateTime can be specified as Data Attribute </a> <a href="PeriodRange-Parameters.htm"> Maximum and Minimum Date, Time or DateTime can be specified as Plugin Parameter </a> <a href="PeriodRange-Both.htm"> Maximum and Minimum Date, Time or DateTime can be specified as Plugin Parameter and Data Attribute. In this case, Data Attribute has a higher priority. </a> <a href="PeriodRange-MinToday.htm"> Set Today As Minimum Date </a> <a href="StartEnd-DataAttributes.htm"> Start and End Date, Time and DateTime fields can be specified as Data Attribute </a> <a href="ViewPopup-Parameters.htm"> DateTimePicker Popup View specified as Parameter </a> <a href="ViewDropdown-Parameters.htm"> DateTimePicker Dropdown View specified as Parameter </a> <a href="View-DataAttributes.htm"> DateTimePicker View specified as HTML5 Custom Data Attribute </a> <a href="View-BasedOnDocumentWidth.htm"> DateTimePicker View selected based on Document Width </a> <a href="View-Inline.htm"> DateTimePicker Inline View </a> <a href="Internationalization.htm"> Internationalization </a> <a href="Internationalization-German.htm"> Internationalization German </a> <a href="SetValueInInput.htm"> Set Value In Input Field </a> <a href="AngularJS/BasicDatePicker-AngularJS.htm"> DateTimePicker with Angular JS </a> <a href="Events-TouchHold.htm"> Increment/Decrement with hold of Increment/Decrement buttons for touch devices </a> <a href="Events-MouseHold.htm"> Increment/Decrement with hold of Increment/Decrement buttons </a> </div> <div class="footer">This project is maintained by <a class="btn-link" href="path_to_url">Neha Kadam</a></div> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/index.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
1,539
```html <!DOCTYPE html> <html> <head> <title>Time Picker</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <p>Time : </p> <input type="text" data-field="time" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker(); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicTimePicker.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
308
```javascript /*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(l.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f }}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},W=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.isWindow(d)){for(i=k.delegateType||p,_.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((n.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?n(c,this).index(i)>=0:n.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=$.test(e)?this.mouseHooks:Z.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||z),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||z,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==db()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===db()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=z.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===L&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?bb:cb):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:cb,isPropagationStopped:cb,isImmediatePropagationStopped:cb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=bb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=bb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return Y.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;Y.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!Y.test(this.nodeName)}}),l.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=cb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=cb),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});function eb(a){var b=fb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var fb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gb=/ jQuery\d+="(?:null|\d+)"/g,hb=new RegExp("<(?:"+fb+")[\\s/>]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/<tbody/i,mb=/<|&#?\w+;/,nb=/<(?:script|style|link)/i,ob=/checked\s*(?:[^=]|=\s*.checked.)/i,pb=/^$|\/(?:java|ecma)script/i,qb=/^true\/(.*)/,rb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?"<table>"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(vb(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Mb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Rb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b) },a,b,arguments.length>1)},show:function(){return Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},$b.propHooks.scrollTop=$b.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],bc.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:_b||gc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(lc,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=lc(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(_b=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),_b=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ac||(ac=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(ac),ac=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e=z.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.text(a)}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(vc," ").indexOf(b)>=0)return!0;return!1}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nc(a,b,c,d){var e={},f=a===Jc;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Qc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Dc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Kc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Nc(Jc,k,b,v)){v.readyState=1,h&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Yc[g],b=void 0,f.onreadystatechange=n.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,ad.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return W(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n}); ```
/content/code_sandbox/public/vendor/datetimepicker/demo/jquery-1.11.0.min.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
32,321
```html <!DOCTYPE html> <html> <head> <title>beforeShow Callback </title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker( { beforeShow: function(oInputElement) { var oDTP = this; if($(oInputElement).val() === "") oDTP.settings.defaultDate = new Date(); } }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/Callback-beforeShow.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
356
```html <!DOCTYPE html> <html> <head> <title>DateTimePicker in Custom Container</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } #input-date { display: none; } #dtBox { margin: 0px auto; width: 700px; height: auto; } </style> </head> <body> <p>Date : </p> <span id="input-date" type="text" data-field="date"></span> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker({ isInline: true, inputElement: $("#input-date"), buttonsToDisplay: [], showHeader: false, readonlyInputs: false, setValueInTextboxOnEveryClick: true, settingValueOfElement: function(oDTP, sElemValue, dElemValue, $oElem) { console.log("settingValueOfElement : " + sElemValue); console.log(dElemValue); } }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/View-Inline.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
424
```html <!DOCTYPE html> <html> <head> <title>Period Range - Data Attributes and Parameters</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <form> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" data-min="01-10-2012" data-max="01-05-2015" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" data-min="10:00" data-max="16:30" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" data-min="01-10-2012 09:30" data-max="01-05-2015 17:30" readonly> </form> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker({ defaultDate: new Date(2014, 5, 20, 0, 0, 0), minDate: "01-03-2012", maxDate: "01-03-2016", minTime: "09:00", maxTime: "19:30", minDateTime: new Date(2016, 2, 1, 8, 30, 0, 0), maxDateTime: new Date(2016, 2, 1, 18, 30, 0, 0) // OR // minDateTime: "01-03-2012 08:30", // maxDateTime: "01-03-2016 18:30" }); }); </script> <!-- Default dateFormat: "dd-MM-yyyy" dateFormat Options : 1. "dd-MM-yyyy" 2. "MM-dd-yyyy" 3. "yyyy-MM-dd" Specify (data-min & data-max) / (minDate & maxDate) values in the same dateFormat specified in settings parameters --> <!-- Default timeFormat: "HH:mm" timeFormat Options : 1. "HH:mm" 2. "hh:mm AA" Specify (data-min & data-max) / (minTime & maxTime) values in the same timeFormat specified in settings parameters --> <!-- Default dateTimeFormat: "dd-MM-yyyy HH:mm:ss" dateTimeFormat Options : 1. "dd-MM-yyyy HH:mm:ss" 2. "dd-MM-yyyy hh:mm:ss AA" 3. "MM-dd-yyyy HH:mm:ss" 4. "MM-dd-yyyy hh:mm:ss AA" 5. "yyyy-MM-dd HH:mm:ss" 6. "yyyy-MM-dd hh:mm:ss AA" Specify (data-min & data-max) / (minDateTime & maxDateTime) values in the same dateTimeFormat specified in settings parameters --> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/PeriodRange-Both.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
1,014
```html <!DOCTYPE html> <html> <head> <title>Period Range - Minimum Date Today</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <form> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input id="in-date" type="text" data-field="date" data-format="dd-MM-yyyy" readonly> <p>Time : </p> <input id="in-time" type="text" data-field="time" data-format="hh:mm AA" readonly> </form> <div id="dtBox"></div> <script type="text/javascript"> var oDTP, dDate, dTime, dDateTime, sDateFormat = ""; $(document).ready(function() { $("#dtBox").DateTimePicker({ addEventHandlers: function() { oDTP = this; if(oDTP.settings.defaultDate) dDateTime = new Date(oDTP.settings.defaultDate); else dDateTime = new Date(); oDTP.settings.minDate = oDTP.getDateTimeStringInFormat("Date", "dd-MM-yyyy", new Date(dDateTime)); oDTP.settings.minTime = oDTP.getDateTimeStringInFormat("Time", "hh:mm AA", new Date(dDateTime)); }, settingValueOfElement: function(sElemValue, dElemValue, oElem) { oDTP = this; if(oDTP.settings.mode === "date") { dDateTime = new Date(dElemValue.getFullYear(), dElemValue.getMonth(), dElemValue.getDate(), dDateTime.getHours(), dDateTime.getMinutes(), 0, 0); } else if(oDTP.settings.mode === "time") { dDateTime = new Date(dDateTime.getFullYear(), dDateTime.getMonth(), dDateTime.getDate(), dElemValue.getHours(), dElemValue.getMinutes(), 0, 0); } console.log(dDateTime); }, formatHumanDate: function(oDateTime, sMode, sFormat) { oDTP = this; if(sMode === "date") { sDateFormat = oDateTime.dayShort + ", " + oDateTime.dd + " " + oDateTime.month+ ", " + oDateTime.yyyy; return sDateFormat; } else if(sMode === "time") { if(sDateFormat !== "") { return sDateFormat + " " + oDateTime.HH + ":" + oDateTime.mm + ":" + oDateTime.ss; } else { return (oDTP.settings.shortDayNames[dDateTime.getDay()] + ", " + dDateTime.getDate() + " " + oDTP.settings.fullMonthNames[dDateTime.getMonth()] + " " + dDateTime.getFullYear()) + " " + oDateTime.HH + ":" + oDateTime.mm + ":" + oDateTime.ss; } } }, buttonClicked: function(sButtonType, oElement) { oDTP = this; if(sButtonType === "CLEAR" && $(oElement).attr("id") === "in-date") { dDateTime = new Date(); sDateFormat = ""; } } }); }); </script> <!-- Default dateFormat: "dd-MM-yyyy" dateFormat Options : 1. "dd-MM-yyyy" 2. "MM-dd-yyyy" 3. "yyyy-MM-dd" Specify (data-min & data-max) / (minDate & maxDate) values in the same dateFormat specified in settings parameters --> <!-- Default timeFormat: "HH:mm" timeFormat Options : 1. "HH:mm" 2. "hh:mm AA" Specify (data-min & data-max) / (minTime & maxTime) values in the same timeFormat specified in settings parameters --> <!-- Default dateTimeFormat: "dd-MM-yyyy HH:mm:ss" dateTimeFormat Options : 1. "dd-MM-yyyy HH:mm:ss" 2. "dd-MM-yyyy hh:mm:ss AA" 3. "MM-dd-yyyy HH:mm:ss" 4. "MM-dd-yyyy hh:mm:ss AA" 5. "yyyy-MM-dd HH:mm:ss" 6. "yyyy-MM-dd hh:mm:ss AA" Specify (data-min & data-max) / (minDateTime & maxDateTime) values in the same dateTimeFormat specified in settings parameters --> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/PeriodRange-Constant_Date.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
1,207
```html <!DOCTYPE html> <html> <head> <title>Minute Intervals - Multiple</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <div class="minutes-1"> <p>Time : (1 minute)</p> <input id="input-1" type="text" data-field="time" readonly> </div> <div class="minutes-5"> <p>Time : (5 minutes)</p> <input id="input-2" type="text" data-field="time" readonly> </div> <div id="dtBox-1"></div> <div id="dtBox-2"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox-1").DateTimePicker( { parentElement: ".minutes-1", minuteInterval: 1 }); $("#dtBox-2").DateTimePicker( { parentElement: ".minutes-5", minuteInterval: 5 }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicExamples-MinuteInterval-Multiple.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
443
```html <!DOCTYPE html> <html> <head> <title>Period Range - Data Attributes</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" data-min="01-03-2012" data-max="01-03-2016" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" data-min="09:00" data-max="19:30" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" data-min="01-03-2012 08:30" data-max="01-03-2016 18:30" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker({ defaultDate: new Date(2014, 5, 20, 0, 0, 0) }); }); </script> <!-- Default dateFormat: "dd-MM-yyyy" dateFormat Options : 1. "dd-MM-yyyy" 2. "MM-dd-yyyy" 3. "yyyy-MM-dd" Specify data-min & data-max values in the same dateFormat specified in settings parameters --> <!-- Default timeFormat: "HH:mm" timeFormat Options : 1. "HH:mm" 2. "hh:mm AA" Specify data-min & data-max values in the same timeFormat specified in settings parameters --> <!-- Default dateTimeFormat: "dd-MM-yyyy HH:mm:ss" dateTimeFormat Options : 1. "dd-MM-yyyy HH:mm:ss" 2. "dd-MM-yyyy hh:mm:ss AA" 3. "MM-dd-yyyy HH:mm:ss" 4. "MM-dd-yyyy hh:mm:ss AA" 5. "yyyy-MM-dd HH:mm:ss" 6. "yyyy-MM-dd hh:mm:ss AA" Specify data-min & data-max values in the same dateTimeFormat specified in settings parameters --> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/PeriodRange-DataAttributes.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
733
```html <!DOCTYPE html> <html> <head> <title>Basic Examples - Set DateTime In Input Field</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <p>Date : </p> <input type="text" data-field="date" data-format="dd-MM-yyyy" readonly> <div id="dtBox"></div> <script type="text/javascript"> var inputDateString = "2016-10-22", outputDateString, dDateTime; $(document).ready(function() { $("#dtBox").DateTimePicker( { addEventHandlers: function() { oDTP = this; var inputDateStringComp = inputDateString.split("-"); // Set Date oDTP.settings.defaultDate = new Date(parseInt(inputDateStringComp[0]), parseInt(inputDateStringComp[1]) - 1, parseInt(inputDateStringComp[2]), 0, 0, 0, 0); dDateTime = new Date(oDTP.settings.defaultDate); oDTP.setDateTimeStringInInputField($("input"), oDTP.settings.defaultDate); }, settingValueOfElement: function(sElemValue, dElemValue, oElem) { oDTP = this; if(oDTP.settings.mode === "date") { dDateTime = new Date(dElemValue.getFullYear(), dElemValue.getMonth(), dElemValue.getDate(), 0, 0, 0, 0); outputDateString = oDTP.getDateTimeStringInFormat("date", "yyyy-MM-dd"); } console.log(dDateTime + " -- " + outputDateString); } }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/FormatConversion.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
573
```html <!DOCTYPE html> <html> <head> <title>Basic Examples -- Input Type Date | Time | DateTime</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <!---- This will not work on IE Versions less than 9 -------------> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="time" readonly> <!------------------------ DateTime Picker ------------------------> <p>DateTime : </p> <input type="datetime" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker(); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicExamples-InputHTML5.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
394
```html <!DOCTYPE html> <html> <head> <title>Time and DateTime with Seconds</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <p>Time : (Format - "hh:mm:ss AA")</p> <input type="text" data-field="time" data-format="hh:mm:ss AA" readonly> <p>Time : (Format - "HH:mm:ss")</p> <input type="text" data-field="time" data-format="HH:mm:ss" readonly> <p>DateTime : (Format - "dd-MM-yyyy hh:mm:ss AA")</p> <input type="text" data-field="datetime" data-format="dd-MM-yyyy hh:mm:ss AA" readonly> <p>DateTime : (Format - "dd-MM-yyyy HH:mm:ss")</p> <input type="text" data-field="datetime" data-format="dd-MM-yyyy HH:mm:ss" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker(); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicExamples-Seconds.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
454
```html <!DOCTYPE html> <html> <head> <title>Basic Examples -- Input Type Text</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker( { dateFormat: "dd-MMM-yyyy" }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicExamples-InputText.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
402
```html <!DOCTYPE html> <html> <head> <title>Basic Examples -- Non Input Element</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } span[data-field] { border: 1px inset #DEDEDE; display: inline-block; width: 200px; height: 15px; line-height: 15px; font: -webkit-small-control; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <!------------------------ Date Picker ------------------------> <p>Date : </p> <span data-field="date"></span> <!------------------------ Time Picker ------------------------> <p>Time : </p> <span data-field="time"></span> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <span data-field="datetime"></span> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker(); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicExamples-NonInputElement.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
419
```html <!DOCTYPE html> <html> <head> <title>Format - Parameters</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker({ dateFormat: "yyyy-MM-dd", timeFormat: "hh:mm AA", dateTimeFormat: "yyyy-MM-dd hh:mm:ss AA" }); }); </script> <!-- Default dateFormat: "dd-MM-yyyy" dateFormat Options : 1. "dd-MM-yyyy" 2. "MM-dd-yyyy" 3. "yyyy-MM-dd" Specify minDate & maxDate values in the same dateFormat specified in settings parameters --> <!-- Default timeFormat: "HH:mm" timeFormat Options : 1. "HH:mm" 2. "hh:mm AA" Specify minTime & maxTime values in the same timeFormat specified in settings parameters --> <!-- Default dateTimeFormat: "dd-MM-yyyy HH:mm:ss" dateTimeFormat Options : 1. "dd-MM-yyyy HH:mm:ss" 2. "dd-MM-yyyy hh:mm:ss AA" 3. "MM-dd-yyyy HH:mm:ss" 4. "MM-dd-yyyy hh:mm:ss AA" 5. "yyyy-MM-dd HH:mm:ss" 6. "yyyy-MM-dd hh:mm:ss AA" Specify minDateTime & maxDateTime values in the same dateTimeFormat specified in settings parameters --> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/Format-Parameters.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
674
```html <!DOCTYPE html> <html> <head> <title>Format - Data Attributes and Parameters</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" data-format="dd-MMM-yyyy" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" data-format="hh:mm AA" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" data-format="dd-MMM-yyyy hh:mm:ss AA" readonly> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" data-format="yyyy-MM-dd" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" data-format="hh:mm AA" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" data-format="yyyy-MM-dd hh:mm:ss AA" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker({ dateFormat: "MM-dd-yyyy", timeFormat: "HH:mm", dateTimeFormat: "MM-dd-yyyy HH:mm:ss AA" }); }); </script> <!-- Default dateFormat: "dd-MM-yyyy" dateFormat Options : 1. "dd-MM-yyyy" 2. "MM-dd-yyyy" 3. "yyyy-MM-dd" Specify (data-min & data-max) / (minDate & maxDate) values in the same dateFormat specified in settings parameters --> <!-- Default timeFormat: "HH:mm" timeFormat Options : 1. "HH:mm" 2. "hh:mm AA" Specify (data-min & data-max) / (minTime & maxTime) values in the same timeFormat specified in settings parameters --> <!-- Default dateTimeFormat: "dd-MM-yyyy HH:mm:ss" dateTimeFormat Options : 1. "dd-MM-yyyy HH:mm:ss" 2. "dd-MM-yyyy hh:mm:ss AA" 3. "MM-dd-yyyy HH:mm:ss" 4. "MM-dd-yyyy hh:mm:ss AA" 5. "yyyy-MM-dd HH:mm:ss" 6. "yyyy-MM-dd hh:mm:ss AA" Specify (data-min & data-max) / (minDateTime & maxDateTime) values in the same dateTimeFormat specified in settings parameters --> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/Format-Both.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
958
```html <!DOCTYPE html> <html> <head> <title>Internationalization - German Locale</title> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <script type="text/javascript" src="../src/i18n/DateTimePicker-i18n.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <p>Date : </p> <input type="text" data-field="date" readonly> <p>Time : </p> <input type="text" data-field="time" readonly> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <div id="dtBox"></div> <script type="text/javascript"> // German Locale Strings Source - path_to_url $(document).ready(function() { $("#dtBox").DateTimePicker({ language:'zh-CN', defaultDate: new Date(), animationDuration:200, buttonsToDisplay: [ "SetButton","HeaderCloseButton"], clearButtonContent: "" }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/Internationalization-Chinese.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
445
```html <!DOCTYPE html> <html> <head> <title>Seconds Intervals - Multiple</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <div class="seconds-1"> <p>Time : (Format - "HH:mm:ss", Interval - 2 seconds)</p> <input id="input-1" type="text" data-field="time" data-format="HH:mm:ss" readonly> </div> <div class="seconds-5"> <p>DateTime : (Format - "dd-MM-yyyy HH:mm:ss", Interval - 5 seconds)</p> <input id="input-2" type="text" data-field="datetime" data-format="dd-MM-yyyy HH:mm:ss" readonly> </div> <div id="dtBox-1"></div> <div id="dtBox-2"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox-1").DateTimePicker( { parentElement: ".seconds-1", secondsInterval: 2 }); $("#dtBox-2").DateTimePicker( { parentElement: ".seconds-5", secondsInterval: 5 }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicExamples-SecondsInterval-Multiple.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
483
```html <!DOCTYPE html> <html> <head> <title>Date Picker</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <!-- <script type="text/javascript" src="jquery-1.11.0.min.js"></script> --> <script type="text/javascript" src="jquery-3.1.0.min.js"></script> <script type="text/javascript" src="../dist/DateTimePicker.min.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <p>Date : </p> <input type="text" data-field="date" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker(); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicDatePicker.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
331
```html <!DOCTYPE html> <html> <head> <title>View -- Data Attributes</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <!------------------------ Date Picker ------------------------> <p>Start Date : </p> <input class="startDate1" type="text" data-field="date" data-startend="start" data-startendelem=".endDate1" readonly> <p>End Date : </p> <input class="endDate1" type="text" data-field="date" data-startend="end" data-startendelem=".startDate1" readonly> <!------------------------ Time Picker ------------------------> <p>Start Time : </p> <input class="startTime1" type="text" data-field="time" data-startend="start" data-format="hh:mm AA" data-startendelem=".endTime1" readonly> <p>End Time : </p> <input class="endTime1" type="text" data-field="time" data-format="hh:mm AA" data-startend="end" data-startendelem=".startTime1" readonly> <!---------------------- DateTime Picker ----------------------> <p>Start DateTime : </p> <input class="startDateTime1" type="text" data-field="datetime" data-startend="start" data-startendelem=".endDateTime1" readonly> <p>End DateTime : </p> <input class="endDateTime1" type="text" data-field="datetime" data-startend="end" data-startendelem=".startDateTime1" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker(); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/StartEnd-DataAttributes.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
595
```html <!DOCTYPE html> <html> <head> <title>Internationalization - German Locale</title> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <p>Date : </p> <input type="text" data-field="date" readonly> <p>Time : </p> <input type="text" data-field="time" readonly> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <div id="dtBox"></div> <script type="text/javascript"> // German Locale Strings Source - path_to_url $(document).ready(function() { $("#dtBox").DateTimePicker({ dateTimeFormat: "dd-MMM-yyyy HH:mm:ss", dateFormat: "dd-MMM-yyyy", timeFormat: "HH:mm:ss", shortDayNames: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"], fullDayNames: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"], shortMonthNames: ["Jan", "Feb", "Mr", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"], fullMonthNames: ["Januar", "Februar", "Mrz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"], titleContentDate: "Datum auswhlen", titleContentTime: "Zeit auswhlen", titleContentDateTime: "Datum & Zeit auswhlen", setButtonContent: "Auswhlen", clearButtonContent: "Zurcksetzen", formatHumanDate: function(oDate, sMode, sFormat) { if(sMode === "date") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ ", " + oDate.yyyy; else if(sMode === "time") return oDate.HH + ":" + oDate.mm + ":" + oDate.ss; else if(sMode === "datetime") return oDate.dayShort + ", " + oDate.dd + " " + oDate.month+ ", " + oDate.yyyy + " " + oDate.HH + ":" + oDate.mm + ":" + oDate.ss; } }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/Internationalization-German.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
778
```html <!DOCTYPE html> <html> <head> <title>Internationalization</title> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <script type="text/javascript" src="../src/i18n/DateTimePicker-i18n.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <label class="forSelLang"> Select Language : </label> <select class="selLang"></select> <p>Date : </p> <input type="text" data-field="date" readonly> <p>Time : </p> <input type="text" data-field="time" readonly> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { var sArrLang = Object.keys($.DateTimePicker.i18n), oDTP; $.each(sArrLang, function (iIndex, sTempLang) { $(".selLang").append($('<option>', { value: sTempLang, text : sTempLang })); }); $(".selLang").change(function() { var sTempLang = $(".selLang").val(); console.log("Language Changed From '" + oDTP.settings.language + "' to '" + sTempLang + "'"); oDTP = oDTP.setLanguage(sTempLang); }); $("#dtBox").DateTimePicker( { init: function() { oDTP = this; }, language: "cs" }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/Internationalization.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
581
```html <!DOCTYPE html> <html> <head> <title>View -- Dropdown</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker({ isPopup: false }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/ViewDropdown-Parameters.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
393
```html <!DOCTYPE html> <html> <head> <title>Custom Input Value</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } .btn { background: #FFFFFF; color: #A3A3CC; border: 2px solid #A3A3CC; border-radius: 5px; padding: 10px 20px; margin: 20px; font-size: 12px; cursor: pointer; } </style> </head> <body> <div class="container"> <div class="cont-date"> <p>Date : </p> <input id="input-date" type="text" data-field="date" value="Friday, 23 October" readonly> <span id="btnCurrentDate" class="btn">Today</span> <span id="btnGetDate" class="btn">Get Date</span> </div> <div class="cont-datetime"> <p>Time : </p> <input id="input-time" type="text" data-field="time" value="12:35" readonly> <span id="btnCurrentTime" class="btn">Now</span> <span id="btnGetTime" class="btn">Get Time</span> <p>DateTime : </p> <input id="input-datetime" type="text" data-field="datetime" value="23-10-2015 00:00" readonly> <span id="btnCurrentDateTime" class="btn">This Moment</span> <span id="btnGetDateTime" class="btn">Get DateTime</span> </div> </div> <div id="dateBox"></div> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { var oDTP1, oDTP2; $("#dateBox").DateTimePicker( { init: function() { oDTP1 = this; }, parentElement: ".cont-date", parseDateTimeString: function(sDateTime, sMode, sFormat, oInputElement) { oDTP1 = this; console.log(sDateTime + " " + sMode); var dThisDate = new Date(), iArrDateTimeComps, sRegex; if($.cf._isValid(sDateTime)) { // "Friday, 23 October" sRegex = /([a-zA-Z]+)(, )(\d{1,2})( )([a-zA-Z]+)/; iArrDateTimeComps = sDateTime.match(sRegex); dThisDate = new Date( dThisDate.getFullYear(), oDTP1.settings.fullMonthNames.indexOf(iArrDateTimeComps[5]), parseInt(iArrDateTimeComps[3]), 0, 0, 0, 0 ); } return dThisDate; }, formatDateTimeString: function(oDate, sMode, sFormat, oInputElement) { oDTP1 = this; console.log(oDate); return oDate.day + ", " + oDate.dd + " " + oDate.month; } }); $("#dtBox").DateTimePicker( { init: function() { oDTP2 = this; }, parentElement: ".cont-datetime", }); $("#btnCurrentDate").click(function() { oDTP1.setDateTimeStringInInputField($("#input-date"), new Date()); }); $("#btnCurrentTime").click(function() { oDTP2.setDateTimeStringInInputField($("#input-time"), new Date()); }); $("#btnCurrentDateTime").click(function() { oDTP2.setDateTimeStringInInputField($("#input-datetime"), new Date()); }); $("#btnGetDate").click(function() { alert("Date is : " + oDTP1.getDateObjectForInputField($("#input-date"))); }); $("#btnGetTime").click(function() { alert("Time is : " + oDTP2.getDateObjectForInputField($("#input-time"))); }); $("#btnGetDateTime").click(function() { alert("DateTime is : " + oDTP2.getDateObjectForInputField($("#input-datetime"))); }); }); </script> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicExamples-CustomInputValue.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
1,188
```html <!DOCTYPE html> <html> <head> <title>Basic Examples - Set DateTime In Input Field</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" data-format="dd-MMM-yyyy" class= "fillDateTime" id="date1" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" data-format="hh:mm AA" class= "fillDateTime" id="time1" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" data-format="dd-MMM-yyyy hh:mm:ss AA" class= "fillDateTime" id="datetime1" readonly> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" id="date2" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" id="time2" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" id="datetime2" readonly> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" data-format="yyyy-MM-dd" id="date3" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" data-format="hh:mm AA" id="time3" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" data-format="yyyy-MM-dd hh:mm:ss AA" id="datetime3" readonly> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker( { dateFormat: "MM-dd-yyyy", timeFormat: "HH:mm", dateTimeFormat: "MM-dd-yyyy HH:mm:ss AA", addEventHandlers: function() { var dtPickerObj = this; /* // Set DateTime Strings for all elements */ dtPickerObj.setDateTimeStringInInputField($("input")); /* // Set DateTime Strings for a single element dtPickerObj.setDateTimeStringInInputField($("#date1"), new Date(2014, 4, 25, 0, 0, 0, 0)); dtPickerObj.setDateTimeStringInInputField($("#time1"), new Date(2014, 4, 25, 16, 40, 0, 0)); */ /* // Set DateTime Strings for a group of elements dtPickerObj.setDateTimeStringInInputField($(".fillDateTime")); */ } }); }); </script> <!-- Default dateFormat: "dd-MM-yyyy" dateFormat Options : 1. "dd-MM-yyyy" 2. "MM-dd-yyyy" 3. "yyyy-MM-dd" Specify (data-min & data-max) / (minDate & maxDate) values in the same dateFormat specified in settings parameters --> <!-- Default timeFormat: "HH:mm" timeFormat Options : 1. "HH:mm" 2. "hh:mm AA" Specify (data-min & data-max) / (minTime & maxTime) values in the same timeFormat specified in settings parameters --> <!-- Default dateTimeFormat: "dd-MM-yyyy HH:mm:ss" dateTimeFormat Options : 1. "dd-MM-yyyy HH:mm:ss" 2. "dd-MM-yyyy hh:mm:ss AA" 3. "MM-dd-yyyy HH:mm:ss" 4. "MM-dd-yyyy hh:mm:ss AA" 5. "yyyy-MM-dd HH:mm:ss" 6. "yyyy-MM-dd hh:mm:ss AA" Specify (data-min & data-max) / (minDateTime & maxDateTime) values in the same dateTimeFormat specified in settings parameters --> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/BasicExamples-SetDateTimeOnLoad.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
1,210
```html <!DOCTYPE html> <html> <head> <title>Date Picker with AngularJS</title> <link rel="stylesheet" type="text/css" href="../../src/DateTimePicker.css" /> <script type="text/javascript" src="../jquery-1.11.0.min.js"></script> <script type="text/javascript" src="angular-1.4.2.min.js"></script> <script type="text/javascript" src="../../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> <script type="text/javascript"> var dDate1; angular.module("App-DTP", []).controller("Ctrl-DTP", function($scope) { $scope.date1 = new Date(2015, 11, 26, 0, 0, 0, 0); $scope.datestring1 = "26-11-2015"; $scope.setValue = function() { console.log("Before setValue : " + $scope.date1 + " " + $scope.datestring1); $scope.date1 = new Date(dDate1); console.log("After setValue : " + $scope.date1 + " " + $scope.datestring1); }; }); $(document).ready(function() { $("#dtBox").DateTimePicker( { settingValueOfElement: function(sValue, dValue, oInputElement) { dDate1 = dValue; console.log("settingValueOfElement : " + dDate1+ " " + sValue); } }); }); </script> </head> <body ng-app="App-DTP" ng-controller="Ctrl-DTP"> <p>Date : </p> <input type="text" data-field="date" id="ipDate1" ng-model="datestring1" ng-change="setValue()" readonly> <div>Date 1 : {{ datestring1 }}</div> <div id="dtBox"></div> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/AngularJS/BasicDatePicker-AngularJS.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
578
```html <!DOCTYPE html> <html> <head> <title>Keyboard Navigation</title> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker.css" /> <script type="text/javascript" src="jquery-1.11.0.min.js"></script> <script type="text/javascript" src="../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> </head> <body> <form> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" tabindex="1" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" tabindex="2" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" tabindex="3" readonly> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" data-min="01-10-2012" data-max="01-05-2015" tabindex="4" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" data-min="10:00" data-max="16:30" tabindex="5" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" data-min="01-10-2012 09:30" data-max="01-05-2015 17:30" tabindex="6" readonly> </form> <div id="dtBox"></div> <script type="text/javascript"> $(document).ready(function() { $("#dtBox").DateTimePicker({ buttonClicked: function(sButtonType, oInputElement) { console.log(sButtonType + " Button clicked on "); console.log(oInputElement); } }); }); </script> <!-- Default dateFormat: "dd-MM-yyyy" dateFormat Options : 1. "dd-MM-yyyy" 2. "MM-dd-yyyy" 3. "yyyy-MM-dd" Specify (data-min & data-max) / (minDate & maxDate) values in the same dateFormat specified in settings parameters --> <!-- Default timeFormat: "HH:mm" timeFormat Options : 1. "HH:mm" 2. "hh:mm AA" Specify (data-min & data-max) / (minTime & maxTime) values in the same timeFormat specified in settings parameters --> <!-- Default dateTimeFormat: "dd-MM-yyyy HH:mm:ss" dateTimeFormat Options : 1. "dd-MM-yyyy HH:mm:ss" 2. "dd-MM-yyyy hh:mm:ss AA" 3. "MM-dd-yyyy HH:mm:ss" 4. "MM-dd-yyyy hh:mm:ss AA" 5. "yyyy-MM-dd HH:mm:ss" 6. "yyyy-MM-dd hh:mm:ss AA" Specify (data-min & data-max) / (minDateTime & maxDateTime) values in the same dateTimeFormat specified in settings parameters --> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/KeyboardNavigation.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
899
```html <!DOCTYPE html> <html> <head> <title>Date Picker with AngularJS</title> <link rel="stylesheet" type="text/css" href="../../src/DateTimePicker.css" /> <script type="text/javascript" src="../jquery-1.11.0.min.js"></script> <script type="text/javascript" src="angular-1.4.2.min.js"></script> <script type="text/javascript" src="../../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> <script type="text/javascript"> var dQuestionDate, dReviewDate; angular.module("App-DTP", []).controller("Ctrl-DTP", function($scope) { $scope.question = {}; $scope.question.date = new Date(2016, 2, 1, 0, 0, 0, 0); $scope.question.datestr = "01-Mar-2016"; $scope.question.setValue = function() { console.log("Before question.setValue : " + $scope.question.date + " " + $scope.question.datestr); $scope.question.date = new Date(dQuestionDate); console.log("After question.setValue : " + $scope.question.date + " " + $scope.question.datestr); }; $scope.reviews = {}; $scope.reviews.date = new Date(2016, 2, 15, 0, 0, 0, 0); $scope.reviews.datestr = "15-Mar-2016"; $scope.reviews.setValue = function() { console.log("Before review.setValue : " + $scope.reviews.date + " " + $scope.reviews.datestr); $scope.reviews.date = new Date(dQuestionDate); console.log("After review.setValue : " + $scope.reviews.date + " " + $scope.reviews.datestr); }; }); $(document).ready(function() { $('#dtBox-1').DateTimePicker( { parentElement: ".questionsDateDiv", dateFormat: "dd-MMM-yyyy", addEventHandlers: function() { var oDTP = this; oDTP.settings.minDate = oDTP.getDateTimeStringInFormat("Date", "dd-MMM-yyyy", new Date()); }, settingValueOfElement: function(sValue, dValue, oInputElement) { dQuestionDate = dValue; console.log("settingValueOfElement dQuestionDate : " + dQuestionDate+ " " + sValue); } }); $('#dtBox-2').DateTimePicker( { parentElement: ".reviewDateDiv", dateFormat: "dd-MMM-yyyy", addEventHandlers: function() { var oDTP = this; oDTP.settings.maxDate = oDTP.getDateTimeStringInFormat("Date", "dd-MMM-yyyy", new Date()); }, settingValueOfElement: function(sValue, dValue, oInputElement) { dReviewDate = dValue; console.log("settingValueOfElement dReviewDate : " + dReviewDate+ " " + sValue); } }); }); </script> </head> <body ng-app="App-DTP" ng-controller="Ctrl-DTP"> <div class="questionsDateDiv"> <p>Question Date : {{ question.datestr }}</p> <input type="text" name="questionDate" id="question_date" data-field="date" ng-model="question.datestr" placeholder="Pick a suitable date" ng-change="question.setValue()" readonly required /> </div> <div class="reviewDateDiv"> <p>Review Date : {{ reviews.datestr }}</p> <input type="text" name="reviewDate" id="review_date" data-field="date" ng-model="reviews.datestr" placeholder="Date Hired (optional)" ng-change="reviews.setValue()" readonly required /> </div> <div id="dtBox-1"></div> <div id="dtBox-2"></div> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/AngularJS/TwoPicker-AngularJS.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
1,045
```html <!DOCTYPE html> <html> <head> <title>long type of model in AngularJS</title> <link rel="stylesheet" type="text/css" href="../../src/DateTimePicker.css" /> <script type="text/javascript" src="../jquery-1.11.0.min.js"></script> <script type="text/javascript" src="angular-1.4.2.min.js"></script> <script type="text/javascript" src="../../src/DateTimePicker.js"></script> <!--[if lt IE 9]> <link rel="stylesheet" type="text/css" href="../src/DateTimePicker-ltie9.css" /> <script type="text/javascript" src="../src/DateTimePicker-ltie9.js"></script> <![endif]--> <style type="text/css"> p { margin-left: 20px; } input { width: 200px; padding: 10px; margin-left: 20px; margin-bottom: 20px; } </style> <script type="text/javascript"> var dDate1; angular.module("App-DTP", []).controller("Ctrl-DTP", function($scope) { $scope.datestring = "3600000"; }) .directive('dateFormat', ['$filter',function($filter) { var dateFilter = $filter('date'); return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { function formatter(value) { return dateFilter(value, 'HH:mm'); //format } ctrl.$formatters.push(formatter); } }; }]); $(document).ready(function() { $("#dtBox").DateTimePicker( { }); }); </script> </head> <body ng-app="App-DTP" ng-controller="Ctrl-DTP"> <p>Time : </p> <input type="text" date-format data-field="time" ng-model="datestring" > <div>Time : {{ datestring }}</div> <div id="dtBox"></div> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/AngularJS/BasicDatePicker-LongTypeOfModel.html
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
508
```javascript /* AngularJS v1.4.2 (c) 2010-2015 Google, Inc. path_to_url */ (function(O,U,t){'use strict';function J(b){return function(){var a=arguments[0],c;c="["+(b?b+":":"")+a+"] path_to_url"+(b?b+"/":"")+a;for(a=1;a<arguments.length;a++){c=c+(1==a?"?":"&")+"p"+(a-1)+"=";var d=encodeURIComponent,e;e=arguments[a];e="function"==typeof e?e.toString().replace(/ \{[\s\S]*$/,""):"undefined"==typeof e?"undefined":"string"!=typeof e?JSON.stringify(e):e;c+=d(e)}return Error(c)}}function Ea(b){if(null==b||Wa(b))return!1;var a="length"in Object(b)&&b.length; return b.nodeType===qa&&a?!0:L(b)||G(b)||0===a||"number"===typeof a&&0<a&&a-1 in b}function m(b,a,c){var d,e;if(b)if(z(b))for(d in b)"prototype"==d||"length"==d||"name"==d||b.hasOwnProperty&&!b.hasOwnProperty(d)||a.call(c,b[d],d,b);else if(G(b)||Ea(b)){var f="object"!==typeof b;d=0;for(e=b.length;d<e;d++)(f||d in b)&&a.call(c,b[d],d,b)}else if(b.forEach&&b.forEach!==m)b.forEach(a,c,b);else if(nc(b))for(d in b)a.call(c,b[d],d,b);else if("function"===typeof b.hasOwnProperty)for(d in b)b.hasOwnProperty(d)&& a.call(c,b[d],d,b);else for(d in b)Xa.call(b,d)&&a.call(c,b[d],d,b);return b}function oc(b,a,c){for(var d=Object.keys(b).sort(),e=0;e<d.length;e++)a.call(c,b[d[e]],d[e]);return d}function pc(b){return function(a,c){b(c,a)}}function Ud(){return++nb}function qc(b,a){a?b.$$hashKey=a:delete b.$$hashKey}function Nb(b,a,c){for(var d=b.$$hashKey,e=0,f=a.length;e<f;++e){var g=a[e];if(H(g)||z(g))for(var h=Object.keys(g),l=0,k=h.length;l<k;l++){var n=h[l],r=g[n];c&&H(r)?aa(r)?b[n]=new Date(r.valueOf()):(H(b[n])|| (b[n]=G(r)?[]:{}),Nb(b[n],[r],!0)):b[n]=r}}qc(b,d);return b}function P(b){return Nb(b,za.call(arguments,1),!1)}function Vd(b){return Nb(b,za.call(arguments,1),!0)}function W(b){return parseInt(b,10)}function Ob(b,a){return P(Object.create(b),a)}function v(){}function Ya(b){return b}function ra(b){return function(){return b}}function rc(b){return z(b.toString)&&b.toString!==Object.prototype.toString}function A(b){return"undefined"===typeof b}function w(b){return"undefined"!==typeof b}function H(b){return null!== b&&"object"===typeof b}function nc(b){return null!==b&&"object"===typeof b&&!sc(b)}function L(b){return"string"===typeof b}function V(b){return"number"===typeof b}function aa(b){return"[object Date]"===sa.call(b)}function z(b){return"function"===typeof b}function Za(b){return"[object RegExp]"===sa.call(b)}function Wa(b){return b&&b.window===b}function $a(b){return b&&b.$evalAsync&&b.$watch}function ab(b){return"boolean"===typeof b}function tc(b){return!(!b||!(b.nodeName||b.prop&&b.attr&&b.find))} function Wd(b){var a={};b=b.split(",");var c;for(c=0;c<b.length;c++)a[b[c]]=!0;return a}function ta(b){return M(b.nodeName||b[0]&&b[0].nodeName)}function bb(b,a){var c=b.indexOf(a);0<=c&&b.splice(c,1);return c}function fa(b,a,c,d){if(Wa(b)||$a(b))throw Fa("cpws");if(uc.test(sa.call(a)))throw Fa("cpta");if(a){if(b===a)throw Fa("cpi");c=c||[];d=d||[];H(b)&&(c.push(b),d.push(a));var e;if(G(b))for(e=a.length=0;e<b.length;e++)a.push(fa(b[e],null,c,d));else{var f=a.$$hashKey;G(a)?a.length=0:m(a,function(b, c){delete a[c]});if(nc(b))for(e in b)a[e]=fa(b[e],null,c,d);else if(b&&"function"===typeof b.hasOwnProperty)for(e in b)b.hasOwnProperty(e)&&(a[e]=fa(b[e],null,c,d));else for(e in b)Xa.call(b,e)&&(a[e]=fa(b[e],null,c,d));qc(a,f)}}else if(a=b,H(b)){if(c&&-1!==(f=c.indexOf(b)))return d[f];if(G(b))return fa(b,[],c,d);if(uc.test(sa.call(b)))a=new b.constructor(b);else if(aa(b))a=new Date(b.getTime());else if(Za(b))a=new RegExp(b.source,b.toString().match(/[^\/]*$/)[0]),a.lastIndex=b.lastIndex;else return e= Object.create(sc(b)),fa(b,e,c,d);d&&(c.push(b),d.push(a))}return a}function ia(b,a){if(G(b)){a=a||[];for(var c=0,d=b.length;c<d;c++)a[c]=b[c]}else if(H(b))for(c in a=a||{},b)if("$"!==c.charAt(0)||"$"!==c.charAt(1))a[c]=b[c];return a||b}function ka(b,a){if(b===a)return!0;if(null===b||null===a)return!1;if(b!==b&&a!==a)return!0;var c=typeof b,d;if(c==typeof a&&"object"==c)if(G(b)){if(!G(a))return!1;if((c=b.length)==a.length){for(d=0;d<c;d++)if(!ka(b[d],a[d]))return!1;return!0}}else{if(aa(b))return aa(a)? ka(b.getTime(),a.getTime()):!1;if(Za(b))return Za(a)?b.toString()==a.toString():!1;if($a(b)||$a(a)||Wa(b)||Wa(a)||G(a)||aa(a)||Za(a))return!1;c=ga();for(d in b)if("$"!==d.charAt(0)&&!z(b[d])){if(!ka(b[d],a[d]))return!1;c[d]=!0}for(d in a)if(!(d in c||"$"===d.charAt(0)||a[d]===t||z(a[d])))return!1;return!0}return!1}function cb(b,a,c){return b.concat(za.call(a,c))}function vc(b,a){var c=2<arguments.length?za.call(arguments,2):[];return!z(a)||a instanceof RegExp?a:c.length?function(){return arguments.length? a.apply(b,cb(c,arguments,0)):a.apply(b,c)}:function(){return arguments.length?a.apply(b,arguments):a.call(b)}}function Xd(b,a){var c=a;"string"===typeof b&&"$"===b.charAt(0)&&"$"===b.charAt(1)?c=t:Wa(a)?c="$WINDOW":a&&U===a?c="$DOCUMENT":$a(a)&&(c="$SCOPE");return c}function db(b,a){if("undefined"===typeof b)return t;V(a)||(a=a?2:null);return JSON.stringify(b,Xd,a)}function wc(b){return L(b)?JSON.parse(b):b}function xc(b,a){var c=Date.parse("Jan 01, 1970 00:00:00 "+b)/6E4;return isNaN(c)?a:c}function Pb(b, a,c){c=c?-1:1;var d=xc(a,b.getTimezoneOffset());a=b;b=c*(d-b.getTimezoneOffset());a=new Date(a.getTime());a.setMinutes(a.getMinutes()+b);return a}function ua(b){b=y(b).clone();try{b.empty()}catch(a){}var c=y("<div>").append(b).html();try{return b[0].nodeType===Na?M(c):c.match(/^(<[^>]+>)/)[1].replace(/^<([\w\-]+)/,function(a,b){return"<"+M(b)})}catch(d){return M(c)}}function yc(b){try{return decodeURIComponent(b)}catch(a){}}function zc(b){var a={},c,d;m((b||"").split("&"),function(b){b&&(c=b.replace(/\+/g, "%20").split("="),d=yc(c[0]),w(d)&&(b=w(c[1])?yc(c[1]):!0,Xa.call(a,d)?G(a[d])?a[d].push(b):a[d]=[a[d],b]:a[d]=b))});return a}function Qb(b){var a=[];m(b,function(b,d){G(b)?m(b,function(b){a.push(ma(d,!0)+(!0===b?"":"="+ma(b,!0)))}):a.push(ma(d,!0)+(!0===b?"":"="+ma(b,!0)))});return a.length?a.join("&"):""}function ob(b){return ma(b,!0).replace(/%26/gi,"&").replace(/%3D/gi,"=").replace(/%2B/gi,"+")}function ma(b,a){return encodeURIComponent(b).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g, "$").replace(/%2C/gi,",").replace(/%3B/gi,";").replace(/%20/g,a?"%20":"+")}function Yd(b,a){var c,d,e=Oa.length;for(d=0;d<e;++d)if(c=Oa[d]+a,L(c=b.getAttribute(c)))return c;return null}function Zd(b,a){var c,d,e={};m(Oa,function(a){a+="app";!c&&b.hasAttribute&&b.hasAttribute(a)&&(c=b,d=b.getAttribute(a))});m(Oa,function(a){a+="app";var e;!c&&(e=b.querySelector("["+a.replace(":","\\:")+"]"))&&(c=e,d=e.getAttribute(a))});c&&(e.strictDi=null!==Yd(c,"strict-di"),a(c,d?[d]:[],e))}function Ac(b,a,c){H(c)|| (c={});c=P({strictDi:!1},c);var d=function(){b=y(b);if(b.injector()){var d=b[0]===U?"document":ua(b);throw Fa("btstrpd",d.replace(/</,"&lt;").replace(/>/,"&gt;"));}a=a||[];a.unshift(["$provide",function(a){a.value("$rootElement",b)}]);c.debugInfoEnabled&&a.push(["$compileProvider",function(a){a.debugInfoEnabled(!0)}]);a.unshift("ng");d=eb(a,c.strictDi);d.invoke(["$rootScope","$rootElement","$compile","$injector",function(a,b,c,d){a.$apply(function(){b.data("$injector",d);c(b)(a)})}]);return d},e= /^NG_ENABLE_DEBUG_INFO!/,f=/^NG_DEFER_BOOTSTRAP!/;O&&e.test(O.name)&&(c.debugInfoEnabled=!0,O.name=O.name.replace(e,""));if(O&&!f.test(O.name))return d();O.name=O.name.replace(f,"");ca.resumeBootstrap=function(b){m(b,function(b){a.push(b)});return d()};z(ca.resumeDeferredBootstrap)&&ca.resumeDeferredBootstrap()}function $d(){O.name="NG_ENABLE_DEBUG_INFO!"+O.name;O.location.reload()}function ae(b){b=ca.element(b).injector();if(!b)throw Fa("test");return b.get("$$testability")}function Bc(b,a){a=a|| "_";return b.replace(be,function(b,d){return(d?a:"")+b.toLowerCase()})}function ce(){var b;if(!Cc){var a=pb();la=O.jQuery;w(a)&&(la=null===a?t:O[a]);la&&la.fn.on?(y=la,P(la.fn,{scope:Pa.scope,isolateScope:Pa.isolateScope,controller:Pa.controller,injector:Pa.injector,inheritedData:Pa.inheritedData}),b=la.cleanData,la.cleanData=function(a){var d;if(Rb)Rb=!1;else for(var e=0,f;null!=(f=a[e]);e++)(d=la._data(f,"events"))&&d.$destroy&&la(f).triggerHandler("$destroy");b(a)}):y=Q;ca.element=y;Cc=!0}}function Sb(b, a,c){if(!b)throw Fa("areq",a||"?",c||"required");return b}function Qa(b,a,c){c&&G(b)&&(b=b[b.length-1]);Sb(z(b),a,"not a function, got "+(b&&"object"===typeof b?b.constructor.name||"Object":typeof b));return b}function Ra(b,a){if("hasOwnProperty"===b)throw Fa("badname",a);}function Dc(b,a,c){if(!a)return b;a=a.split(".");for(var d,e=b,f=a.length,g=0;g<f;g++)d=a[g],b&&(b=(e=b)[d]);return!c&&z(b)?vc(e,b):b}function qb(b){var a=b[0];b=b[b.length-1];var c=[a];do{a=a.nextSibling;if(!a)break;c.push(a)}while(a!== b);return y(c)}function ga(){return Object.create(null)}function de(b){function a(a,b,c){return a[b]||(a[b]=c())}var c=J("$injector"),d=J("ng");b=a(b,"angular",Object);b.$$minErr=b.$$minErr||J;return a(b,"module",function(){var b={};return function(f,g,h){if("hasOwnProperty"===f)throw d("badname","module");g&&b.hasOwnProperty(f)&&(b[f]=null);return a(b,f,function(){function a(b,c,e,f){f||(f=d);return function(){f[e||"push"]([b,c,arguments]);return C}}function b(a,c){return function(b,e){e&&z(e)&& (e.$$moduleName=f);d.push([a,c,arguments]);return C}}if(!g)throw c("nomod",f);var d=[],e=[],s=[],x=a("$injector","invoke","push",e),C={_invokeQueue:d,_configBlocks:e,_runBlocks:s,requires:g,name:f,provider:b("$provide","provider"),factory:b("$provide","factory"),service:b("$provide","service"),value:a("$provide","value"),constant:a("$provide","constant","unshift"),decorator:b("$provide","decorator"),animation:b("$animateProvider","register"),filter:b("$filterProvider","register"),controller:b("$controllerProvider", "register"),directive:b("$compileProvider","directive"),config:x,run:function(a){s.push(a);return this}};h&&x(h);return C})}})}function ee(b){P(b,{bootstrap:Ac,copy:fa,extend:P,merge:Vd,equals:ka,element:y,forEach:m,injector:eb,noop:v,bind:vc,toJson:db,fromJson:wc,identity:Ya,isUndefined:A,isDefined:w,isString:L,isFunction:z,isObject:H,isNumber:V,isElement:tc,isArray:G,version:fe,isDate:aa,lowercase:M,uppercase:rb,callbacks:{counter:0},getTestability:ae,$$minErr:J,$$csp:fb,reloadWithDebugInfo:$d}); gb=de(O);try{gb("ngLocale")}catch(a){gb("ngLocale",[]).provider("$locale",ge)}gb("ng",["ngLocale"],["$provide",function(a){a.provider({$$sanitizeUri:he});a.provider("$compile",Ec).directive({a:ie,input:Fc,textarea:Fc,form:je,script:ke,select:le,style:me,option:ne,ngBind:oe,ngBindHtml:pe,ngBindTemplate:qe,ngClass:re,ngClassEven:se,ngClassOdd:te,ngCloak:ue,ngController:ve,ngForm:we,ngHide:xe,ngIf:ye,ngInclude:ze,ngInit:Ae,ngNonBindable:Be,ngPluralize:Ce,ngRepeat:De,ngShow:Ee,ngStyle:Fe,ngSwitch:Ge, ngSwitchWhen:He,ngSwitchDefault:Ie,ngOptions:Je,ngTransclude:Ke,ngModel:Le,ngList:Me,ngChange:Ne,pattern:Gc,ngPattern:Gc,required:Hc,ngRequired:Hc,minlength:Ic,ngMinlength:Ic,maxlength:Jc,ngMaxlength:Jc,ngValue:Oe,ngModelOptions:Pe}).directive({ngInclude:Qe}).directive(sb).directive(Kc);a.provider({$anchorScroll:Re,$animate:Se,$$animateQueue:Te,$$AnimateRunner:Ue,$browser:Ve,$cacheFactory:We,$controller:Xe,$document:Ye,$exceptionHandler:Ze,$filter:Lc,$interpolate:$e,$interval:af,$http:bf,$httpParamSerializer:cf, $httpParamSerializerJQLike:df,$httpBackend:ef,$location:ff,$log:gf,$parse:hf,$rootScope:jf,$q:kf,$$q:lf,$sce:mf,$sceDelegate:nf,$sniffer:of,$templateCache:pf,$templateRequest:qf,$$testability:rf,$timeout:sf,$window:tf,$$rAF:uf,$$asyncCallback:vf,$$jqLite:wf,$$HashMap:xf,$$cookieReader:yf})}])}function hb(b){return b.replace(zf,function(a,b,d,e){return e?d.toUpperCase():d}).replace(Af,"Moz$1")}function Mc(b){b=b.nodeType;return b===qa||!b||9===b}function Nc(b,a){var c,d,e=a.createDocumentFragment(), f=[];if(Tb.test(b)){c=c||e.appendChild(a.createElement("div"));d=(Bf.exec(b)||["",""])[1].toLowerCase();d=na[d]||na._default;c.innerHTML=d[1]+b.replace(Cf,"<$1></$2>")+d[2];for(d=d[0];d--;)c=c.lastChild;f=cb(f,c.childNodes);c=e.firstChild;c.textContent=""}else f.push(a.createTextNode(b));e.textContent="";e.innerHTML="";m(f,function(a){e.appendChild(a)});return e}function Q(b){if(b instanceof Q)return b;var a;L(b)&&(b=R(b),a=!0);if(!(this instanceof Q)){if(a&&"<"!=b.charAt(0))throw Ub("nosel");return new Q(b)}if(a){a= U;var c;b=(c=Df.exec(b))?[a.createElement(c[1])]:(c=Nc(b,a))?c.childNodes:[]}Oc(this,b)}function Vb(b){return b.cloneNode(!0)}function tb(b,a){a||ub(b);if(b.querySelectorAll)for(var c=b.querySelectorAll("*"),d=0,e=c.length;d<e;d++)ub(c[d])}function Pc(b,a,c,d){if(w(d))throw Ub("offargs");var e=(d=vb(b))&&d.events,f=d&&d.handle;if(f)if(a)m(a.split(" "),function(a){if(w(c)){var d=e[a];bb(d||[],c);if(d&&0<d.length)return}b.removeEventListener(a,f,!1);delete e[a]});else for(a in e)"$destroy"!==a&&b.removeEventListener(a, f,!1),delete e[a]}function ub(b,a){var c=b.ng339,d=c&&ib[c];d&&(a?delete d.data[a]:(d.handle&&(d.events.$destroy&&d.handle({},"$destroy"),Pc(b)),delete ib[c],b.ng339=t))}function vb(b,a){var c=b.ng339,c=c&&ib[c];a&&!c&&(b.ng339=c=++Ef,c=ib[c]={events:{},data:{},handle:t});return c}function Wb(b,a,c){if(Mc(b)){var d=w(c),e=!d&&a&&!H(a),f=!a;b=(b=vb(b,!e))&&b.data;if(d)b[a]=c;else{if(f)return b;if(e)return b&&b[a];P(b,a)}}}function wb(b,a){return b.getAttribute?-1<(" "+(b.getAttribute("class")||"")+ " ").replace(/[\n\t]/g," ").indexOf(" "+a+" "):!1}function xb(b,a){a&&b.setAttribute&&m(a.split(" "),function(a){b.setAttribute("class",R((" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ").replace(" "+R(a)+" "," ")))})}function yb(b,a){if(a&&b.setAttribute){var c=(" "+(b.getAttribute("class")||"")+" ").replace(/[\n\t]/g," ");m(a.split(" "),function(a){a=R(a);-1===c.indexOf(" "+a+" ")&&(c+=a+" ")});b.setAttribute("class",R(c))}}function Oc(b,a){if(a)if(a.nodeType)b[b.length++]=a;else{var c= a.length;if("number"===typeof c&&a.window!==a){if(c)for(var d=0;d<c;d++)b[b.length++]=a[d]}else b[b.length++]=a}}function Qc(b,a){return zb(b,"$"+(a||"ngController")+"Controller")}function zb(b,a,c){9==b.nodeType&&(b=b.documentElement);for(a=G(a)?a:[a];b;){for(var d=0,e=a.length;d<e;d++)if((c=y.data(b,a[d]))!==t)return c;b=b.parentNode||11===b.nodeType&&b.host}}function Rc(b){for(tb(b,!0);b.firstChild;)b.removeChild(b.firstChild)}function Xb(b,a){a||tb(b);var c=b.parentNode;c&&c.removeChild(b)}function Ff(b, a){a=a||O;if("complete"===a.document.readyState)a.setTimeout(b);else y(a).on("load",b)}function Sc(b,a){var c=Ab[a.toLowerCase()];return c&&Tc[ta(b)]&&c}function Gf(b,a){var c=b.nodeName;return("INPUT"===c||"TEXTAREA"===c)&&Uc[a]}function Hf(b,a){var c=function(c,e){c.isDefaultPrevented=function(){return c.defaultPrevented};var f=a[e||c.type],g=f?f.length:0;if(g){if(A(c.immediatePropagationStopped)){var h=c.stopImmediatePropagation;c.stopImmediatePropagation=function(){c.immediatePropagationStopped= !0;c.stopPropagation&&c.stopPropagation();h&&h.call(c)}}c.isImmediatePropagationStopped=function(){return!0===c.immediatePropagationStopped};1<g&&(f=ia(f));for(var l=0;l<g;l++)c.isImmediatePropagationStopped()||f[l].call(b,c)}};c.elem=b;return c}function wf(){this.$get=function(){return P(Q,{hasClass:function(b,a){b.attr&&(b=b[0]);return wb(b,a)},addClass:function(b,a){b.attr&&(b=b[0]);return yb(b,a)},removeClass:function(b,a){b.attr&&(b=b[0]);return xb(b,a)}})}}function Ga(b,a){var c=b&&b.$$hashKey; if(c)return"function"===typeof c&&(c=b.$$hashKey()),c;c=typeof b;return c="function"==c||"object"==c&&null!==b?b.$$hashKey=c+":"+(a||Ud)():c+":"+b}function Sa(b,a){if(a){var c=0;this.nextUid=function(){return++c}}m(b,this.put,this)}function If(b){return(b=b.toString().replace(Vc,"").match(Wc))?"function("+(b[1]||"").replace(/[\s\r\n]+/," ")+")":"fn"}function eb(b,a){function c(a){return function(b,c){if(H(b))m(b,pc(a));else return a(b,c)}}function d(a,b){Ra(a,"service");if(z(b)||G(b))b=s.instantiate(b); if(!b.$get)throw Ha("pget",a);return r[a+"Provider"]=b}function e(a,b){return function(){var c=C.invoke(b,this);if(A(c))throw Ha("undef",a);return c}}function f(a,b,c){return d(a,{$get:!1!==c?e(a,b):b})}function g(a){var b=[],c;m(a,function(a){function d(a){var b,c;b=0;for(c=a.length;b<c;b++){var e=a[b],f=s.get(e[0]);f[e[1]].apply(f,e[2])}}if(!n.get(a)){n.put(a,!0);try{L(a)?(c=gb(a),b=b.concat(g(c.requires)).concat(c._runBlocks),d(c._invokeQueue),d(c._configBlocks)):z(a)?b.push(s.invoke(a)):G(a)? b.push(s.invoke(a)):Qa(a,"module")}catch(e){throw G(a)&&(a=a[a.length-1]),e.message&&e.stack&&-1==e.stack.indexOf(e.message)&&(e=e.message+"\n"+e.stack),Ha("modulerr",a,e.stack||e.message||e);}}});return b}function h(b,c){function d(a,e){if(b.hasOwnProperty(a)){if(b[a]===l)throw Ha("cdep",a+" <- "+k.join(" <- "));return b[a]}try{return k.unshift(a),b[a]=l,b[a]=c(a,e)}catch(f){throw b[a]===l&&delete b[a],f;}finally{k.shift()}}function e(b,c,f,g){"string"===typeof f&&(g=f,f=null);var h=[],k=eb.$$annotate(b, a,g),l,s,n;s=0;for(l=k.length;s<l;s++){n=k[s];if("string"!==typeof n)throw Ha("itkn",n);h.push(f&&f.hasOwnProperty(n)?f[n]:d(n,g))}G(b)&&(b=b[l]);return b.apply(c,h)}return{invoke:e,instantiate:function(a,b,c){var d=Object.create((G(a)?a[a.length-1]:a).prototype||null);a=e(a,d,b,c);return H(a)||z(a)?a:d},get:d,annotate:eb.$$annotate,has:function(a){return r.hasOwnProperty(a+"Provider")||b.hasOwnProperty(a)}}}a=!0===a;var l={},k=[],n=new Sa([],!0),r={$provide:{provider:c(d),factory:c(f),service:c(function(a, b){return f(a,["$injector",function(a){return a.instantiate(b)}])}),value:c(function(a,b){return f(a,ra(b),!1)}),constant:c(function(a,b){Ra(a,"constant");r[a]=b;x[a]=b}),decorator:function(a,b){var c=s.get(a+"Provider"),d=c.$get;c.$get=function(){var a=C.invoke(d,c);return C.invoke(b,null,{$delegate:a})}}}},s=r.$injector=h(r,function(a,b){ca.isString(b)&&k.push(b);throw Ha("unpr",k.join(" <- "));}),x={},C=x.$injector=h(x,function(a,b){var c=s.get(a+"Provider",b);return C.invoke(c.$get,c,t,a)});m(g(b), function(a){a&&C.invoke(a)});return C}function Re(){var b=!0;this.disableAutoScrolling=function(){b=!1};this.$get=["$window","$location","$rootScope",function(a,c,d){function e(a){var b=null;Array.prototype.some.call(a,function(a){if("a"===ta(a))return b=a,!0});return b}function f(b){if(b){b.scrollIntoView();var c;c=g.yOffset;z(c)?c=c():tc(c)?(c=c[0],c="fixed"!==a.getComputedStyle(c).position?0:c.getBoundingClientRect().bottom):V(c)||(c=0);c&&(b=b.getBoundingClientRect().top,a.scrollBy(0,b-c))}else a.scrollTo(0, 0)}function g(a){a=L(a)?a:c.hash();var b;a?(b=h.getElementById(a))?f(b):(b=e(h.getElementsByName(a)))?f(b):"top"===a&&f(null):f(null)}var h=a.document;b&&d.$watch(function(){return c.hash()},function(a,b){a===b&&""===a||Ff(function(){d.$evalAsync(g)})});return g}]}function jb(b,a){if(!b&&!a)return"";if(!b)return a;if(!a)return b;G(b)&&(b=b.join(" "));G(a)&&(a=a.join(" "));return b+" "+a}function Jf(b){L(b)&&(b=b.split(" "));var a=ga();m(b,function(b){b.length&&(a[b]=!0)});return a}function Ia(b){return H(b)? b:{}}function vf(){this.$get=["$$rAF","$timeout",function(b,a){return b.supported?function(a){return b(a)}:function(b){return a(b,0,!1)}}]}function Kf(b,a,c,d){function e(a){try{a.apply(null,za.call(arguments,1))}finally{if(C--,0===C)for(;F.length;)try{F.pop()()}catch(b){c.error(b)}}}function f(){g();h()}function g(){a:{try{u=n.state;break a}catch(a){}u=void 0}u=A(u)?null:u;ka(u,D)&&(u=D);D=u}function h(){if(K!==l.url()||p!==u)K=l.url(),p=u,m(B,function(a){a(l.url(),u)})}var l=this,k=b.location,n= b.history,r=b.setTimeout,s=b.clearTimeout,x={};l.isMock=!1;var C=0,F=[];l.$$completeOutstandingRequest=e;l.$$incOutstandingRequestCount=function(){C++};l.notifyWhenNoOutstandingRequests=function(a){0===C?a():F.push(a)};var u,p,K=k.href,q=a.find("base"),I=null;g();p=u;l.url=function(a,c,e){A(e)&&(e=null);k!==b.location&&(k=b.location);n!==b.history&&(n=b.history);if(a){var f=p===e;if(K===a&&(!d.history||f))return l;var h=K&&Ja(K)===Ja(a);K=a;p=e;if(!d.history||h&&f){if(!h||I)I=a;c?k.replace(a):h?(c= k,e=a.indexOf("#"),a=-1===e?"":a.substr(e),c.hash=a):k.href=a}else n[c?"replaceState":"pushState"](e,"",a),g(),p=u;return l}return I||k.href.replace(/%27/g,"'")};l.state=function(){return u};var B=[],N=!1,D=null;l.onUrlChange=function(a){if(!N){if(d.history)y(b).on("popstate",f);y(b).on("hashchange",f);N=!0}B.push(a);return a};l.$$applicationDestroyed=function(){y(b).off("hashchange popstate",f)};l.$$checkUrlChange=h;l.baseHref=function(){var a=q.attr("href");return a?a.replace(/^(https?\:)?\/\/[^\/]*/, ""):""};l.defer=function(a,b){var c;C++;c=r(function(){delete x[c];e(a)},b||0);x[c]=!0;return c};l.defer.cancel=function(a){return x[a]?(delete x[a],s(a),e(v),!0):!1}}function Ve(){this.$get=["$window","$log","$sniffer","$document",function(b,a,c,d){return new Kf(b,d,a,c)}]}function We(){this.$get=function(){function b(b,d){function e(a){a!=r&&(s?s==a&&(s=a.n):s=a,f(a.n,a.p),f(a,r),r=a,r.n=null)}function f(a,b){a!=b&&(a&&(a.p=b),b&&(b.n=a))}if(b in a)throw J("$cacheFactory")("iid",b);var g=0,h=P({}, d,{id:b}),l={},k=d&&d.capacity||Number.MAX_VALUE,n={},r=null,s=null;return a[b]={put:function(a,b){if(!A(b)){if(k<Number.MAX_VALUE){var c=n[a]||(n[a]={key:a});e(c)}a in l||g++;l[a]=b;g>k&&this.remove(s.key);return b}},get:function(a){if(k<Number.MAX_VALUE){var b=n[a];if(!b)return;e(b)}return l[a]},remove:function(a){if(k<Number.MAX_VALUE){var b=n[a];if(!b)return;b==r&&(r=b.p);b==s&&(s=b.n);f(b.n,b.p);delete n[a]}delete l[a];g--},removeAll:function(){l={};g=0;n={};r=s=null},destroy:function(){n=h= l=null;delete a[b]},info:function(){return P({},h,{size:g})}}}var a={};b.info=function(){var b={};m(a,function(a,e){b[e]=a.info()});return b};b.get=function(b){return a[b]};return b}}function pf(){this.$get=["$cacheFactory",function(b){return b("templates")}]}function Ec(b,a){function c(a,b,c){var d=/^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/,e={};m(a,function(a,f){var g=a.match(d);if(!g)throw ea("iscp",b,f,a,c?"controller bindings definition":"isolate scope definition");e[f]={mode:g[1][0],collection:"*"=== g[2],optional:"?"===g[3],attrName:g[4]||f}});return e}function d(a){var b=a.charAt(0);if(!b||b!==M(b))throw ea("baddir",a);if(a!==a.trim())throw ea("baddir",a);}var e={},f=/^\s*directive\:\s*([\w\-]+)\s+(.*)$/,g=/(([\w\-]+)(?:\:([^;]+))?;?)/,h=Wd("ngSrc,ngSrcset,src,srcset"),l=/^(?:(\^\^?)?(\?)?(\^\^?)?)?/,k=/^(on[a-z]+|formaction)$/;this.directive=function s(a,f){Ra(a,"directive");L(a)?(d(a),Sb(f,"directiveFactory"),e.hasOwnProperty(a)||(e[a]=[],b.factory(a+"Directive",["$injector","$exceptionHandler", function(b,d){var f=[];m(e[a],function(e,g){try{var h=b.invoke(e);z(h)?h={compile:ra(h)}:!h.compile&&h.link&&(h.compile=ra(h.link));h.priority=h.priority||0;h.index=g;h.name=h.name||a;h.require=h.require||h.controller&&h.name;h.restrict=h.restrict||"EA";var k=h,l=h,s=h.name,n={isolateScope:null,bindToController:null};H(l.scope)&&(!0===l.bindToController?(n.bindToController=c(l.scope,s,!0),n.isolateScope={}):n.isolateScope=c(l.scope,s,!1));H(l.bindToController)&&(n.bindToController=c(l.bindToController, s,!0));if(H(n.bindToController)){var C=l.controller,$=l.controllerAs;if(!C)throw ea("noctrl",s);var ha;a:if($&&L($))ha=$;else{if(L(C)){var m=Xc.exec(C);if(m){ha=m[3];break a}}ha=void 0}if(!ha)throw ea("noident",s);}var q=k.$$bindings=n;H(q.isolateScope)&&(h.$$isolateBindings=q.isolateScope);h.$$moduleName=e.$$moduleName;f.push(h)}catch(t){d(t)}});return f}])),e[a].push(f)):m(a,pc(s));return this};this.aHrefSanitizationWhitelist=function(b){return w(b)?(a.aHrefSanitizationWhitelist(b),this):a.aHrefSanitizationWhitelist()}; this.imgSrcSanitizationWhitelist=function(b){return w(b)?(a.imgSrcSanitizationWhitelist(b),this):a.imgSrcSanitizationWhitelist()};var n=!0;this.debugInfoEnabled=function(a){return w(a)?(n=a,this):n};this.$get=["$injector","$interpolate","$exceptionHandler","$templateRequest","$parse","$controller","$rootScope","$document","$sce","$animate","$$sanitizeUri",function(a,b,c,d,u,p,K,q,I,B,N){function D(a,b){try{a.addClass(b)}catch(c){}}function Z(a,b,c,d,e){a instanceof y||(a=y(a));m(a,function(b,c){b.nodeType== Na&&b.nodeValue.match(/\S+/)&&(a[c]=y(b).wrap("<span></span>").parent()[0])});var f=S(a,b,a,c,d,e);Z.$$addScopeClass(a);var g=null;return function(b,c,d){Sb(b,"scope");d=d||{};var e=d.parentBoundTranscludeFn,h=d.transcludeControllers;d=d.futureParentElement;e&&e.$$boundTransclude&&(e=e.$$boundTransclude);g||(g=(d=d&&d[0])?"foreignobject"!==ta(d)&&d.toString().match(/SVG/)?"svg":"html":"html");d="html"!==g?y(Yb(g,y("<div>").append(a).html())):c?Pa.clone.call(a):a;if(h)for(var k in h)d.data("$"+k+"Controller", h[k].instance);Z.$$addScopeInfo(d,b);c&&c(d,b);f&&f(b,d,d,e);return d}}function S(a,b,c,d,e,f){function g(a,c,d,e){var f,k,l,s,n,B,C;if(p)for(C=Array(c.length),s=0;s<h.length;s+=3)f=h[s],C[f]=c[f];else C=c;s=0;for(n=h.length;s<n;)if(k=C[h[s++]],c=h[s++],f=h[s++],c){if(c.scope){if(l=a.$new(),Z.$$addScopeInfo(y(k),l),B=c.$$destroyBindings)c.$$destroyBindings=null,l.$on("$destroyed",B)}else l=a;B=c.transcludeOnThisElement?$(a,c.transclude,e):!c.templateOnThisElement&&e?e:!e&&b?$(a,b):null;c(f,l,k,d, B,c)}else f&&f(a,k.childNodes,t,e)}for(var h=[],k,l,s,n,p,B=0;B<a.length;B++){k=new aa;l=ha(a[B],[],k,0===B?d:t,e);(f=l.length?E(l,a[B],k,b,c,null,[],[],f):null)&&f.scope&&Z.$$addScopeClass(k.$$element);k=f&&f.terminal||!(s=a[B].childNodes)||!s.length?null:S(s,f?(f.transcludeOnThisElement||!f.templateOnThisElement)&&f.transclude:b);if(f||k)h.push(B,f,k),n=!0,p=p||f;f=null}return n?g:null}function $(a,b,c){return function(d,e,f,g,h){d||(d=a.$new(!1,h),d.$$transcluded=!0);return b(d,e,{parentBoundTranscludeFn:c, transcludeControllers:f,futureParentElement:g})}}function ha(a,b,c,d,e){var h=c.$attr,k;switch(a.nodeType){case qa:w(b,wa(ta(a)),"E",d,e);for(var l,s,n,p=a.attributes,B=0,C=p&&p.length;B<C;B++){var x=!1,S=!1;l=p[B];k=l.name;s=R(l.value);l=wa(k);if(n=ia.test(l))k=k.replace(Zc,"").substr(8).replace(/_(.)/g,function(a,b){return b.toUpperCase()});var F=l.replace(/(Start|End)$/,"");A(F)&&l===F+"Start"&&(x=k,S=k.substr(0,k.length-5)+"end",k=k.substr(0,k.length-6));l=wa(k.toLowerCase());h[l]=k;if(n||!c.hasOwnProperty(l))c[l]= s,Sc(a,l)&&(c[l]=!0);V(a,b,s,l,n);w(b,l,"A",d,e,x,S)}a=a.className;H(a)&&(a=a.animVal);if(L(a)&&""!==a)for(;k=g.exec(a);)l=wa(k[2]),w(b,l,"C",d,e)&&(c[l]=R(k[3])),a=a.substr(k.index+k[0].length);break;case Na:if(11===Ua)for(;a.parentNode&&a.nextSibling&&a.nextSibling.nodeType===Na;)a.nodeValue+=a.nextSibling.nodeValue,a.parentNode.removeChild(a.nextSibling);xa(b,a.nodeValue);break;case 8:try{if(k=f.exec(a.nodeValue))l=wa(k[1]),w(b,l,"M",d,e)&&(c[l]=R(k[2]))}catch($){}}b.sort(Aa);return b}function va(a, b,c){var d=[],e=0;if(b&&a.hasAttribute&&a.hasAttribute(b)){do{if(!a)throw ea("uterdir",b,c);a.nodeType==qa&&(a.hasAttribute(b)&&e++,a.hasAttribute(c)&&e--);d.push(a);a=a.nextSibling}while(0<e)}else d.push(a);return y(d)}function Yc(a,b,c){return function(d,e,f,g,h){e=va(e[0],b,c);return a(d,e,f,g,h)}}function E(a,b,d,e,f,g,h,k,s){function n(a,b,c,d){if(a){c&&(a=Yc(a,c,d));a.require=E.require;a.directiveName=w;if(u===E||E.$$isolateScope)a=X(a,{isolateScope:!0});h.push(a)}if(b){c&&(b=Yc(b,c,d));b.require= E.require;b.directiveName=w;if(u===E||E.$$isolateScope)b=X(b,{isolateScope:!0});k.push(b)}}function B(a,b,c,d){var e;if(L(b)){var f=b.match(l);b=b.substring(f[0].length);var g=f[1]||f[3],f="?"===f[2];"^^"===g?c=c.parent():e=(e=d&&d[b])&&e.instance;e||(d="$"+b+"Controller",e=g?c.inheritedData(d):c.data(d));if(!e&&!f)throw ea("ctreq",b,a);}else if(G(b))for(e=[],g=0,f=b.length;g<f;g++)e[g]=B(a,b[g],c,d);return e||null}function x(a,b,c,d,e,f){var g=ga(),h;for(h in d){var k=d[h],l={$scope:k===u||k.$$isolateScope? e:f,$element:a,$attrs:b,$transclude:c},s=k.controller;"@"==s&&(s=b[k.name]);l=p(s,l,!0,k.controllerAs);g[k.name]=l;q||a.data("$"+k.name+"Controller",l.instance)}return g}function S(a,c,e,f,g,l){function s(a,b,c){var d;$a(a)||(c=b,b=a,a=t);q&&(d=m);c||(c=q?ja.parent():ja);return g(a,b,d,c,va)}var n,p,C,F,m,ha,ja;b===e?(f=d,ja=d.$$element):(ja=y(e),f=new aa(ja,d));u&&(F=c.$new(!0));g&&(ha=s,ha.$$boundTransclude=g);N&&(m=x(ja,f,ha,N,F,c));u&&(Z.$$addScopeInfo(ja,F,!0,!(D&&(D===u||D===u.$$originalDirective))), Z.$$addScopeClass(ja,!0),F.$$isolateBindings=u.$$isolateBindings,W(c,f,F,F.$$isolateBindings,u,F));if(m){var K=u||$,I;K&&m[K.name]&&(p=K.$$bindings.bindToController,(C=m[K.name])&&C.identifier&&p&&(I=C,l.$$destroyBindings=W(c,f,C.instance,p,K)));for(n in m){C=m[n];var E=C();E!==C.instance&&(C.instance=E,ja.data("$"+n+"Controller",E),C===I&&(l.$$destroyBindings(),l.$$destroyBindings=W(c,f,E,p,K)))}}n=0;for(l=h.length;n<l;n++)p=h[n],Y(p,p.isolateScope?F:c,ja,f,p.require&&B(p.directiveName,p.require, ja,m),ha);var va=c;u&&(u.template||null===u.templateUrl)&&(va=F);a&&a(va,e.childNodes,t,g);for(n=k.length-1;0<=n;n--)p=k[n],Y(p,p.isolateScope?F:c,ja,f,p.require&&B(p.directiveName,p.require,ja,m),ha)}s=s||{};for(var F=-Number.MAX_VALUE,$=s.newScopeDirective,N=s.controllerDirectives,u=s.newIsolateScopeDirective,D=s.templateDirective,m=s.nonTlbTranscludeDirective,K=!1,I=!1,q=s.hasElementTranscludeDirective,ba=d.$$element=y(b),E,w,v,A=e,Aa,xa=0,Ta=a.length;xa<Ta;xa++){E=a[xa];var M=E.$$start,P=E.$$end; M&&(ba=va(b,M,P));v=t;if(F>E.priority)break;if(v=E.scope)E.templateUrl||(H(v)?(O("new/isolated scope",u||$,E,ba),u=E):O("new/isolated scope",u,E,ba)),$=$||E;w=E.name;!E.templateUrl&&E.controller&&(v=E.controller,N=N||ga(),O("'"+w+"' controller",N[w],E,ba),N[w]=E);if(v=E.transclude)K=!0,E.$$tlb||(O("transclusion",m,E,ba),m=E),"element"==v?(q=!0,F=E.priority,v=ba,ba=d.$$element=y(U.createComment(" "+w+": "+d[w]+" ")),b=ba[0],T(f,za.call(v,0),b),A=Z(v,e,F,g&&g.name,{nonTlbTranscludeDirective:m})):(v= y(Vb(b)).contents(),ba.empty(),A=Z(v,e));if(E.template)if(I=!0,O("template",D,E,ba),D=E,v=z(E.template)?E.template(ba,d):E.template,v=fa(v),E.replace){g=E;v=Tb.test(v)?$c(Yb(E.templateNamespace,R(v))):[];b=v[0];if(1!=v.length||b.nodeType!==qa)throw ea("tplrt",w,"");T(f,ba,b);Ta={$attr:{}};v=ha(b,[],Ta);var Q=a.splice(xa+1,a.length-(xa+1));u&&ad(v);a=a.concat(v).concat(Q);J(d,Ta);Ta=a.length}else ba.html(v);if(E.templateUrl)I=!0,O("template",D,E,ba),D=E,E.replace&&(g=E),S=Mf(a.splice(xa,a.length-xa), ba,d,f,K&&A,h,k,{controllerDirectives:N,newScopeDirective:$!==E&&$,newIsolateScopeDirective:u,templateDirective:D,nonTlbTranscludeDirective:m}),Ta=a.length;else if(E.compile)try{Aa=E.compile(ba,d,A),z(Aa)?n(null,Aa,M,P):Aa&&n(Aa.pre,Aa.post,M,P)}catch(Lf){c(Lf,ua(ba))}E.terminal&&(S.terminal=!0,F=Math.max(F,E.priority))}S.scope=$&&!0===$.scope;S.transcludeOnThisElement=K;S.templateOnThisElement=I;S.transclude=A;s.hasElementTranscludeDirective=q;return S}function ad(a){for(var b=0,c=a.length;b<c;b++)a[b]= Ob(a[b],{$$isolateScope:!0})}function w(b,d,f,g,h,k,l){if(d===h)return null;h=null;if(e.hasOwnProperty(d)){var n;d=a.get(d+"Directive");for(var p=0,B=d.length;p<B;p++)try{n=d[p],(g===t||g>n.priority)&&-1!=n.restrict.indexOf(f)&&(k&&(n=Ob(n,{$$start:k,$$end:l})),b.push(n),h=n)}catch(x){c(x)}}return h}function A(b){if(e.hasOwnProperty(b))for(var c=a.get(b+"Directive"),d=0,f=c.length;d<f;d++)if(b=c[d],b.multiElement)return!0;return!1}function J(a,b){var c=b.$attr,d=a.$attr,e=a.$$element;m(a,function(d, e){"$"!=e.charAt(0)&&(b[e]&&b[e]!==d&&(d+=("style"===e?";":" ")+b[e]),a.$set(e,d,!0,c[e]))});m(b,function(b,f){"class"==f?(D(e,b),a["class"]=(a["class"]?a["class"]+" ":"")+b):"style"==f?(e.attr("style",e.attr("style")+";"+b),a.style=(a.style?a.style+";":"")+b):"$"==f.charAt(0)||a.hasOwnProperty(f)||(a[f]=b,d[f]=c[f])})}function Mf(a,b,c,e,f,g,h,k){var l=[],s,n,p=b[0],B=a.shift(),C=Ob(B,{templateUrl:null,transclude:null,replace:null,$$originalDirective:B}),x=z(B.templateUrl)?B.templateUrl(b,c):B.templateUrl, N=B.templateNamespace;b.empty();d(x).then(function(d){var F,u;d=fa(d);if(B.replace){d=Tb.test(d)?$c(Yb(N,R(d))):[];F=d[0];if(1!=d.length||F.nodeType!==qa)throw ea("tplrt",B.name,x);d={$attr:{}};T(e,b,F);var K=ha(F,[],d);H(B.scope)&&ad(K);a=K.concat(a);J(c,d)}else F=p,b.html(d);a.unshift(C);s=E(a,F,c,f,b,B,g,h,k);m(e,function(a,c){a==F&&(e[c]=b[0])});for(n=S(b[0].childNodes,f);l.length;){d=l.shift();u=l.shift();var I=l.shift(),va=l.shift(),K=b[0];if(!d.$$destroyed){if(u!==p){var Z=u.className;k.hasElementTranscludeDirective&& B.replace||(K=Vb(F));T(I,y(u),K);D(y(K),Z)}u=s.transcludeOnThisElement?$(d,s.transclude,va):va;s(n,d,K,e,u,s)}}l=null});return function(a,b,c,d,e){a=e;b.$$destroyed||(l?l.push(b,c,d,a):(s.transcludeOnThisElement&&(a=$(b,s.transclude,e)),s(n,b,c,d,a,s)))}}function Aa(a,b){var c=b.priority-a.priority;return 0!==c?c:a.name!==b.name?a.name<b.name?-1:1:a.index-b.index}function O(a,b,c,d){function e(a){return a?" (module: "+a+")":""}if(b)throw ea("multidir",b.name,e(b.$$moduleName),c.name,e(c.$$moduleName), a,ua(d));}function xa(a,c){var d=b(c,!0);d&&a.push({priority:0,compile:function(a){a=a.parent();var b=!!a.length;b&&Z.$$addBindingClass(a);return function(a,c){var e=c.parent();b||Z.$$addBindingClass(e);Z.$$addBindingInfo(e,d.expressions);a.$watch(d,function(a){c[0].nodeValue=a})}}})}function Yb(a,b){a=M(a||"html");switch(a){case "svg":case "math":var c=U.createElement("div");c.innerHTML="<"+a+">"+b+"</"+a+">";return c.childNodes[0].childNodes;default:return b}}function Q(a,b){if("srcdoc"==b)return I.HTML; var c=ta(a);if("xlinkHref"==b||"form"==c&&"action"==b||"img"!=c&&("src"==b||"ngSrc"==b))return I.RESOURCE_URL}function V(a,c,d,e,f){var g=Q(a,e);f=h[e]||f;var l=b(d,!0,g,f);if(l){if("multiple"===e&&"select"===ta(a))throw ea("selmulti",ua(a));c.push({priority:100,compile:function(){return{pre:function(a,c,h){c=h.$$observers||(h.$$observers={});if(k.test(e))throw ea("nodomevents");var s=h[e];s!==d&&(l=s&&b(s,!0,g,f),d=s);l&&(h[e]=l(a),(c[e]||(c[e]=[])).$$inter=!0,(h.$$observers&&h.$$observers[e].$$scope|| a).$watch(l,function(a,b){"class"===e&&a!=b?h.$updateClass(a,b):h.$set(e,a)}))}}}})}}function T(a,b,c){var d=b[0],e=b.length,f=d.parentNode,g,h;if(a)for(g=0,h=a.length;g<h;g++)if(a[g]==d){a[g++]=c;h=g+e-1;for(var k=a.length;g<k;g++,h++)h<k?a[g]=a[h]:delete a[g];a.length-=e-1;a.context===d&&(a.context=c);break}f&&f.replaceChild(c,d);a=U.createDocumentFragment();a.appendChild(d);y.hasData(d)&&(y(c).data(y(d).data()),la?(Rb=!0,la.cleanData([d])):delete y.cache[d[y.expando]]);d=1;for(e=b.length;d<e;d++)f= b[d],y(f).remove(),a.appendChild(f),delete b[d];b[0]=c;b.length=1}function X(a,b){return P(function(){return a.apply(null,arguments)},a,b)}function Y(a,b,d,e,f,g){try{a(b,d,e,f,g)}catch(h){c(h,ua(d))}}function W(a,c,d,e,f,g){var h;m(e,function(e,g){var k=e.attrName,l=e.optional,s=e.mode,n,p,B,C;Xa.call(c,k)||(c[k]=t);switch(s){case "@":c[k]||l||(d[g]=t);c.$observe(k,function(a){d[g]=a});c.$$observers[k].$$scope=a;c[k]&&(d[g]=b(c[k])(a));break;case "=":if(l&&!c[k])break;p=u(c[k]);C=p.literal?ka:function(a, b){return a===b||a!==a&&b!==b};B=p.assign||function(){n=d[g]=p(a);throw ea("nonassign",c[k],f.name);};n=d[g]=p(a);l=function(b){C(b,d[g])||(C(b,n)?B(a,b=d[g]):d[g]=b);return n=b};l.$stateful=!0;l=e.collection?a.$watchCollection(c[k],l):a.$watch(u(c[k],l),null,p.literal);h=h||[];h.push(l);break;case "&":p=u(c[k]);if(p===v&&l)break;d[g]=function(b){return p(a,b)}}});e=h?function(){for(var a=0,b=h.length;a<b;++a)h[a]()}:v;return g&&e!==v?(g.$on("$destroy",e),v):e}var aa=function(a,b){if(b){var c=Object.keys(b), d,e,f;d=0;for(e=c.length;d<e;d++)f=c[d],this[f]=b[f]}else this.$attr={};this.$$element=a};aa.prototype={$normalize:wa,$addClass:function(a){a&&0<a.length&&B.addClass(this.$$element,a)},$removeClass:function(a){a&&0<a.length&&B.removeClass(this.$$element,a)},$updateClass:function(a,b){var c=bd(a,b);c&&c.length&&B.addClass(this.$$element,c);(c=bd(b,a))&&c.length&&B.removeClass(this.$$element,c)},$set:function(a,b,d,e){var f=this.$$element[0],g=Sc(f,a),h=Gf(f,a),f=a;g?(this.$$element.prop(a,b),e=g): h&&(this[h]=b,f=h);this[a]=b;e?this.$attr[a]=e:(e=this.$attr[a])||(this.$attr[a]=e=Bc(a,"-"));g=ta(this.$$element);if("a"===g&&"href"===a||"img"===g&&"src"===a)this[a]=b=N(b,"src"===a);else if("img"===g&&"srcset"===a){for(var g="",h=R(b),k=/(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/,k=/\s/.test(h)?k:/(,)/,h=h.split(k),k=Math.floor(h.length/2),l=0;l<k;l++)var s=2*l,g=g+N(R(h[s]),!0),g=g+(" "+R(h[s+1]));h=R(h[2*l]).split(/\s/);g+=N(R(h[0]),!0);2===h.length&&(g+=" "+R(h[1]));this[a]=b=g}!1!==d&&(null===b|| b===t?this.$$element.removeAttr(e):this.$$element.attr(e,b));(a=this.$$observers)&&m(a[f],function(a){try{a(b)}catch(d){c(d)}})},$observe:function(a,b){var c=this,d=c.$$observers||(c.$$observers=ga()),e=d[a]||(d[a]=[]);e.push(b);K.$evalAsync(function(){!e.$$inter&&c.hasOwnProperty(a)&&b(c[a])});return function(){bb(e,b)}}};var ca=b.startSymbol(),da=b.endSymbol(),fa="{{"==ca||"}}"==da?Ya:function(a){return a.replace(/\{\{/g,ca).replace(/}}/g,da)},ia=/^ngAttr[A-Z]/;Z.$$addBindingInfo=n?function(a,b){var c= a.data("$binding")||[];G(b)?c=c.concat(b):c.push(b);a.data("$binding",c)}:v;Z.$$addBindingClass=n?function(a){D(a,"ng-binding")}:v;Z.$$addScopeInfo=n?function(a,b,c,d){a.data(c?d?"$isolateScopeNoTemplate":"$isolateScope":"$scope",b)}:v;Z.$$addScopeClass=n?function(a,b){D(a,b?"ng-isolate-scope":"ng-scope")}:v;return Z}]}function wa(b){return hb(b.replace(Zc,""))}function bd(b,a){var c="",d=b.split(/\s+/),e=a.split(/\s+/),f=0;a:for(;f<d.length;f++){for(var g=d[f],h=0;h<e.length;h++)if(g==e[h])continue a; c+=(0<c.length?" ":"")+g}return c}function $c(b){b=y(b);var a=b.length;if(1>=a)return b;for(;a--;)8===b[a].nodeType&&Nf.call(b,a,1);return b}function Xe(){var b={},a=!1;this.register=function(a,d){Ra(a,"controller");H(a)?P(b,a):b[a]=d};this.allowGlobals=function(){a=!0};this.$get=["$injector","$window",function(c,d){function e(a,b,c,d){if(!a||!H(a.$scope))throw J("$controller")("noscp",d,b);a.$scope[b]=c}return function(f,g,h,l){var k,n,r;h=!0===h;l&&L(l)&&(r=l);if(L(f)){l=f.match(Xc);if(!l)throw Of("ctrlfmt", f);n=l[1];r=r||l[3];f=b.hasOwnProperty(n)?b[n]:Dc(g.$scope,n,!0)||(a?Dc(d,n,!0):t);Qa(f,n,!0)}if(h)return h=(G(f)?f[f.length-1]:f).prototype,k=Object.create(h||null),r&&e(g,r,k,n||f.name),P(function(){var a=c.invoke(f,k,g,n);a!==k&&(H(a)||z(a))&&(k=a,r&&e(g,r,k,n||f.name));return k},{instance:k,identifier:r});k=c.instantiate(f,g,n);r&&e(g,r,k,n||f.name);return k}}]}function Ye(){this.$get=["$window",function(b){return y(b.document)}]}function Ze(){this.$get=["$log",function(b){return function(a,c){b.error.apply(b, arguments)}}]}function Zb(b){return H(b)?aa(b)?b.toISOString():db(b):b}function cf(){this.$get=function(){return function(b){if(!b)return"";var a=[];oc(b,function(b,d){null===b||A(b)||(G(b)?m(b,function(b,c){a.push(ma(d)+"="+ma(Zb(b)))}):a.push(ma(d)+"="+ma(Zb(b))))});return a.join("&")}}}function df(){this.$get=function(){return function(b){function a(b,e,f){null===b||A(b)||(G(b)?m(b,function(b){a(b,e+"[]")}):H(b)&&!aa(b)?oc(b,function(b,c){a(b,e+(f?"":"[")+c+(f?"":"]"))}):c.push(ma(e)+"="+ma(Zb(b))))} if(!b)return"";var c=[];a(b,"",!0);return c.join("&")}}}function $b(b,a){if(L(b)){var c=b.replace(Pf,"").trim();if(c){var d=a("Content-Type");(d=d&&0===d.indexOf(cd))||(d=(d=c.match(Qf))&&Rf[d[0]].test(c));d&&(b=wc(c))}}return b}function dd(b){var a=ga(),c;L(b)?m(b.split("\n"),function(b){c=b.indexOf(":");var e=M(R(b.substr(0,c)));b=R(b.substr(c+1));e&&(a[e]=a[e]?a[e]+", "+b:b)}):H(b)&&m(b,function(b,c){var f=M(c),g=R(b);f&&(a[f]=a[f]?a[f]+", "+g:g)});return a}function ed(b){var a;return function(c){a|| (a=dd(b));return c?(c=a[M(c)],void 0===c&&(c=null),c):a}}function fd(b,a,c,d){if(z(d))return d(b,a,c);m(d,function(d){b=d(b,a,c)});return b}function bf(){var b=this.defaults={transformResponse:[$b],transformRequest:[function(a){return H(a)&&"[object File]"!==sa.call(a)&&"[object Blob]"!==sa.call(a)&&"[object FormData]"!==sa.call(a)?db(a):a}],headers:{common:{Accept:"application/json, text/plain, */*"},post:ia(ac),put:ia(ac),patch:ia(ac)},xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",paramSerializer:"$httpParamSerializer"}, a=!1;this.useApplyAsync=function(b){return w(b)?(a=!!b,this):a};var c=this.interceptors=[];this.$get=["$httpBackend","$$cookieReader","$cacheFactory","$rootScope","$q","$injector",function(d,e,f,g,h,l){function k(a){function c(a){var b=P({},a);b.data=a.data?fd(a.data,a.headers,a.status,e.transformResponse):a.data;a=a.status;return 200<=a&&300>a?b:h.reject(b)}function d(a,b){var c,e={};m(a,function(a,d){z(a)?(c=a(b),null!=c&&(e[d]=c)):e[d]=a});return e}if(!ca.isObject(a))throw J("$http")("badreq", a);var e=P({method:"get",transformRequest:b.transformRequest,transformResponse:b.transformResponse,paramSerializer:b.paramSerializer},a);e.headers=function(a){var c=b.headers,e=P({},a.headers),f,g,h,c=P({},c.common,c[M(a.method)]);a:for(f in c){g=M(f);for(h in e)if(M(h)===g)continue a;e[f]=c[f]}return d(e,ia(a))}(a);e.method=rb(e.method);e.paramSerializer=L(e.paramSerializer)?l.get(e.paramSerializer):e.paramSerializer;var f=[function(a){var d=a.headers,e=fd(a.data,ed(d),t,a.transformRequest);A(e)&& m(d,function(a,b){"content-type"===M(b)&&delete d[b]});A(a.withCredentials)&&!A(b.withCredentials)&&(a.withCredentials=b.withCredentials);return n(a,e).then(c,c)},t],g=h.when(e);for(m(x,function(a){(a.request||a.requestError)&&f.unshift(a.request,a.requestError);(a.response||a.responseError)&&f.push(a.response,a.responseError)});f.length;){a=f.shift();var k=f.shift(),g=g.then(a,k)}g.success=function(a){Qa(a,"fn");g.then(function(b){a(b.data,b.status,b.headers,e)});return g};g.error=function(a){Qa(a, "fn");g.then(null,function(b){a(b.data,b.status,b.headers,e)});return g};return g}function n(c,f){function l(b,c,d,e){function f(){n(c,b,d,e)}N&&(200<=b&&300>b?N.put(S,[b,c,dd(d),e]):N.remove(S));a?g.$applyAsync(f):(f(),g.$$phase||g.$apply())}function n(a,b,d,e){b=Math.max(b,0);(200<=b&&300>b?I.resolve:I.reject)({data:a,status:b,headers:ed(d),config:c,statusText:e})}function x(a){n(a.data,a.status,ia(a.headers()),a.statusText)}function m(){var a=k.pendingRequests.indexOf(c);-1!==a&&k.pendingRequests.splice(a, 1)}var I=h.defer(),B=I.promise,N,D,q=c.headers,S=r(c.url,c.paramSerializer(c.params));k.pendingRequests.push(c);B.then(m,m);!c.cache&&!b.cache||!1===c.cache||"GET"!==c.method&&"JSONP"!==c.method||(N=H(c.cache)?c.cache:H(b.cache)?b.cache:s);N&&(D=N.get(S),w(D)?D&&z(D.then)?D.then(x,x):G(D)?n(D[1],D[0],ia(D[2]),D[3]):n(D,200,{},"OK"):N.put(S,B));A(D)&&((D=gd(c.url)?e()[c.xsrfCookieName||b.xsrfCookieName]:t)&&(q[c.xsrfHeaderName||b.xsrfHeaderName]=D),d(c.method,S,f,l,q,c.timeout,c.withCredentials,c.responseType)); return B}function r(a,b){0<b.length&&(a+=(-1==a.indexOf("?")?"?":"&")+b);return a}var s=f("$http");b.paramSerializer=L(b.paramSerializer)?l.get(b.paramSerializer):b.paramSerializer;var x=[];m(c,function(a){x.unshift(L(a)?l.get(a):l.invoke(a))});k.pendingRequests=[];(function(a){m(arguments,function(a){k[a]=function(b,c){return k(P({},c||{},{method:a,url:b}))}})})("get","delete","head","jsonp");(function(a){m(arguments,function(a){k[a]=function(b,c,d){return k(P({},d||{},{method:a,url:b,data:c}))}})})("post", "put","patch");k.defaults=b;return k}]}function Sf(){return new O.XMLHttpRequest}function ef(){this.$get=["$browser","$window","$document",function(b,a,c){return Tf(b,Sf,b.defer,a.angular.callbacks,c[0])}]}function Tf(b,a,c,d,e){function f(a,b,c){var f=e.createElement("script"),n=null;f.type="text/javascript";f.src=a;f.async=!0;n=function(a){f.removeEventListener("load",n,!1);f.removeEventListener("error",n,!1);e.body.removeChild(f);f=null;var g=-1,x="unknown";a&&("load"!==a.type||d[b].called||(a= {type:"error"}),x=a.type,g="error"===a.type?404:200);c&&c(g,x)};f.addEventListener("load",n,!1);f.addEventListener("error",n,!1);e.body.appendChild(f);return n}return function(e,h,l,k,n,r,s,x){function C(){p&&p();K&&K.abort()}function F(a,d,e,f,g){I!==t&&c.cancel(I);p=K=null;a(d,e,f,g);b.$$completeOutstandingRequest(v)}b.$$incOutstandingRequestCount();h=h||b.url();if("jsonp"==M(e)){var u="_"+(d.counter++).toString(36);d[u]=function(a){d[u].data=a;d[u].called=!0};var p=f(h.replace("JSON_CALLBACK", "angular.callbacks."+u),u,function(a,b){F(k,a,d[u].data,"",b);d[u]=v})}else{var K=a();K.open(e,h,!0);m(n,function(a,b){w(a)&&K.setRequestHeader(b,a)});K.onload=function(){var a=K.statusText||"",b="response"in K?K.response:K.responseText,c=1223===K.status?204:K.status;0===c&&(c=b?200:"file"==Ba(h).protocol?404:0);F(k,c,b,K.getAllResponseHeaders(),a)};e=function(){F(k,-1,null,null,"")};K.onerror=e;K.onabort=e;s&&(K.withCredentials=!0);if(x)try{K.responseType=x}catch(q){if("json"!==x)throw q;}K.send(l)}if(0< r)var I=c(C,r);else r&&z(r.then)&&r.then(C)}}function $e(){var b="{{",a="}}";this.startSymbol=function(a){return a?(b=a,this):b};this.endSymbol=function(b){return b?(a=b,this):a};this.$get=["$parse","$exceptionHandler","$sce",function(c,d,e){function f(a){return"\\\\\\"+a}function g(c){return c.replace(n,b).replace(r,a)}function h(f,h,n,r){function u(a){try{var b=a;a=n?e.getTrusted(n,b):e.valueOf(b);var c;if(r&&!w(a))c=a;else if(null==a)c="";else{switch(typeof a){case "string":break;case "number":a= ""+a;break;default:a=db(a)}c=a}return c}catch(g){d(Ka.interr(f,g))}}r=!!r;for(var p,m,q=0,I=[],B=[],N=f.length,D=[],t=[];q<N;)if(-1!=(p=f.indexOf(b,q))&&-1!=(m=f.indexOf(a,p+l)))q!==p&&D.push(g(f.substring(q,p))),q=f.substring(p+l,m),I.push(q),B.push(c(q,u)),q=m+k,t.push(D.length),D.push("");else{q!==N&&D.push(g(f.substring(q)));break}n&&1<D.length&&Ka.throwNoconcat(f);if(!h||I.length){var S=function(a){for(var b=0,c=I.length;b<c;b++){if(r&&A(a[b]))return;D[t[b]]=a[b]}return D.join("")};return P(function(a){var b= 0,c=I.length,e=Array(c);try{for(;b<c;b++)e[b]=B[b](a);return S(e)}catch(g){d(Ka.interr(f,g))}},{exp:f,expressions:I,$$watchDelegate:function(a,b){var c;return a.$watchGroup(B,function(d,e){var f=S(d);z(b)&&b.call(this,f,d!==e?c:f,a);c=f})}})}}var l=b.length,k=a.length,n=new RegExp(b.replace(/./g,f),"g"),r=new RegExp(a.replace(/./g,f),"g");h.startSymbol=function(){return b};h.endSymbol=function(){return a};return h}]}function af(){this.$get=["$rootScope","$window","$q","$$q",function(b,a,c,d){function e(e, h,l,k){var n=4<arguments.length,r=n?za.call(arguments,4):[],s=a.setInterval,x=a.clearInterval,C=0,F=w(k)&&!k,u=(F?d:c).defer(),p=u.promise;l=w(l)?l:0;p.then(null,null,n?function(){e.apply(null,r)}:e);p.$$intervalId=s(function(){u.notify(C++);0<l&&C>=l&&(u.resolve(C),x(p.$$intervalId),delete f[p.$$intervalId]);F||b.$apply()},h);f[p.$$intervalId]=u;return p}var f={};e.cancel=function(b){return b&&b.$$intervalId in f?(f[b.$$intervalId].reject("canceled"),a.clearInterval(b.$$intervalId),delete f[b.$$intervalId], !0):!1};return e}]}function ge(){this.$get=function(){return{id:"en-us",NUMBER_FORMATS:{DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{minInt:1,minFrac:0,maxFrac:3,posPre:"",posSuf:"",negPre:"-",negSuf:"",gSize:3,lgSize:3},{minInt:1,minFrac:2,maxFrac:2,posPre:"\u00a4",posSuf:"",negPre:"(\u00a4",negSuf:")",gSize:3,lgSize:3}],CURRENCY_SYM:"$"},DATETIME_FORMATS:{MONTH:"January February March April May June July August September October November December".split(" "),SHORTMONTH:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "), DAY:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),SHORTDAY:"Sun Mon Tue Wed Thu Fri Sat".split(" "),AMPMS:["AM","PM"],medium:"MMM d, y h:mm:ss a","short":"M/d/yy h:mm a",fullDate:"EEEE, MMMM d, y",longDate:"MMMM d, y",mediumDate:"MMM d, y",shortDate:"M/d/yy",mediumTime:"h:mm:ss a",shortTime:"h:mm a",ERANAMES:["Before Christ","Anno Domini"],ERAS:["BC","AD"]},pluralCat:function(b){return 1===b?"one":"other"}}}}function bc(b){b=b.split("/");for(var a=b.length;a--;)b[a]=ob(b[a]); return b.join("/")}function hd(b,a){var c=Ba(b);a.$$protocol=c.protocol;a.$$host=c.hostname;a.$$port=W(c.port)||Uf[c.protocol]||null}function id(b,a){var c="/"!==b.charAt(0);c&&(b="/"+b);var d=Ba(b);a.$$path=decodeURIComponent(c&&"/"===d.pathname.charAt(0)?d.pathname.substring(1):d.pathname);a.$$search=zc(d.search);a.$$hash=decodeURIComponent(d.hash);a.$$path&&"/"!=a.$$path.charAt(0)&&(a.$$path="/"+a.$$path)}function ya(b,a){if(0===a.indexOf(b))return a.substr(b.length)}function Ja(b){var a=b.indexOf("#"); return-1==a?b:b.substr(0,a)}function Bb(b){return b.replace(/(#.+)|#$/,"$1")}function cc(b){return b.substr(0,Ja(b).lastIndexOf("/")+1)}function dc(b,a){this.$$html5=!0;a=a||"";var c=cc(b);hd(b,this);this.$$parse=function(a){var b=ya(c,a);if(!L(b))throw Cb("ipthprfx",a,c);id(b,this);this.$$path||(this.$$path="/");this.$$compose()};this.$$compose=function(){var a=Qb(this.$$search),b=this.$$hash?"#"+ob(this.$$hash):"";this.$$url=bc(this.$$path)+(a?"?"+a:"")+b;this.$$absUrl=c+this.$$url.substr(1)};this.$$parseLinkUrl= function(d,e){if(e&&"#"===e[0])return this.hash(e.slice(1)),!0;var f,g;(f=ya(b,d))!==t?(g=f,g=(f=ya(a,f))!==t?c+(ya("/",f)||f):b+g):(f=ya(c,d))!==t?g=c+f:c==d+"/"&&(g=c);g&&this.$$parse(g);return!!g}}function ec(b,a){var c=cc(b);hd(b,this);this.$$parse=function(d){var e=ya(b,d)||ya(c,d),f;A(e)||"#"!==e.charAt(0)?this.$$html5?f=e:(f="",A(e)&&(b=d,this.replace())):(f=ya(a,e),A(f)&&(f=e));id(f,this);d=this.$$path;var e=b,g=/^\/[A-Z]:(\/.*)/;0===f.indexOf(e)&&(f=f.replace(e,""));g.exec(f)||(d=(f=g.exec(d))? f[1]:d);this.$$path=d;this.$$compose()};this.$$compose=function(){var c=Qb(this.$$search),e=this.$$hash?"#"+ob(this.$$hash):"";this.$$url=bc(this.$$path)+(c?"?"+c:"")+e;this.$$absUrl=b+(this.$$url?a+this.$$url:"")};this.$$parseLinkUrl=function(a,c){return Ja(b)==Ja(a)?(this.$$parse(a),!0):!1}}function jd(b,a){this.$$html5=!0;ec.apply(this,arguments);var c=cc(b);this.$$parseLinkUrl=function(d,e){if(e&&"#"===e[0])return this.hash(e.slice(1)),!0;var f,g;b==Ja(d)?f=d:(g=ya(c,d))?f=b+a+g:c===d+"/"&&(f= c);f&&this.$$parse(f);return!!f};this.$$compose=function(){var c=Qb(this.$$search),e=this.$$hash?"#"+ob(this.$$hash):"";this.$$url=bc(this.$$path)+(c?"?"+c:"")+e;this.$$absUrl=b+a+this.$$url}}function Db(b){return function(){return this[b]}}function kd(b,a){return function(c){if(A(c))return this[b];this[b]=a(c);this.$$compose();return this}}function ff(){var b="",a={enabled:!1,requireBase:!0,rewriteLinks:!0};this.hashPrefix=function(a){return w(a)?(b=a,this):b};this.html5Mode=function(b){return ab(b)? (a.enabled=b,this):H(b)?(ab(b.enabled)&&(a.enabled=b.enabled),ab(b.requireBase)&&(a.requireBase=b.requireBase),ab(b.rewriteLinks)&&(a.rewriteLinks=b.rewriteLinks),this):a};this.$get=["$rootScope","$browser","$sniffer","$rootElement","$window",function(c,d,e,f,g){function h(a,b,c){var e=k.url(),f=k.$$state;try{d.url(a,b,c),k.$$state=d.state()}catch(g){throw k.url(e),k.$$state=f,g;}}function l(a,b){c.$broadcast("$locationChangeSuccess",k.absUrl(),a,k.$$state,b)}var k,n;n=d.baseHref();var r=d.url(), s;if(a.enabled){if(!n&&a.requireBase)throw Cb("nobase");s=r.substring(0,r.indexOf("/",r.indexOf("//")+2))+(n||"/");n=e.history?dc:jd}else s=Ja(r),n=ec;k=new n(s,"#"+b);k.$$parseLinkUrl(r,r);k.$$state=d.state();var x=/^\s*(javascript|mailto):/i;f.on("click",function(b){if(a.rewriteLinks&&!b.ctrlKey&&!b.metaKey&&!b.shiftKey&&2!=b.which&&2!=b.button){for(var e=y(b.target);"a"!==ta(e[0]);)if(e[0]===f[0]||!(e=e.parent())[0])return;var h=e.prop("href"),l=e.attr("href")||e.attr("xlink:href");H(h)&&"[object SVGAnimatedString]"=== h.toString()&&(h=Ba(h.animVal).href);x.test(h)||!h||e.attr("target")||b.isDefaultPrevented()||!k.$$parseLinkUrl(h,l)||(b.preventDefault(),k.absUrl()!=d.url()&&(c.$apply(),g.angular["ff-684208-preventDefault"]=!0))}});Bb(k.absUrl())!=Bb(r)&&d.url(k.absUrl(),!0);var C=!0;d.onUrlChange(function(a,b){c.$evalAsync(function(){var d=k.absUrl(),e=k.$$state,f;k.$$parse(a);k.$$state=b;f=c.$broadcast("$locationChangeStart",a,d,b,e).defaultPrevented;k.absUrl()===a&&(f?(k.$$parse(d),k.$$state=e,h(d,!1,e)):(C= !1,l(d,e)))});c.$$phase||c.$digest()});c.$watch(function(){var a=Bb(d.url()),b=Bb(k.absUrl()),f=d.state(),g=k.$$replace,n=a!==b||k.$$html5&&e.history&&f!==k.$$state;if(C||n)C=!1,c.$evalAsync(function(){var b=k.absUrl(),d=c.$broadcast("$locationChangeStart",b,a,k.$$state,f).defaultPrevented;k.absUrl()===b&&(d?(k.$$parse(a),k.$$state=f):(n&&h(b,g,f===k.$$state?null:k.$$state),l(a,f)))});k.$$replace=!1});return k}]}function gf(){var b=!0,a=this;this.debugEnabled=function(a){return w(a)?(b=a,this):b}; this.$get=["$window",function(c){function d(a){a instanceof Error&&(a.stack?a=a.message&&-1===a.stack.indexOf(a.message)?"Error: "+a.message+"\n"+a.stack:a.stack:a.sourceURL&&(a=a.message+"\n"+a.sourceURL+":"+a.line));return a}function e(a){var b=c.console||{},e=b[a]||b.log||v;a=!1;try{a=!!e.apply}catch(l){}return a?function(){var a=[];m(arguments,function(b){a.push(d(b))});return e.apply(b,a)}:function(a,b){e(a,null==b?"":b)}}return{log:e("log"),info:e("info"),warn:e("warn"),error:e("error"),debug:function(){var c= e("debug");return function(){b&&c.apply(a,arguments)}}()}}]}function Ca(b,a){if("__defineGetter__"===b||"__defineSetter__"===b||"__lookupGetter__"===b||"__lookupSetter__"===b||"__proto__"===b)throw da("isecfld",a);return b}function oa(b,a){if(b){if(b.constructor===b)throw da("isecfn",a);if(b.window===b)throw da("isecwindow",a);if(b.children&&(b.nodeName||b.prop&&b.attr&&b.find))throw da("isecdom",a);if(b===Object)throw da("isecobj",a);}return b}function ld(b,a){if(b){if(b.constructor===b)throw da("isecfn", a);if(b===Vf||b===Wf||b===Xf)throw da("isecff",a);}}function Yf(b,a){return"undefined"!==typeof b?b:a}function md(b,a){return"undefined"===typeof b?a:"undefined"===typeof a?b:b+a}function T(b,a){var c,d;switch(b.type){case q.Program:c=!0;m(b.body,function(b){T(b.expression,a);c=c&&b.expression.constant});b.constant=c;break;case q.Literal:b.constant=!0;b.toWatch=[];break;case q.UnaryExpression:T(b.argument,a);b.constant=b.argument.constant;b.toWatch=b.argument.toWatch;break;case q.BinaryExpression:T(b.left, a);T(b.right,a);b.constant=b.left.constant&&b.right.constant;b.toWatch=b.left.toWatch.concat(b.right.toWatch);break;case q.LogicalExpression:T(b.left,a);T(b.right,a);b.constant=b.left.constant&&b.right.constant;b.toWatch=b.constant?[]:[b];break;case q.ConditionalExpression:T(b.test,a);T(b.alternate,a);T(b.consequent,a);b.constant=b.test.constant&&b.alternate.constant&&b.consequent.constant;b.toWatch=b.constant?[]:[b];break;case q.Identifier:b.constant=!1;b.toWatch=[b];break;case q.MemberExpression:T(b.object, a);b.computed&&T(b.property,a);b.constant=b.object.constant&&(!b.computed||b.property.constant);b.toWatch=[b];break;case q.CallExpression:c=b.filter?!a(b.callee.name).$stateful:!1;d=[];m(b.arguments,function(b){T(b,a);c=c&&b.constant;b.constant||d.push.apply(d,b.toWatch)});b.constant=c;b.toWatch=b.filter&&!a(b.callee.name).$stateful?d:[b];break;case q.AssignmentExpression:T(b.left,a);T(b.right,a);b.constant=b.left.constant&&b.right.constant;b.toWatch=[b];break;case q.ArrayExpression:c=!0;d=[];m(b.elements, function(b){T(b,a);c=c&&b.constant;b.constant||d.push.apply(d,b.toWatch)});b.constant=c;b.toWatch=d;break;case q.ObjectExpression:c=!0;d=[];m(b.properties,function(b){T(b.value,a);c=c&&b.value.constant;b.value.constant||d.push.apply(d,b.value.toWatch)});b.constant=c;b.toWatch=d;break;case q.ThisExpression:b.constant=!1,b.toWatch=[]}}function nd(b){if(1==b.length){b=b[0].expression;var a=b.toWatch;return 1!==a.length?a:a[0]!==b?a:t}}function od(b){return b.type===q.Identifier||b.type===q.MemberExpression} function pd(b){if(1===b.body.length&&od(b.body[0].expression))return{type:q.AssignmentExpression,left:b.body[0].expression,right:{type:q.NGValueParameter},operator:"="}}function qd(b){return 0===b.body.length||1===b.body.length&&(b.body[0].expression.type===q.Literal||b.body[0].expression.type===q.ArrayExpression||b.body[0].expression.type===q.ObjectExpression)}function rd(b,a){this.astBuilder=b;this.$filter=a}function sd(b,a){this.astBuilder=b;this.$filter=a}function Eb(b,a,c,d){oa(b,d);a=a.split("."); for(var e,f=0;1<a.length;f++){e=Ca(a.shift(),d);var g=oa(b[e],d);g||(g={},b[e]=g);b=g}e=Ca(a.shift(),d);oa(b[e],d);return b[e]=c}function Fb(b){return"constructor"==b}function fc(b){return z(b.valueOf)?b.valueOf():Zf.call(b)}function hf(){var b=ga(),a=ga();this.$get=["$filter","$sniffer",function(c,d){function e(a,b){return null==a||null==b?a===b:"object"===typeof a&&(a=fc(a),"object"===typeof a)?!1:a===b||a!==a&&b!==b}function f(a,b,c,d,f){var g=d.inputs,h;if(1===g.length){var k=e,g=g[0];return a.$watch(function(a){var b= g(a);e(b,k)||(h=d(a,t,t,[b]),k=b&&fc(b));return h},b,c,f)}for(var l=[],n=[],r=0,m=g.length;r<m;r++)l[r]=e,n[r]=null;return a.$watch(function(a){for(var b=!1,c=0,f=g.length;c<f;c++){var k=g[c](a);if(b||(b=!e(k,l[c])))n[c]=k,l[c]=k&&fc(k)}b&&(h=d(a,t,t,n));return h},b,c,f)}function g(a,b,c,d){var e,f;return e=a.$watch(function(a){return d(a)},function(a,c,d){f=a;z(b)&&b.apply(this,arguments);w(a)&&d.$$postDigest(function(){w(f)&&e()})},c)}function h(a,b,c,d){function e(a){var b=!0;m(a,function(a){w(a)|| (b=!1)});return b}var f,g;return f=a.$watch(function(a){return d(a)},function(a,c,d){g=a;z(b)&&b.call(this,a,c,d);e(a)&&d.$$postDigest(function(){e(g)&&f()})},c)}function l(a,b,c,d){var e;return e=a.$watch(function(a){return d(a)},function(a,c,d){z(b)&&b.apply(this,arguments);e()},c)}function k(a,b){if(!b)return a;var c=a.$$watchDelegate,c=c!==h&&c!==g?function(c,d,e,f){e=a(c,d,e,f);return b(e,c,d)}:function(c,d,e,f){e=a(c,d,e,f);c=b(e,c,d);return w(e)?c:e};a.$$watchDelegate&&a.$$watchDelegate!== f?c.$$watchDelegate=a.$$watchDelegate:b.$stateful||(c.$$watchDelegate=f,c.inputs=a.inputs?a.inputs:[a]);return c}var n={csp:d.csp,expensiveChecks:!1},r={csp:d.csp,expensiveChecks:!0};return function(d,e,C){var m,u,p;switch(typeof d){case "string":p=d=d.trim();var q=C?a:b;m=q[p];m||(":"===d.charAt(0)&&":"===d.charAt(1)&&(u=!0,d=d.substring(2)),C=C?r:n,m=new gc(C),m=(new hc(m,c,C)).parse(d),m.constant?m.$$watchDelegate=l:u?m.$$watchDelegate=m.literal?h:g:m.inputs&&(m.$$watchDelegate=f),q[p]=m);return k(m, e);case "function":return k(d,e);default:return v}}}]}function kf(){this.$get=["$rootScope","$exceptionHandler",function(b,a){return td(function(a){b.$evalAsync(a)},a)}]}function lf(){this.$get=["$browser","$exceptionHandler",function(b,a){return td(function(a){b.defer(a)},a)}]}function td(b,a){function c(a,b,c){function d(b){return function(c){e||(e=!0,b.call(a,c))}}var e=!1;return[d(b),d(c)]}function d(){this.$$state={status:0}}function e(a,b){return function(c){b.call(a,c)}}function f(c){!c.processScheduled&& c.pending&&(c.processScheduled=!0,b(function(){var b,d,e;e=c.pending;c.processScheduled=!1;c.pending=t;for(var f=0,g=e.length;f<g;++f){d=e[f][0];b=e[f][c.status];try{z(b)?d.resolve(b(c.value)):1===c.status?d.resolve(c.value):d.reject(c.value)}catch(h){d.reject(h),a(h)}}}))}function g(){this.promise=new d;this.resolve=e(this,this.resolve);this.reject=e(this,this.reject);this.notify=e(this,this.notify)}var h=J("$q",TypeError);d.prototype={then:function(a,b,c){var d=new g;this.$$state.pending=this.$$state.pending|| [];this.$$state.pending.push([d,a,b,c]);0<this.$$state.status&&f(this.$$state);return d.promise},"catch":function(a){return this.then(null,a)},"finally":function(a,b){return this.then(function(b){return k(b,!0,a)},function(b){return k(b,!1,a)},b)}};g.prototype={resolve:function(a){this.promise.$$state.status||(a===this.promise?this.$$reject(h("qcycle",a)):this.$$resolve(a))},$$resolve:function(b){var d,e;e=c(this,this.$$resolve,this.$$reject);try{if(H(b)||z(b))d=b&&b.then;z(d)?(this.promise.$$state.status= -1,d.call(b,e[0],e[1],this.notify)):(this.promise.$$state.value=b,this.promise.$$state.status=1,f(this.promise.$$state))}catch(g){e[1](g),a(g)}},reject:function(a){this.promise.$$state.status||this.$$reject(a)},$$reject:function(a){this.promise.$$state.value=a;this.promise.$$state.status=2;f(this.promise.$$state)},notify:function(c){var d=this.promise.$$state.pending;0>=this.promise.$$state.status&&d&&d.length&&b(function(){for(var b,e,f=0,g=d.length;f<g;f++){e=d[f][0];b=d[f][3];try{e.notify(z(b)? b(c):c)}catch(h){a(h)}}})}};var l=function(a,b){var c=new g;b?c.resolve(a):c.reject(a);return c.promise},k=function(a,b,c){var d=null;try{z(c)&&(d=c())}catch(e){return l(e,!1)}return d&&z(d.then)?d.then(function(){return l(a,b)},function(a){return l(a,!1)}):l(a,b)},n=function(a,b,c,d){var e=new g;e.resolve(a);return e.promise.then(b,c,d)},r=function x(a){if(!z(a))throw h("norslvr",a);if(!(this instanceof x))return new x(a);var b=new g;a(function(a){b.resolve(a)},function(a){b.reject(a)});return b.promise}; r.defer=function(){return new g};r.reject=function(a){var b=new g;b.reject(a);return b.promise};r.when=n;r.resolve=n;r.all=function(a){var b=new g,c=0,d=G(a)?[]:{};m(a,function(a,e){c++;n(a).then(function(a){d.hasOwnProperty(e)||(d[e]=a,--c||b.resolve(d))},function(a){d.hasOwnProperty(e)||b.reject(a)})});0===c&&b.resolve(d);return b.promise};return r}function uf(){this.$get=["$window","$timeout",function(b,a){function c(){for(var a=0;a<n.length;a++){var b=n[a];b&&(n[a]=null,b())}k=n.length=0}function d(a){var b= n.length;k++;n.push(a);0===b&&(l=h(c));return function(){0<=b&&(b=n[b]=null,0===--k&&l&&(l(),l=null,n.length=0))}}var e=b.requestAnimationFrame||b.webkitRequestAnimationFrame,f=b.cancelAnimationFrame||b.webkitCancelAnimationFrame||b.webkitCancelRequestAnimationFrame,g=!!e,h=g?function(a){var b=e(a);return function(){f(b)}}:function(b){var c=a(b,16.66,!1);return function(){a.cancel(c)}};d.supported=g;var l,k=0,n=[];return d}]}function jf(){function b(a){function b(){this.$$watchers=this.$$nextSibling= this.$$childHead=this.$$childTail=null;this.$$listeners={};this.$$listenerCount={};this.$$watchersCount=0;this.$id=++nb;this.$$ChildScope=null}b.prototype=a;return b}var a=10,c=J("$rootScope"),d=null,e=null;this.digestTtl=function(b){arguments.length&&(a=b);return a};this.$get=["$injector","$exceptionHandler","$parse","$browser",function(f,g,h,l){function k(a){a.currentScope.$$destroyed=!0}function n(){this.$id=++nb;this.$$phase=this.$parent=this.$$watchers=this.$$nextSibling=this.$$prevSibling=this.$$childHead= this.$$childTail=null;this.$root=this;this.$$destroyed=!1;this.$$listeners={};this.$$listenerCount={};this.$$watchersCount=0;this.$$isolateBindings=null}function r(a){if(p.$$phase)throw c("inprog",p.$$phase);p.$$phase=a}function s(a,b){do a.$$watchersCount+=b;while(a=a.$parent)}function x(a,b,c){do a.$$listenerCount[c]-=b,0===a.$$listenerCount[c]&&delete a.$$listenerCount[c];while(a=a.$parent)}function q(){}function F(){for(;I.length;)try{I.shift()()}catch(a){g(a)}e=null}function u(){null===e&&(e= l.defer(function(){p.$apply(F)}))}n.prototype={constructor:n,$new:function(a,c){var d;c=c||this;a?(d=new n,d.$root=this.$root):(this.$$ChildScope||(this.$$ChildScope=b(this)),d=new this.$$ChildScope);d.$parent=c;d.$$prevSibling=c.$$childTail;c.$$childHead?(c.$$childTail.$$nextSibling=d,c.$$childTail=d):c.$$childHead=c.$$childTail=d;(a||c!=this)&&d.$on("$destroy",k);return d},$watch:function(a,b,c,e){var f=h(a);if(f.$$watchDelegate)return f.$$watchDelegate(this,b,c,f,a);var g=this,k=g.$$watchers,l= {fn:b,last:q,get:f,exp:e||a,eq:!!c};d=null;z(b)||(l.fn=v);k||(k=g.$$watchers=[]);k.unshift(l);s(this,1);return function(){0<=bb(k,l)&&s(g,-1);d=null}},$watchGroup:function(a,b){function c(){h=!1;k?(k=!1,b(e,e,g)):b(e,d,g)}var d=Array(a.length),e=Array(a.length),f=[],g=this,h=!1,k=!0;if(!a.length){var l=!0;g.$evalAsync(function(){l&&b(e,e,g)});return function(){l=!1}}if(1===a.length)return this.$watch(a[0],function(a,c,f){e[0]=a;d[0]=c;b(e,a===c?e:d,f)});m(a,function(a,b){var k=g.$watch(a,function(a, f){e[b]=a;d[b]=f;h||(h=!0,g.$evalAsync(c))});f.push(k)});return function(){for(;f.length;)f.shift()()}},$watchCollection:function(a,b){function c(a){e=a;var b,d,g,h;if(!A(e)){if(H(e))if(Ea(e))for(f!==r&&(f=r,m=f.length=0,l++),a=e.length,m!==a&&(l++,f.length=m=a),b=0;b<a;b++)h=f[b],g=e[b],d=h!==h&&g!==g,d||h===g||(l++,f[b]=g);else{f!==s&&(f=s={},m=0,l++);a=0;for(b in e)e.hasOwnProperty(b)&&(a++,g=e[b],h=f[b],b in f?(d=h!==h&&g!==g,d||h===g||(l++,f[b]=g)):(m++,f[b]=g,l++));if(m>a)for(b in l++,f)e.hasOwnProperty(b)|| (m--,delete f[b])}else f!==e&&(f=e,l++);return l}}c.$stateful=!0;var d=this,e,f,g,k=1<b.length,l=0,n=h(a,c),r=[],s={},p=!0,m=0;return this.$watch(n,function(){p?(p=!1,b(e,e,d)):b(e,g,d);if(k)if(H(e))if(Ea(e)){g=Array(e.length);for(var a=0;a<e.length;a++)g[a]=e[a]}else for(a in g={},e)Xa.call(e,a)&&(g[a]=e[a]);else g=e})},$digest:function(){var b,f,h,k,n,s,m=a,x,u=[],E,I;r("$digest");l.$$checkUrlChange();this===p&&null!==e&&(l.defer.cancel(e),F());d=null;do{s=!1;for(x=this;t.length;){try{I=t.shift(), I.scope.$eval(I.expression,I.locals)}catch(v){g(v)}d=null}a:do{if(k=x.$$watchers)for(n=k.length;n--;)try{if(b=k[n])if((f=b.get(x))!==(h=b.last)&&!(b.eq?ka(f,h):"number"===typeof f&&"number"===typeof h&&isNaN(f)&&isNaN(h)))s=!0,d=b,b.last=b.eq?fa(f,null):f,b.fn(f,h===q?f:h,x),5>m&&(E=4-m,u[E]||(u[E]=[]),u[E].push({msg:z(b.exp)?"fn: "+(b.exp.name||b.exp.toString()):b.exp,newVal:f,oldVal:h}));else if(b===d){s=!1;break a}}catch(A){g(A)}if(!(k=x.$$watchersCount&&x.$$childHead||x!==this&&x.$$nextSibling))for(;x!== this&&!(k=x.$$nextSibling);)x=x.$parent}while(x=k);if((s||t.length)&&!m--)throw p.$$phase=null,c("infdig",a,u);}while(s||t.length);for(p.$$phase=null;w.length;)try{w.shift()()}catch(y){g(y)}},$destroy:function(){if(!this.$$destroyed){var a=this.$parent;this.$broadcast("$destroy");this.$$destroyed=!0;this===p&&l.$$applicationDestroyed();s(this,-this.$$watchersCount);for(var b in this.$$listenerCount)x(this,this.$$listenerCount[b],b);a&&a.$$childHead==this&&(a.$$childHead=this.$$nextSibling);a&&a.$$childTail== this&&(a.$$childTail=this.$$prevSibling);this.$$prevSibling&&(this.$$prevSibling.$$nextSibling=this.$$nextSibling);this.$$nextSibling&&(this.$$nextSibling.$$prevSibling=this.$$prevSibling);this.$destroy=this.$digest=this.$apply=this.$evalAsync=this.$applyAsync=v;this.$on=this.$watch=this.$watchGroup=function(){return v};this.$$listeners={};this.$parent=this.$$nextSibling=this.$$prevSibling=this.$$childHead=this.$$childTail=this.$root=this.$$watchers=null}},$eval:function(a,b){return h(a)(this,b)}, $evalAsync:function(a,b){p.$$phase||t.length||l.defer(function(){t.length&&p.$digest()});t.push({scope:this,expression:a,locals:b})},$$postDigest:function(a){w.push(a)},$apply:function(a){try{return r("$apply"),this.$eval(a)}catch(b){g(b)}finally{p.$$phase=null;try{p.$digest()}catch(c){throw g(c),c;}}},$applyAsync:function(a){function b(){c.$eval(a)}var c=this;a&&I.push(b);u()},$on:function(a,b){var c=this.$$listeners[a];c||(this.$$listeners[a]=c=[]);c.push(b);var d=this;do d.$$listenerCount[a]|| (d.$$listenerCount[a]=0),d.$$listenerCount[a]++;while(d=d.$parent);var e=this;return function(){var d=c.indexOf(b);-1!==d&&(c[d]=null,x(e,1,a))}},$emit:function(a,b){var c=[],d,e=this,f=!1,h={name:a,targetScope:e,stopPropagation:function(){f=!0},preventDefault:function(){h.defaultPrevented=!0},defaultPrevented:!1},k=cb([h],arguments,1),l,n;do{d=e.$$listeners[a]||c;h.currentScope=e;l=0;for(n=d.length;l<n;l++)if(d[l])try{d[l].apply(null,k)}catch(r){g(r)}else d.splice(l,1),l--,n--;if(f)return h.currentScope= null,h;e=e.$parent}while(e);h.currentScope=null;return h},$broadcast:function(a,b){var c=this,d=this,e={name:a,targetScope:this,preventDefault:function(){e.defaultPrevented=!0},defaultPrevented:!1};if(!this.$$listenerCount[a])return e;for(var f=cb([e],arguments,1),h,k;c=d;){e.currentScope=c;d=c.$$listeners[a]||[];h=0;for(k=d.length;h<k;h++)if(d[h])try{d[h].apply(null,f)}catch(l){g(l)}else d.splice(h,1),h--,k--;if(!(d=c.$$listenerCount[a]&&c.$$childHead||c!==this&&c.$$nextSibling))for(;c!==this&&!(d= c.$$nextSibling);)c=c.$parent}e.currentScope=null;return e}};var p=new n,t=p.$$asyncQueue=[],w=p.$$postDigestQueue=[],I=p.$$applyAsyncQueue=[];return p}]}function he(){var b=/^\s*(https?|ftp|mailto|tel|file):/,a=/^\s*((https?|ftp|file|blob):|data:image\/)/;this.aHrefSanitizationWhitelist=function(a){return w(a)?(b=a,this):b};this.imgSrcSanitizationWhitelist=function(b){return w(b)?(a=b,this):a};this.$get=function(){return function(c,d){var e=d?a:b,f;f=Ba(c).href;return""===f||f.match(e)?c:"unsafe:"+ f}}}function $f(b){if("self"===b)return b;if(L(b)){if(-1<b.indexOf("***"))throw Da("iwcard",b);b=ud(b).replace("\\*\\*",".*").replace("\\*","[^:/.?&;]*");return new RegExp("^"+b+"$")}if(Za(b))return new RegExp("^"+b.source+"$");throw Da("imatcher");}function vd(b){var a=[];w(b)&&m(b,function(b){a.push($f(b))});return a}function nf(){this.SCE_CONTEXTS=pa;var b=["self"],a=[];this.resourceUrlWhitelist=function(a){arguments.length&&(b=vd(a));return b};this.resourceUrlBlacklist=function(b){arguments.length&& (a=vd(b));return a};this.$get=["$injector",function(c){function d(a,b){return"self"===a?gd(b):!!a.exec(b.href)}function e(a){var b=function(a){this.$$unwrapTrustedValue=function(){return a}};a&&(b.prototype=new a);b.prototype.valueOf=function(){return this.$$unwrapTrustedValue()};b.prototype.toString=function(){return this.$$unwrapTrustedValue().toString()};return b}var f=function(a){throw Da("unsafe");};c.has("$sanitize")&&(f=c.get("$sanitize"));var g=e(),h={};h[pa.HTML]=e(g);h[pa.CSS]=e(g);h[pa.URL]= e(g);h[pa.JS]=e(g);h[pa.RESOURCE_URL]=e(h[pa.URL]);return{trustAs:function(a,b){var c=h.hasOwnProperty(a)?h[a]:null;if(!c)throw Da("icontext",a,b);if(null===b||b===t||""===b)return b;if("string"!==typeof b)throw Da("itype",a);return new c(b)},getTrusted:function(c,e){if(null===e||e===t||""===e)return e;var g=h.hasOwnProperty(c)?h[c]:null;if(g&&e instanceof g)return e.$$unwrapTrustedValue();if(c===pa.RESOURCE_URL){var g=Ba(e.toString()),r,s,m=!1;r=0;for(s=b.length;r<s;r++)if(d(b[r],g)){m=!0;break}if(m)for(r= 0,s=a.length;r<s;r++)if(d(a[r],g)){m=!1;break}if(m)return e;throw Da("insecurl",e.toString());}if(c===pa.HTML)return f(e);throw Da("unsafe");},valueOf:function(a){return a instanceof g?a.$$unwrapTrustedValue():a}}}]}function mf(){var b=!0;this.enabled=function(a){arguments.length&&(b=!!a);return b};this.$get=["$parse","$sceDelegate",function(a,c){if(b&&8>Ua)throw Da("iequirks");var d=ia(pa);d.isEnabled=function(){return b};d.trustAs=c.trustAs;d.getTrusted=c.getTrusted;d.valueOf=c.valueOf;b||(d.trustAs= d.getTrusted=function(a,b){return b},d.valueOf=Ya);d.parseAs=function(b,c){var e=a(c);return e.literal&&e.constant?e:a(c,function(a){return d.getTrusted(b,a)})};var e=d.parseAs,f=d.getTrusted,g=d.trustAs;m(pa,function(a,b){var c=M(b);d[hb("parse_as_"+c)]=function(b){return e(a,b)};d[hb("get_trusted_"+c)]=function(b){return f(a,b)};d[hb("trust_as_"+c)]=function(b){return g(a,b)}});return d}]}function of(){this.$get=["$window","$document",function(b,a){var c={},d=W((/android (\d+)/.exec(M((b.navigator|| {}).userAgent))||[])[1]),e=/Boxee/i.test((b.navigator||{}).userAgent),f=a[0]||{},g,h=/^(Moz|webkit|ms)(?=[A-Z])/,l=f.body&&f.body.style,k=!1,n=!1;if(l){for(var r in l)if(k=h.exec(r)){g=k[0];g=g.substr(0,1).toUpperCase()+g.substr(1);break}g||(g="WebkitOpacity"in l&&"webkit");k=!!("transition"in l||g+"Transition"in l);n=!!("animation"in l||g+"Animation"in l);!d||k&&n||(k=L(l.webkitTransition),n=L(l.webkitAnimation))}return{history:!(!b.history||!b.history.pushState||4>d||e),hasEvent:function(a){if("input"=== a&&11>=Ua)return!1;if(A(c[a])){var b=f.createElement("div");c[a]="on"+a in b}return c[a]},csp:fb(),vendorPrefix:g,transitions:k,animations:n,android:d}}]}function qf(){this.$get=["$templateCache","$http","$q","$sce",function(b,a,c,d){function e(f,g){e.totalPendingRequests++;L(f)&&b.get(f)||(f=d.getTrustedResourceUrl(f));var h=a.defaults&&a.defaults.transformResponse;G(h)?h=h.filter(function(a){return a!==$b}):h===$b&&(h=null);return a.get(f,{cache:b,transformResponse:h})["finally"](function(){e.totalPendingRequests--}).then(function(a){b.put(f, a.data);return a.data},function(a){if(!g)throw ea("tpload",f,a.status,a.statusText);return c.reject(a)})}e.totalPendingRequests=0;return e}]}function rf(){this.$get=["$rootScope","$browser","$location",function(b,a,c){return{findBindings:function(a,b,c){a=a.getElementsByClassName("ng-binding");var g=[];m(a,function(a){var d=ca.element(a).data("$binding");d&&m(d,function(d){c?(new RegExp("(^|\\s)"+ud(b)+"(\\s|\\||$)")).test(d)&&g.push(a):-1!=d.indexOf(b)&&g.push(a)})});return g},findModels:function(a, b,c){for(var g=["ng-","data-ng-","ng\\:"],h=0;h<g.length;++h){var l=a.querySelectorAll("["+g[h]+"model"+(c?"=":"*=")+'"'+b+'"]');if(l.length)return l}},getLocation:function(){return c.url()},setLocation:function(a){a!==c.url()&&(c.url(a),b.$digest())},whenStable:function(b){a.notifyWhenNoOutstandingRequests(b)}}}]}function sf(){this.$get=["$rootScope","$browser","$q","$$q","$exceptionHandler",function(b,a,c,d,e){function f(f,l,k){z(f)||(k=l,l=f,f=v);var n=za.call(arguments,3),r=w(k)&&!k,s=(r?d:c).defer(), m=s.promise,q;q=a.defer(function(){try{s.resolve(f.apply(null,n))}catch(a){s.reject(a),e(a)}finally{delete g[m.$$timeoutId]}r||b.$apply()},l);m.$$timeoutId=q;g[q]=s;return m}var g={};f.cancel=function(b){return b&&b.$$timeoutId in g?(g[b.$$timeoutId].reject("canceled"),delete g[b.$$timeoutId],a.defer.cancel(b.$$timeoutId)):!1};return f}]}function Ba(b){Ua&&(X.setAttribute("href",b),b=X.href);X.setAttribute("href",b);return{href:X.href,protocol:X.protocol?X.protocol.replace(/:$/,""):"",host:X.host, search:X.search?X.search.replace(/^\?/,""):"",hash:X.hash?X.hash.replace(/^#/,""):"",hostname:X.hostname,port:X.port,pathname:"/"===X.pathname.charAt(0)?X.pathname:"/"+X.pathname}}function gd(b){b=L(b)?Ba(b):b;return b.protocol===wd.protocol&&b.host===wd.host}function tf(){this.$get=ra(O)}function xd(b){function a(a){try{return decodeURIComponent(a)}catch(b){return a}}var c=b[0]||{},d={},e="";return function(){var b,g,h,l,k;b=c.cookie||"";if(b!==e)for(e=b,b=e.split("; "),d={},h=0;h<b.length;h++)g= b[h],l=g.indexOf("="),0<l&&(k=a(g.substring(0,l)),d[k]===t&&(d[k]=a(g.substring(l+1))));return d}}function yf(){this.$get=xd}function Lc(b){function a(c,d){if(H(c)){var e={};m(c,function(b,c){e[c]=a(c,b)});return e}return b.factory(c+"Filter",d)}this.register=a;this.$get=["$injector",function(a){return function(b){return a.get(b+"Filter")}}];a("currency",yd);a("date",zd);a("filter",ag);a("json",bg);a("limitTo",cg);a("lowercase",dg);a("number",Ad);a("orderBy",Bd);a("uppercase",eg)}function ag(){return function(b, a,c){if(!Ea(b)){if(null==b)return b;throw J("filter")("notarray",b);}var d;switch(ic(a)){case "function":break;case "boolean":case "null":case "number":case "string":d=!0;case "object":a=fg(a,c,d);break;default:return b}return Array.prototype.filter.call(b,a)}}function fg(b,a,c){var d=H(b)&&"$"in b;!0===a?a=ka:z(a)||(a=function(a,b){if(A(a))return!1;if(null===a||null===b)return a===b;if(H(b)||H(a)&&!rc(a))return!1;a=M(""+a);b=M(""+b);return-1!==a.indexOf(b)});return function(e){return d&&!H(e)?La(e, b.$,a,!1):La(e,b,a,c)}}function La(b,a,c,d,e){var f=ic(b),g=ic(a);if("string"===g&&"!"===a.charAt(0))return!La(b,a.substring(1),c,d);if(G(b))return b.some(function(b){return La(b,a,c,d)});switch(f){case "object":var h;if(d){for(h in b)if("$"!==h.charAt(0)&&La(b[h],a,c,!0))return!0;return e?!1:La(b,a,c,!1)}if("object"===g){for(h in a)if(e=a[h],!z(e)&&!A(e)&&(f="$"===h,!La(f?b:b[h],e,c,f,f)))return!1;return!0}return c(b,a);case "function":return!1;default:return c(b,a)}}function ic(b){return null=== b?"null":typeof b}function yd(b){var a=b.NUMBER_FORMATS;return function(b,d,e){A(d)&&(d=a.CURRENCY_SYM);A(e)&&(e=a.PATTERNS[1].maxFrac);return null==b?b:Cd(b,a.PATTERNS[1],a.GROUP_SEP,a.DECIMAL_SEP,e).replace(/\u00A4/g,d)}}function Ad(b){var a=b.NUMBER_FORMATS;return function(b,d){return null==b?b:Cd(b,a.PATTERNS[0],a.GROUP_SEP,a.DECIMAL_SEP,d)}}function Cd(b,a,c,d,e){if(H(b))return"";var f=0>b;b=Math.abs(b);var g=Infinity===b;if(!g&&!isFinite(b))return"";var h=b+"",l="",k=!1,n=[];g&&(l="\u221e"); if(!g&&-1!==h.indexOf("e")){var r=h.match(/([\d\.]+)e(-?)(\d+)/);r&&"-"==r[2]&&r[3]>e+1?b=0:(l=h,k=!0)}if(g||k)0<e&&1>b&&(l=b.toFixed(e),b=parseFloat(l));else{g=(h.split(Dd)[1]||"").length;A(e)&&(e=Math.min(Math.max(a.minFrac,g),a.maxFrac));b=+(Math.round(+(b.toString()+"e"+e)).toString()+"e"+-e);var g=(""+b).split(Dd),h=g[0],g=g[1]||"",r=0,s=a.lgSize,m=a.gSize;if(h.length>=s+m)for(r=h.length-s,k=0;k<r;k++)0===(r-k)%m&&0!==k&&(l+=c),l+=h.charAt(k);for(k=r;k<h.length;k++)0===(h.length-k)%s&&0!==k&& (l+=c),l+=h.charAt(k);for(;g.length<e;)g+="0";e&&"0"!==e&&(l+=d+g.substr(0,e))}0===b&&(f=!1);n.push(f?a.negPre:a.posPre,l,f?a.negSuf:a.posSuf);return n.join("")}function Gb(b,a,c){var d="";0>b&&(d="-",b=-b);for(b=""+b;b.length<a;)b="0"+b;c&&(b=b.substr(b.length-a));return d+b}function Y(b,a,c,d){c=c||0;return function(e){e=e["get"+b]();if(0<c||e>-c)e+=c;0===e&&-12==c&&(e=12);return Gb(e,a,d)}}function Hb(b,a){return function(c,d){var e=c["get"+b](),f=rb(a?"SHORT"+b:b);return d[f][e]}}function Ed(b){var a= (new Date(b,0,1)).getDay();return new Date(b,0,(4>=a?5:12)-a)}function Fd(b){return function(a){var c=Ed(a.getFullYear());a=+new Date(a.getFullYear(),a.getMonth(),a.getDate()+(4-a.getDay()))-+c;a=1+Math.round(a/6048E5);return Gb(a,b)}}function jc(b,a){return 0>=b.getFullYear()?a.ERAS[0]:a.ERAS[1]}function zd(b){function a(a){var b;if(b=a.match(c)){a=new Date(0);var f=0,g=0,h=b[8]?a.setUTCFullYear:a.setFullYear,l=b[8]?a.setUTCHours:a.setHours;b[9]&&(f=W(b[9]+b[10]),g=W(b[9]+b[11]));h.call(a,W(b[1]), W(b[2])-1,W(b[3]));f=W(b[4]||0)-f;g=W(b[5]||0)-g;h=W(b[6]||0);b=Math.round(1E3*parseFloat("0."+(b[7]||0)));l.call(a,f,g,h,b)}return a}var c=/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;return function(c,e,f){var g="",h=[],l,k;e=e||"mediumDate";e=b.DATETIME_FORMATS[e]||e;L(c)&&(c=gg.test(c)?W(c):a(c));V(c)&&(c=new Date(c));if(!aa(c)||!isFinite(c.getTime()))return c;for(;e;)(k=hg.exec(e))?(h=cb(h,k,1),e=h.pop()):(h.push(e),e=null);var n=c.getTimezoneOffset(); f&&(n=xc(f,c.getTimezoneOffset()),c=Pb(c,f,!0));m(h,function(a){l=ig[a];g+=l?l(c,b.DATETIME_FORMATS,n):a.replace(/(^'|'$)/g,"").replace(/''/g,"'")});return g}}function bg(){return function(b,a){A(a)&&(a=2);return db(b,a)}}function cg(){return function(b,a,c){a=Infinity===Math.abs(Number(a))?Number(a):W(a);if(isNaN(a))return b;V(b)&&(b=b.toString());if(!G(b)&&!L(b))return b;c=!c||isNaN(c)?0:W(c);c=0>c&&c>=-b.length?b.length+c:c;return 0<=a?b.slice(c,c+a):0===c?b.slice(a,b.length):b.slice(Math.max(0, c+a),c)}}function Bd(b){function a(a,c){c=c?-1:1;return a.map(function(a){var d=1,h=Ya;if(z(a))h=a;else if(L(a)){if("+"==a.charAt(0)||"-"==a.charAt(0))d="-"==a.charAt(0)?-1:1,a=a.substring(1);if(""!==a&&(h=b(a),h.constant))var l=h(),h=function(a){return a[l]}}return{get:h,descending:d*c}})}function c(a){switch(typeof a){case "number":case "boolean":case "string":return!0;default:return!1}}return function(b,e,f){if(!Ea(b))return b;G(e)||(e=[e]);0===e.length&&(e=["+"]);var g=a(e,f);b=Array.prototype.map.call(b, function(a,b){return{value:a,predicateValues:g.map(function(d){var e=d.get(a);d=typeof e;if(null===e)d="string",e="null";else if("string"===d)e=e.toLowerCase();else if("object"===d)a:{if("function"===typeof e.valueOf&&(e=e.valueOf(),c(e)))break a;if(rc(e)&&(e=e.toString(),c(e)))break a;e=b}return{value:e,type:d}})}});b.sort(function(a,b){for(var c=0,d=0,e=g.length;d<e;++d){var c=a.predicateValues[d],f=b.predicateValues[d],m=0;c.type===f.type?c.value!==f.value&&(m=c.value<f.value?-1:1):m=c.type<f.type? -1:1;if(c=m*g[d].descending)break}return c});return b=b.map(function(a){return a.value})}}function Ma(b){z(b)&&(b={link:b});b.restrict=b.restrict||"AC";return ra(b)}function Gd(b,a,c,d,e){var f=this,g=[],h=f.$$parentForm=b.parent().controller("form")||Ib;f.$error={};f.$$success={};f.$pending=t;f.$name=e(a.name||a.ngForm||"")(c);f.$dirty=!1;f.$pristine=!0;f.$valid=!0;f.$invalid=!1;f.$submitted=!1;h.$addControl(f);f.$rollbackViewValue=function(){m(g,function(a){a.$rollbackViewValue()})};f.$commitViewValue= function(){m(g,function(a){a.$commitViewValue()})};f.$addControl=function(a){Ra(a.$name,"input");g.push(a);a.$name&&(f[a.$name]=a)};f.$$renameControl=function(a,b){var c=a.$name;f[c]===a&&delete f[c];f[b]=a;a.$name=b};f.$removeControl=function(a){a.$name&&f[a.$name]===a&&delete f[a.$name];m(f.$pending,function(b,c){f.$setValidity(c,null,a)});m(f.$error,function(b,c){f.$setValidity(c,null,a)});m(f.$$success,function(b,c){f.$setValidity(c,null,a)});bb(g,a)};Hd({ctrl:this,$element:b,set:function(a,b, c){var d=a[b];d?-1===d.indexOf(c)&&d.push(c):a[b]=[c]},unset:function(a,b,c){var d=a[b];d&&(bb(d,c),0===d.length&&delete a[b])},parentForm:h,$animate:d});f.$setDirty=function(){d.removeClass(b,Va);d.addClass(b,Jb);f.$dirty=!0;f.$pristine=!1;h.$setDirty()};f.$setPristine=function(){d.setClass(b,Va,Jb+" ng-submitted");f.$dirty=!1;f.$pristine=!0;f.$submitted=!1;m(g,function(a){a.$setPristine()})};f.$setUntouched=function(){m(g,function(a){a.$setUntouched()})};f.$setSubmitted=function(){d.addClass(b, "ng-submitted");f.$submitted=!0;h.$setSubmitted()}}function kc(b){b.$formatters.push(function(a){return b.$isEmpty(a)?a:a.toString()})}function kb(b,a,c,d,e,f){var g=M(a[0].type);if(!e.android){var h=!1;a.on("compositionstart",function(a){h=!0});a.on("compositionend",function(){h=!1;l()})}var l=function(b){k&&(f.defer.cancel(k),k=null);if(!h){var e=a.val();b=b&&b.type;"password"===g||c.ngTrim&&"false"===c.ngTrim||(e=R(e));(d.$viewValue!==e||""===e&&d.$$hasNativeValidators)&&d.$setViewValue(e,b)}}; if(e.hasEvent("input"))a.on("input",l);else{var k,n=function(a,b,c){k||(k=f.defer(function(){k=null;b&&b.value===c||l(a)}))};a.on("keydown",function(a){var b=a.keyCode;91===b||15<b&&19>b||37<=b&&40>=b||n(a,this,this.value)});if(e.hasEvent("paste"))a.on("paste cut",n)}a.on("change",l);d.$render=function(){a.val(d.$isEmpty(d.$viewValue)?"":d.$viewValue)}}function Kb(b,a){return function(c,d){var e,f;if(aa(c))return c;if(L(c)){'"'==c.charAt(0)&&'"'==c.charAt(c.length-1)&&(c=c.substring(1,c.length-1)); if(jg.test(c))return new Date(c);b.lastIndex=0;if(e=b.exec(c))return e.shift(),f=d?{yyyy:d.getFullYear(),MM:d.getMonth()+1,dd:d.getDate(),HH:d.getHours(),mm:d.getMinutes(),ss:d.getSeconds(),sss:d.getMilliseconds()/1E3}:{yyyy:1970,MM:1,dd:1,HH:0,mm:0,ss:0,sss:0},m(e,function(b,c){c<a.length&&(f[a[c]]=+b)}),new Date(f.yyyy,f.MM-1,f.dd,f.HH,f.mm,f.ss||0,1E3*f.sss||0)}return NaN}}function lb(b,a,c,d){return function(e,f,g,h,l,k,n){function r(a){return a&&!(a.getTime&&a.getTime()!==a.getTime())}function s(a){return w(a)? aa(a)?a:c(a):t}Id(e,f,g,h);kb(e,f,g,h,l,k);var m=h&&h.$options&&h.$options.timezone,q;h.$$parserName=b;h.$parsers.push(function(b){return h.$isEmpty(b)?null:a.test(b)?(b=c(b,q),m&&(b=Pb(b,m)),b):t});h.$formatters.push(function(a){if(a&&!aa(a))throw Lb("datefmt",a);if(r(a))return(q=a)&&m&&(q=Pb(q,m,!0)),n("date")(a,d,m);q=null;return""});if(w(g.min)||g.ngMin){var F;h.$validators.min=function(a){return!r(a)||A(F)||c(a)>=F};g.$observe("min",function(a){F=s(a);h.$validate()})}if(w(g.max)||g.ngMax){var u; h.$validators.max=function(a){return!r(a)||A(u)||c(a)<=u};g.$observe("max",function(a){u=s(a);h.$validate()})}}}function Id(b,a,c,d){(d.$$hasNativeValidators=H(a[0].validity))&&d.$parsers.push(function(b){var c=a.prop("validity")||{};return c.badInput&&!c.typeMismatch?t:b})}function Jd(b,a,c,d,e){if(w(d)){b=b(d);if(!b.constant)throw J("ngModel")("constexpr",c,d);return b(a)}return e}function lc(b,a){b="ngClass"+b;return["$animate",function(c){function d(a,b){var c=[],d=0;a:for(;d<a.length;d++){for(var e= a[d],n=0;n<b.length;n++)if(e==b[n])continue a;c.push(e)}return c}function e(a){var b=[];return G(a)?(m(a,function(a){b=b.concat(e(a))}),b):L(a)?a.split(" "):H(a)?(m(a,function(a,c){a&&(b=b.concat(c.split(" ")))}),b):a}return{restrict:"AC",link:function(f,g,h){function l(a,b){var c=g.data("$classCounts")||ga(),d=[];m(a,function(a){if(0<b||c[a])c[a]=(c[a]||0)+b,c[a]===+(0<b)&&d.push(a)});g.data("$classCounts",c);return d.join(" ")}function k(b){if(!0===a||f.$index%2===a){var k=e(b||[]);if(!n){var m= l(k,1);h.$addClass(m)}else if(!ka(b,n)){var q=e(n),m=d(k,q),k=d(q,k),m=l(m,1),k=l(k,-1);m&&m.length&&c.addClass(g,m);k&&k.length&&c.removeClass(g,k)}}n=ia(b)}var n;f.$watch(h[b],k,!0);h.$observe("class",function(a){k(f.$eval(h[b]))});"ngClass"!==b&&f.$watch("$index",function(c,d){var g=c&1;if(g!==(d&1)){var k=e(f.$eval(h[b]));g===a?(g=l(k,1),h.$addClass(g)):(g=l(k,-1),h.$removeClass(g))}})}}}]}function Hd(b){function a(a,b){b&&!f[a]?(k.addClass(e,a),f[a]=!0):!b&&f[a]&&(k.removeClass(e,a),f[a]=!1)} function c(b,c){b=b?"-"+Bc(b,"-"):"";a(mb+b,!0===c);a(Kd+b,!1===c)}var d=b.ctrl,e=b.$element,f={},g=b.set,h=b.unset,l=b.parentForm,k=b.$animate;f[Kd]=!(f[mb]=e.hasClass(mb));d.$setValidity=function(b,e,f){e===t?(d.$pending||(d.$pending={}),g(d.$pending,b,f)):(d.$pending&&h(d.$pending,b,f),Ld(d.$pending)&&(d.$pending=t));ab(e)?e?(h(d.$error,b,f),g(d.$$success,b,f)):(g(d.$error,b,f),h(d.$$success,b,f)):(h(d.$error,b,f),h(d.$$success,b,f));d.$pending?(a(Md,!0),d.$valid=d.$invalid=t,c("",null)):(a(Md, !1),d.$valid=Ld(d.$error),d.$invalid=!d.$valid,c("",d.$valid));e=d.$pending&&d.$pending[b]?t:d.$error[b]?!1:d.$$success[b]?!0:null;c(b,e);l.$setValidity(b,e,d)}}function Ld(b){if(b)for(var a in b)if(b.hasOwnProperty(a))return!1;return!0}var kg=/^\/(.+)\/([a-z]*)$/,M=function(b){return L(b)?b.toLowerCase():b},Xa=Object.prototype.hasOwnProperty,rb=function(b){return L(b)?b.toUpperCase():b},Ua,y,la,za=[].slice,Nf=[].splice,lg=[].push,sa=Object.prototype.toString,sc=Object.getPrototypeOf,Fa=J("ng"),ca= O.angular||(O.angular={}),gb,nb=0;Ua=U.documentMode;v.$inject=[];Ya.$inject=[];var G=Array.isArray,uc=/^\[object (Uint8(Clamped)?)|(Uint16)|(Uint32)|(Int8)|(Int16)|(Int32)|(Float(32)|(64))Array\]$/,R=function(b){return L(b)?b.trim():b},ud=function(b){return b.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g,"\\$1").replace(/\x08/g,"\\x08")},fb=function(){if(w(fb.isActive_))return fb.isActive_;var b=!(!U.querySelector("[ng-csp]")&&!U.querySelector("[data-ng-csp]"));if(!b)try{new Function("")}catch(a){b=!0}return fb.isActive_= b},pb=function(){if(w(pb.name_))return pb.name_;var b,a,c=Oa.length,d,e;for(a=0;a<c;++a)if(d=Oa[a],b=U.querySelector("["+d.replace(":","\\:")+"jq]")){e=b.getAttribute(d+"jq");break}return pb.name_=e},Oa=["ng-","data-ng-","ng:","x-ng-"],be=/[A-Z]/g,Cc=!1,Rb,qa=1,Na=3,fe={full:"1.4.2",major:1,minor:4,dot:2,codeName:"nebular-readjustment"};Q.expando="ng339";var ib=Q.cache={},Ef=1;Q._data=function(b){return this.cache[b[this.expando]]||{}};var zf=/([\:\-\_]+(.))/g,Af=/^moz([A-Z])/,mg={mouseleave:"mouseout", mouseenter:"mouseover"},Ub=J("jqLite"),Df=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,Tb=/<|&#?\w+;/,Bf=/<([\w:]+)/,Cf=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,na={option:[1,'<select multiple="multiple">',"</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};na.optgroup=na.option;na.tbody=na.tfoot=na.colgroup=na.caption=na.thead; na.th=na.td;var Pa=Q.prototype={ready:function(b){function a(){c||(c=!0,b())}var c=!1;"complete"===U.readyState?setTimeout(a):(this.on("DOMContentLoaded",a),Q(O).on("load",a))},toString:function(){var b=[];m(this,function(a){b.push(""+a)});return"["+b.join(", ")+"]"},eq:function(b){return 0<=b?y(this[b]):y(this[this.length+b])},length:0,push:lg,sort:[].sort,splice:[].splice},Ab={};m("multiple selected checked disabled readOnly required open".split(" "),function(b){Ab[M(b)]=b});var Tc={};m("input select option textarea button form details".split(" "), function(b){Tc[b]=!0});var Uc={ngMinlength:"minlength",ngMaxlength:"maxlength",ngMin:"min",ngMax:"max",ngPattern:"pattern"};m({data:Wb,removeData:ub,hasData:function(b){for(var a in ib[b.ng339])return!0;return!1}},function(b,a){Q[a]=b});m({data:Wb,inheritedData:zb,scope:function(b){return y.data(b,"$scope")||zb(b.parentNode||b,["$isolateScope","$scope"])},isolateScope:function(b){return y.data(b,"$isolateScope")||y.data(b,"$isolateScopeNoTemplate")},controller:Qc,injector:function(b){return zb(b, "$injector")},removeAttr:function(b,a){b.removeAttribute(a)},hasClass:wb,css:function(b,a,c){a=hb(a);if(w(c))b.style[a]=c;else return b.style[a]},attr:function(b,a,c){var d=b.nodeType;if(d!==Na&&2!==d&&8!==d)if(d=M(a),Ab[d])if(w(c))c?(b[a]=!0,b.setAttribute(a,d)):(b[a]=!1,b.removeAttribute(d));else return b[a]||(b.attributes.getNamedItem(a)||v).specified?d:t;else if(w(c))b.setAttribute(a,c);else if(b.getAttribute)return b=b.getAttribute(a,2),null===b?t:b},prop:function(b,a,c){if(w(c))b[a]=c;else return b[a]}, text:function(){function b(a,b){if(A(b)){var d=a.nodeType;return d===qa||d===Na?a.textContent:""}a.textContent=b}b.$dv="";return b}(),val:function(b,a){if(A(a)){if(b.multiple&&"select"===ta(b)){var c=[];m(b.options,function(a){a.selected&&c.push(a.value||a.text)});return 0===c.length?null:c}return b.value}b.value=a},html:function(b,a){if(A(a))return b.innerHTML;tb(b,!0);b.innerHTML=a},empty:Rc},function(b,a){Q.prototype[a]=function(a,d){var e,f,g=this.length;if(b!==Rc&&(2==b.length&&b!==wb&&b!==Qc? a:d)===t){if(H(a)){for(e=0;e<g;e++)if(b===Wb)b(this[e],a);else for(f in a)b(this[e],f,a[f]);return this}e=b.$dv;g=e===t?Math.min(g,1):g;for(f=0;f<g;f++){var h=b(this[f],a,d);e=e?e+h:h}return e}for(e=0;e<g;e++)b(this[e],a,d);return this}});m({removeData:ub,on:function a(c,d,e,f){if(w(f))throw Ub("onargs");if(Mc(c)){var g=vb(c,!0);f=g.events;var h=g.handle;h||(h=g.handle=Hf(c,f));for(var g=0<=d.indexOf(" ")?d.split(" "):[d],l=g.length;l--;){d=g[l];var k=f[d];k||(f[d]=[],"mouseenter"===d||"mouseleave"=== d?a(c,mg[d],function(a){var c=a.relatedTarget;c&&(c===this||this.contains(c))||h(a,d)}):"$destroy"!==d&&c.addEventListener(d,h,!1),k=f[d]);k.push(e)}}},off:Pc,one:function(a,c,d){a=y(a);a.on(c,function f(){a.off(c,d);a.off(c,f)});a.on(c,d)},replaceWith:function(a,c){var d,e=a.parentNode;tb(a);m(new Q(c),function(c){d?e.insertBefore(c,d.nextSibling):e.replaceChild(c,a);d=c})},children:function(a){var c=[];m(a.childNodes,function(a){a.nodeType===qa&&c.push(a)});return c},contents:function(a){return a.contentDocument|| a.childNodes||[]},append:function(a,c){var d=a.nodeType;if(d===qa||11===d){c=new Q(c);for(var d=0,e=c.length;d<e;d++)a.appendChild(c[d])}},prepend:function(a,c){if(a.nodeType===qa){var d=a.firstChild;m(new Q(c),function(c){a.insertBefore(c,d)})}},wrap:function(a,c){c=y(c).eq(0).clone()[0];var d=a.parentNode;d&&d.replaceChild(c,a);c.appendChild(a)},remove:Xb,detach:function(a){Xb(a,!0)},after:function(a,c){var d=a,e=a.parentNode;c=new Q(c);for(var f=0,g=c.length;f<g;f++){var h=c[f];e.insertBefore(h, d.nextSibling);d=h}},addClass:yb,removeClass:xb,toggleClass:function(a,c,d){c&&m(c.split(" "),function(c){var f=d;A(f)&&(f=!wb(a,c));(f?yb:xb)(a,c)})},parent:function(a){return(a=a.parentNode)&&11!==a.nodeType?a:null},next:function(a){return a.nextElementSibling},find:function(a,c){return a.getElementsByTagName?a.getElementsByTagName(c):[]},clone:Vb,triggerHandler:function(a,c,d){var e,f,g=c.type||c,h=vb(a);if(h=(h=h&&h.events)&&h[g])e={preventDefault:function(){this.defaultPrevented=!0},isDefaultPrevented:function(){return!0=== this.defaultPrevented},stopImmediatePropagation:function(){this.immediatePropagationStopped=!0},isImmediatePropagationStopped:function(){return!0===this.immediatePropagationStopped},stopPropagation:v,type:g,target:a},c.type&&(e=P(e,c)),c=ia(h),f=d?[e].concat(d):[e],m(c,function(c){e.isImmediatePropagationStopped()||c.apply(a,f)})}},function(a,c){Q.prototype[c]=function(c,e,f){for(var g,h=0,l=this.length;h<l;h++)A(g)?(g=a(this[h],c,e,f),w(g)&&(g=y(g))):Oc(g,a(this[h],c,e,f));return w(g)?g:this};Q.prototype.bind= Q.prototype.on;Q.prototype.unbind=Q.prototype.off});Sa.prototype={put:function(a,c){this[Ga(a,this.nextUid)]=c},get:function(a){return this[Ga(a,this.nextUid)]},remove:function(a){var c=this[a=Ga(a,this.nextUid)];delete this[a];return c}};var xf=[function(){this.$get=[function(){return Sa}]}],Wc=/^function\s*[^\(]*\(\s*([^\)]*)\)/m,ng=/,/,og=/^\s*(_?)(\S+?)\1\s*$/,Vc=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,Ha=J("$injector");eb.$$annotate=function(a,c,d){var e;if("function"===typeof a){if(!(e=a.$inject)){e= [];if(a.length){if(c)throw L(d)&&d||(d=a.name||If(a)),Ha("strictdi",d);c=a.toString().replace(Vc,"");c=c.match(Wc);m(c[1].split(ng),function(a){a.replace(og,function(a,c,d){e.push(d)})})}a.$inject=e}}else G(a)?(c=a.length-1,Qa(a[c],"fn"),e=a.slice(0,c)):Qa(a,"fn",!0);return e};var Nd=J("$animate"),Ue=function(){this.$get=["$q","$$rAF",function(a,c){function d(){}d.all=v;d.chain=v;d.prototype={end:v,cancel:v,resume:v,pause:v,complete:v,then:function(d,f){return a(function(a){c(function(){a()})}).then(d, f)}};return d}]},Te=function(){var a=new Sa,c=[];this.$get=["$$AnimateRunner","$rootScope",function(d,e){function f(d,f,l){var k=a.get(d);k||(a.put(d,k={}),c.push(d));f&&m(f.split(" "),function(a){a&&(k[a]=!0)});l&&m(l.split(" "),function(a){a&&(k[a]=!1)});1<c.length||e.$$postDigest(function(){m(c,function(c){var d=a.get(c);if(d){var e=Jf(c.attr("class")),f="",g="";m(d,function(a,c){a!==!!e[c]&&(a?f+=(f.length?" ":"")+c:g+=(g.length?" ":"")+c)});m(c,function(a){f&&yb(a,f);g&&xb(a,g)});a.remove(c)}}); c.length=0})}return{enabled:v,on:v,off:v,pin:v,push:function(a,c,e,k){k&&k();e=e||{};e.from&&a.css(e.from);e.to&&a.css(e.to);(e.addClass||e.removeClass)&&f(a,e.addClass,e.removeClass);return new d}}}]},Se=["$provide",function(a){var c=this;this.$$registeredAnimations=Object.create(null);this.register=function(d,e){if(d&&"."!==d.charAt(0))throw Nd("notcsel",d);var f=d+"-animation";c.$$registeredAnimations[d.substr(1)]=f;a.factory(f,e)};this.classNameFilter=function(a){if(1===arguments.length&&(this.$$classNameFilter= a instanceof RegExp?a:null)&&/(\s+|\/)ng-animate(\s+|\/)/.test(this.$$classNameFilter.toString()))throw Nd("nongcls","ng-animate");return this.$$classNameFilter};this.$get=["$$animateQueue",function(a){function c(a,d,e){if(e){var l;a:{for(l=0;l<e.length;l++){var k=e[l];if(1===k.nodeType){l=k;break a}}l=void 0}!l||l.parentNode||l.previousElementSibling||(e=null)}e?e.after(a):d.prepend(a)}return{on:a.on,off:a.off,pin:a.pin,enabled:a.enabled,cancel:function(a){a.end&&a.end()},enter:function(f,g,h,l){g= g&&y(g);h=h&&y(h);g=g||h.parent();c(f,g,h);return a.push(f,"enter",Ia(l))},move:function(f,g,h,l){g=g&&y(g);h=h&&y(h);g=g||h.parent();c(f,g,h);return a.push(f,"move",Ia(l))},leave:function(c,e){return a.push(c,"leave",Ia(e),function(){c.remove()})},addClass:function(c,e,h){h=Ia(h);h.addClass=jb(h.addclass,e);return a.push(c,"addClass",h)},removeClass:function(c,e,h){h=Ia(h);h.removeClass=jb(h.removeClass,e);return a.push(c,"removeClass",h)},setClass:function(c,e,h,l){l=Ia(l);l.addClass=jb(l.addClass, e);l.removeClass=jb(l.removeClass,h);return a.push(c,"setClass",l)},animate:function(c,e,h,l,k){k=Ia(k);k.from=k.from?P(k.from,e):e;k.to=k.to?P(k.to,h):h;k.tempClasses=jb(k.tempClasses,l||"ng-inline-animate");return a.push(c,"animate",k)}}}]}],ea=J("$compile");Ec.$inject=["$provide","$$sanitizeUriProvider"];var Zc=/^((?:x|data)[\:\-_])/i,Of=J("$controller"),Xc=/^(\S+)(\s+as\s+(\w+))?$/,cd="application/json",ac={"Content-Type":cd+";charset=utf-8"},Qf=/^\[|^\{(?!\{)/,Rf={"[":/]$/,"{":/}$/},Pf=/^\)\]\}',?\n/, Ka=ca.$interpolateMinErr=J("$interpolate");Ka.throwNoconcat=function(a){throw Ka("noconcat",a);};Ka.interr=function(a,c){return Ka("interr",a,c.toString())};var pg=/^([^\?#]*)(\?([^#]*))?(#(.*))?$/,Uf={http:80,https:443,ftp:21},Cb=J("$location"),qg={$$html5:!1,$$replace:!1,absUrl:Db("$$absUrl"),url:function(a){if(A(a))return this.$$url;var c=pg.exec(a);(c[1]||""===a)&&this.path(decodeURIComponent(c[1]));(c[2]||c[1]||""===a)&&this.search(c[3]||"");this.hash(c[5]||"");return this},protocol:Db("$$protocol"), host:Db("$$host"),port:Db("$$port"),path:kd("$$path",function(a){a=null!==a?a.toString():"";return"/"==a.charAt(0)?a:"/"+a}),search:function(a,c){switch(arguments.length){case 0:return this.$$search;case 1:if(L(a)||V(a))a=a.toString(),this.$$search=zc(a);else if(H(a))a=fa(a,{}),m(a,function(c,e){null==c&&delete a[e]}),this.$$search=a;else throw Cb("isrcharg");break;default:A(c)||null===c?delete this.$$search[a]:this.$$search[a]=c}this.$$compose();return this},hash:kd("$$hash",function(a){return null!== a?a.toString():""}),replace:function(){this.$$replace=!0;return this}};m([jd,ec,dc],function(a){a.prototype=Object.create(qg);a.prototype.state=function(c){if(!arguments.length)return this.$$state;if(a!==dc||!this.$$html5)throw Cb("nostate");this.$$state=A(c)?null:c;return this}});var da=J("$parse"),Vf=Function.prototype.call,Wf=Function.prototype.apply,Xf=Function.prototype.bind,Mb=ga();m("+ - * / % === !== == != < > <= >= && || ! = |".split(" "),function(a){Mb[a]=!0});var rg={n:"\n",f:"\f",r:"\r", t:"\t",v:"\v","'":"'",'"':'"'},gc=function(a){this.options=a};gc.prototype={constructor:gc,lex:function(a){this.text=a;this.index=0;for(this.tokens=[];this.index<this.text.length;)if(a=this.text.charAt(this.index),'"'===a||"'"===a)this.readString(a);else if(this.isNumber(a)||"."===a&&this.isNumber(this.peek()))this.readNumber();else if(this.isIdent(a))this.readIdent();else if(this.is(a,"(){}[].,;:?"))this.tokens.push({index:this.index,text:a}),this.index++;else if(this.isWhitespace(a))this.index++; else{var c=a+this.peek(),d=c+this.peek(2),e=Mb[c],f=Mb[d];Mb[a]||e||f?(a=f?d:e?c:a,this.tokens.push({index:this.index,text:a,operator:!0}),this.index+=a.length):this.throwError("Unexpected next character ",this.index,this.index+1)}return this.tokens},is:function(a,c){return-1!==c.indexOf(a)},peek:function(a){a=a||1;return this.index+a<this.text.length?this.text.charAt(this.index+a):!1},isNumber:function(a){return"0"<=a&&"9">=a&&"string"===typeof a},isWhitespace:function(a){return" "===a||"\r"===a|| "\t"===a||"\n"===a||"\v"===a||"\u00a0"===a},isIdent:function(a){return"a"<=a&&"z">=a||"A"<=a&&"Z">=a||"_"===a||"$"===a},isExpOperator:function(a){return"-"===a||"+"===a||this.isNumber(a)},throwError:function(a,c,d){d=d||this.index;c=w(c)?"s "+c+"-"+this.index+" ["+this.text.substring(c,d)+"]":" "+d;throw da("lexerr",a,c,this.text);},readNumber:function(){for(var a="",c=this.index;this.index<this.text.length;){var d=M(this.text.charAt(this.index));if("."==d||this.isNumber(d))a+=d;else{var e=this.peek(); if("e"==d&&this.isExpOperator(e))a+=d;else if(this.isExpOperator(d)&&e&&this.isNumber(e)&&"e"==a.charAt(a.length-1))a+=d;else if(!this.isExpOperator(d)||e&&this.isNumber(e)||"e"!=a.charAt(a.length-1))break;else this.throwError("Invalid exponent")}this.index++}this.tokens.push({index:c,text:a,constant:!0,value:Number(a)})},readIdent:function(){for(var a=this.index;this.index<this.text.length;){var c=this.text.charAt(this.index);if(!this.isIdent(c)&&!this.isNumber(c))break;this.index++}this.tokens.push({index:a, text:this.text.slice(a,this.index),identifier:!0})},readString:function(a){var c=this.index;this.index++;for(var d="",e=a,f=!1;this.index<this.text.length;){var g=this.text.charAt(this.index),e=e+g;if(f)"u"===g?(f=this.text.substring(this.index+1,this.index+5),f.match(/[\da-f]{4}/i)||this.throwError("Invalid unicode escape [\\u"+f+"]"),this.index+=4,d+=String.fromCharCode(parseInt(f,16))):d+=rg[g]||g,f=!1;else if("\\"===g)f=!0;else{if(g===a){this.index++;this.tokens.push({index:c,text:e,constant:!0, value:d});return}d+=g}this.index++}this.throwError("Unterminated quote",c)}};var q=function(a,c){this.lexer=a;this.options=c};q.Program="Program";q.ExpressionStatement="ExpressionStatement";q.AssignmentExpression="AssignmentExpression";q.ConditionalExpression="ConditionalExpression";q.LogicalExpression="LogicalExpression";q.BinaryExpression="BinaryExpression";q.UnaryExpression="UnaryExpression";q.CallExpression="CallExpression";q.MemberExpression="MemberExpression";q.Identifier="Identifier";q.Literal= "Literal";q.ArrayExpression="ArrayExpression";q.Property="Property";q.ObjectExpression="ObjectExpression";q.ThisExpression="ThisExpression";q.NGValueParameter="NGValueParameter";q.prototype={ast:function(a){this.text=a;this.tokens=this.lexer.lex(a);a=this.program();0!==this.tokens.length&&this.throwError("is an unexpected token",this.tokens[0]);return a},program:function(){for(var a=[];;)if(0<this.tokens.length&&!this.peek("}",")",";","]")&&a.push(this.expressionStatement()),!this.expect(";"))return{type:q.Program, body:a}},expressionStatement:function(){return{type:q.ExpressionStatement,expression:this.filterChain()}},filterChain:function(){for(var a=this.expression();this.expect("|");)a=this.filter(a);return a},expression:function(){return this.assignment()},assignment:function(){var a=this.ternary();this.expect("=")&&(a={type:q.AssignmentExpression,left:a,right:this.assignment(),operator:"="});return a},ternary:function(){var a=this.logicalOR(),c,d;return this.expect("?")&&(c=this.expression(),this.consume(":"))? (d=this.expression(),{type:q.ConditionalExpression,test:a,alternate:c,consequent:d}):a},logicalOR:function(){for(var a=this.logicalAND();this.expect("||");)a={type:q.LogicalExpression,operator:"||",left:a,right:this.logicalAND()};return a},logicalAND:function(){for(var a=this.equality();this.expect("&&");)a={type:q.LogicalExpression,operator:"&&",left:a,right:this.equality()};return a},equality:function(){for(var a=this.relational(),c;c=this.expect("==","!=","===","!==");)a={type:q.BinaryExpression, operator:c.text,left:a,right:this.relational()};return a},relational:function(){for(var a=this.additive(),c;c=this.expect("<",">","<=",">=");)a={type:q.BinaryExpression,operator:c.text,left:a,right:this.additive()};return a},additive:function(){for(var a=this.multiplicative(),c;c=this.expect("+","-");)a={type:q.BinaryExpression,operator:c.text,left:a,right:this.multiplicative()};return a},multiplicative:function(){for(var a=this.unary(),c;c=this.expect("*","/","%");)a={type:q.BinaryExpression,operator:c.text, left:a,right:this.unary()};return a},unary:function(){var a;return(a=this.expect("+","-","!"))?{type:q.UnaryExpression,operator:a.text,prefix:!0,argument:this.unary()}:this.primary()},primary:function(){var a;this.expect("(")?(a=this.filterChain(),this.consume(")")):this.expect("[")?a=this.arrayDeclaration():this.expect("{")?a=this.object():this.constants.hasOwnProperty(this.peek().text)?a=fa(this.constants[this.consume().text]):this.peek().identifier?a=this.identifier():this.peek().constant?a=this.constant(): this.throwError("not a primary expression",this.peek());for(var c;c=this.expect("(","[",".");)"("===c.text?(a={type:q.CallExpression,callee:a,arguments:this.parseArguments()},this.consume(")")):"["===c.text?(a={type:q.MemberExpression,object:a,property:this.expression(),computed:!0},this.consume("]")):"."===c.text?a={type:q.MemberExpression,object:a,property:this.identifier(),computed:!1}:this.throwError("IMPOSSIBLE");return a},filter:function(a){a=[a];for(var c={type:q.CallExpression,callee:this.identifier(), arguments:a,filter:!0};this.expect(":");)a.push(this.expression());return c},parseArguments:function(){var a=[];if(")"!==this.peekToken().text){do a.push(this.expression());while(this.expect(","))}return a},identifier:function(){var a=this.consume();a.identifier||this.throwError("is not a valid identifier",a);return{type:q.Identifier,name:a.text}},constant:function(){return{type:q.Literal,value:this.consume().value}},arrayDeclaration:function(){var a=[];if("]"!==this.peekToken().text){do{if(this.peek("]"))break; a.push(this.expression())}while(this.expect(","))}this.consume("]");return{type:q.ArrayExpression,elements:a}},object:function(){var a=[],c;if("}"!==this.peekToken().text){do{if(this.peek("}"))break;c={type:q.Property,kind:"init"};this.peek().constant?c.key=this.constant():this.peek().identifier?c.key=this.identifier():this.throwError("invalid key",this.peek());this.consume(":");c.value=this.expression();a.push(c)}while(this.expect(","))}this.consume("}");return{type:q.ObjectExpression,properties:a}}, throwError:function(a,c){throw da("syntax",c.text,a,c.index+1,this.text,this.text.substring(c.index));},consume:function(a){if(0===this.tokens.length)throw da("ueoe",this.text);var c=this.expect(a);c||this.throwError("is unexpected, expecting ["+a+"]",this.peek());return c},peekToken:function(){if(0===this.tokens.length)throw da("ueoe",this.text);return this.tokens[0]},peek:function(a,c,d,e){return this.peekAhead(0,a,c,d,e)},peekAhead:function(a,c,d,e,f){if(this.tokens.length>a){a=this.tokens[a]; var g=a.text;if(g===c||g===d||g===e||g===f||!(c||d||e||f))return a}return!1},expect:function(a,c,d,e){return(a=this.peek(a,c,d,e))?(this.tokens.shift(),a):!1},constants:{"true":{type:q.Literal,value:!0},"false":{type:q.Literal,value:!1},"null":{type:q.Literal,value:null},undefined:{type:q.Literal,value:t},"this":{type:q.ThisExpression}}};rd.prototype={compile:function(a,c){var d=this,e=this.astBuilder.ast(a);this.state={nextId:0,filters:{},expensiveChecks:c,fn:{vars:[],body:[],own:{}},assign:{vars:[], body:[],own:{}},inputs:[]};T(e,d.$filter);var f="",g;this.stage="assign";if(g=pd(e))this.state.computing="assign",f=this.nextId(),this.recurse(g,f),f="fn.assign="+this.generateFunction("assign","s,v,l");g=nd(e.body);d.stage="inputs";m(g,function(a,c){var e="fn"+c;d.state[e]={vars:[],body:[],own:{}};d.state.computing=e;var f=d.nextId();d.recurse(a,f);d.return_(f);d.state.inputs.push(e);a.watchId=c});this.state.computing="fn";this.stage="main";this.recurse(e);f='"'+this.USE+" "+this.STRICT+'";\n'+this.filterPrefix()+ "var fn="+this.generateFunction("fn","s,l,a,i")+f+this.watchFns()+"return fn;";f=(new Function("$filter","ensureSafeMemberName","ensureSafeObject","ensureSafeFunction","ifDefined","plus","text",f))(this.$filter,Ca,oa,ld,Yf,md,a);this.state=this.stage=t;f.literal=qd(e);f.constant=e.constant;return f},USE:"use",STRICT:"strict",watchFns:function(){var a=[],c=this.state.inputs,d=this;m(c,function(c){a.push("var "+c+"="+d.generateFunction(c,"s"))});c.length&&a.push("fn.inputs=["+c.join(",")+"];");return a.join("")}, generateFunction:function(a,c){return"function("+c+"){"+this.varsPrefix(a)+this.body(a)+"};"},filterPrefix:function(){var a=[],c=this;m(this.state.filters,function(d,e){a.push(d+"=$filter("+c.escape(e)+")")});return a.length?"var "+a.join(",")+";":""},varsPrefix:function(a){return this.state[a].vars.length?"var "+this.state[a].vars.join(",")+";":""},body:function(a){return this.state[a].body.join("")},recurse:function(a,c,d,e,f,g){var h,l,k=this,n,r;e=e||v;if(!g&&w(a.watchId))c=c||this.nextId(),this.if_("i", this.lazyAssign(c,this.computedMember("i",a.watchId)),this.lazyRecurse(a,c,d,e,f,!0));else switch(a.type){case q.Program:m(a.body,function(c,d){k.recurse(c.expression,t,t,function(a){l=a});d!==a.body.length-1?k.current().body.push(l,";"):k.return_(l)});break;case q.Literal:r=this.escape(a.value);this.assign(c,r);e(r);break;case q.UnaryExpression:this.recurse(a.argument,t,t,function(a){l=a});r=a.operator+"("+this.ifDefined(l,0)+")";this.assign(c,r);e(r);break;case q.BinaryExpression:this.recurse(a.left, t,t,function(a){h=a});this.recurse(a.right,t,t,function(a){l=a});r="+"===a.operator?this.plus(h,l):"-"===a.operator?this.ifDefined(h,0)+a.operator+this.ifDefined(l,0):"("+h+")"+a.operator+"("+l+")";this.assign(c,r);e(r);break;case q.LogicalExpression:c=c||this.nextId();k.recurse(a.left,c);k.if_("&&"===a.operator?c:k.not(c),k.lazyRecurse(a.right,c));e(c);break;case q.ConditionalExpression:c=c||this.nextId();k.recurse(a.test,c);k.if_(c,k.lazyRecurse(a.alternate,c),k.lazyRecurse(a.consequent,c));e(c); break;case q.Identifier:c=c||this.nextId();d&&(d.context="inputs"===k.stage?"s":this.assign(this.nextId(),this.getHasOwnProperty("l",a.name)+"?l:s"),d.computed=!1,d.name=a.name);Ca(a.name);k.if_("inputs"===k.stage||k.not(k.getHasOwnProperty("l",a.name)),function(){k.if_("inputs"===k.stage||"s",function(){f&&1!==f&&k.if_(k.not(k.nonComputedMember("s",a.name)),k.lazyAssign(k.nonComputedMember("s",a.name),"{}"));k.assign(c,k.nonComputedMember("s",a.name))})},c&&k.lazyAssign(c,k.nonComputedMember("l", a.name)));(k.state.expensiveChecks||Fb(a.name))&&k.addEnsureSafeObject(c);e(c);break;case q.MemberExpression:h=d&&(d.context=this.nextId())||this.nextId();c=c||this.nextId();k.recurse(a.object,h,t,function(){k.if_(k.notNull(h),function(){if(a.computed)l=k.nextId(),k.recurse(a.property,l),k.addEnsureSafeMemberName(l),f&&1!==f&&k.if_(k.not(k.computedMember(h,l)),k.lazyAssign(k.computedMember(h,l),"{}")),r=k.ensureSafeObject(k.computedMember(h,l)),k.assign(c,r),d&&(d.computed=!0,d.name=l);else{Ca(a.property.name); f&&1!==f&&k.if_(k.not(k.nonComputedMember(h,a.property.name)),k.lazyAssign(k.nonComputedMember(h,a.property.name),"{}"));r=k.nonComputedMember(h,a.property.name);if(k.state.expensiveChecks||Fb(a.property.name))r=k.ensureSafeObject(r);k.assign(c,r);d&&(d.computed=!1,d.name=a.property.name)}},function(){k.assign(c,"undefined")});e(c)},!!f);break;case q.CallExpression:c=c||this.nextId();a.filter?(l=k.filter(a.callee.name),n=[],m(a.arguments,function(a){var c=k.nextId();k.recurse(a,c);n.push(c)}),r=l+ "("+n.join(",")+")",k.assign(c,r),e(c)):(l=k.nextId(),h={},n=[],k.recurse(a.callee,l,h,function(){k.if_(k.notNull(l),function(){k.addEnsureSafeFunction(l);m(a.arguments,function(a){k.recurse(a,k.nextId(),t,function(a){n.push(k.ensureSafeObject(a))})});h.name?(k.state.expensiveChecks||k.addEnsureSafeObject(h.context),r=k.member(h.context,h.name,h.computed)+"("+n.join(",")+")"):r=l+"("+n.join(",")+")";r=k.ensureSafeObject(r);k.assign(c,r)},function(){k.assign(c,"undefined")});e(c)}));break;case q.AssignmentExpression:l= this.nextId();h={};if(!od(a.left))throw da("lval");this.recurse(a.left,t,h,function(){k.if_(k.notNull(h.context),function(){k.recurse(a.right,l);k.addEnsureSafeObject(k.member(h.context,h.name,h.computed));r=k.member(h.context,h.name,h.computed)+a.operator+l;k.assign(c,r);e(c||r)})},1);break;case q.ArrayExpression:n=[];m(a.elements,function(a){k.recurse(a,k.nextId(),t,function(a){n.push(a)})});r="["+n.join(",")+"]";this.assign(c,r);e(r);break;case q.ObjectExpression:n=[];m(a.properties,function(a){k.recurse(a.value, k.nextId(),t,function(c){n.push(k.escape(a.key.type===q.Identifier?a.key.name:""+a.key.value)+":"+c)})});r="{"+n.join(",")+"}";this.assign(c,r);e(r);break;case q.ThisExpression:this.assign(c,"s");e("s");break;case q.NGValueParameter:this.assign(c,"v"),e("v")}},getHasOwnProperty:function(a,c){var d=a+"."+c,e=this.current().own;e.hasOwnProperty(d)||(e[d]=this.nextId(!1,a+"&&("+this.escape(c)+" in "+a+")"));return e[d]},assign:function(a,c){if(a)return this.current().body.push(a,"=",c,";"),a},filter:function(a){this.state.filters.hasOwnProperty(a)|| (this.state.filters[a]=this.nextId(!0));return this.state.filters[a]},ifDefined:function(a,c){return"ifDefined("+a+","+this.escape(c)+")"},plus:function(a,c){return"plus("+a+","+c+")"},return_:function(a){this.current().body.push("return ",a,";")},if_:function(a,c,d){if(!0===a)c();else{var e=this.current().body;e.push("if(",a,"){");c();e.push("}");d&&(e.push("else{"),d(),e.push("}"))}},not:function(a){return"!("+a+")"},notNull:function(a){return a+"!=null"},nonComputedMember:function(a,c){return a+ "."+c},computedMember:function(a,c){return a+"["+c+"]"},member:function(a,c,d){return d?this.computedMember(a,c):this.nonComputedMember(a,c)},addEnsureSafeObject:function(a){this.current().body.push(this.ensureSafeObject(a),";")},addEnsureSafeMemberName:function(a){this.current().body.push(this.ensureSafeMemberName(a),";")},addEnsureSafeFunction:function(a){this.current().body.push(this.ensureSafeFunction(a),";")},ensureSafeObject:function(a){return"ensureSafeObject("+a+",text)"},ensureSafeMemberName:function(a){return"ensureSafeMemberName("+ a+",text)"},ensureSafeFunction:function(a){return"ensureSafeFunction("+a+",text)"},lazyRecurse:function(a,c,d,e,f,g){var h=this;return function(){h.recurse(a,c,d,e,f,g)}},lazyAssign:function(a,c){var d=this;return function(){d.assign(a,c)}},stringEscapeRegex:/[^ a-zA-Z0-9]/g,stringEscapeFn:function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)},escape:function(a){if(L(a))return"'"+a.replace(this.stringEscapeRegex,this.stringEscapeFn)+"'";if(V(a))return a.toString();if(!0===a)return"true"; if(!1===a)return"false";if(null===a)return"null";if("undefined"===typeof a)return"undefined";throw da("esc");},nextId:function(a,c){var d="v"+this.state.nextId++;a||this.current().vars.push(d+(c?"="+c:""));return d},current:function(){return this.state[this.state.computing]}};sd.prototype={compile:function(a,c){var d=this,e=this.astBuilder.ast(a);this.expression=a;this.expensiveChecks=c;T(e,d.$filter);var f,g;if(f=pd(e))g=this.recurse(f);f=nd(e.body);var h;f&&(h=[],m(f,function(a,c){var e=d.recurse(a); a.input=e;h.push(e);a.watchId=c}));var l=[];m(e.body,function(a){l.push(d.recurse(a.expression))});f=0===e.body.length?function(){}:1===e.body.length?l[0]:function(a,c){var d;m(l,function(e){d=e(a,c)});return d};g&&(f.assign=function(a,c,d){return g(a,d,c)});h&&(f.inputs=h);f.literal=qd(e);f.constant=e.constant;return f},recurse:function(a,c,d){var e,f,g=this,h;if(a.input)return this.inputs(a.input,a.watchId);switch(a.type){case q.Literal:return this.value(a.value,c);case q.UnaryExpression:return f= this.recurse(a.argument),this["unary"+a.operator](f,c);case q.BinaryExpression:return e=this.recurse(a.left),f=this.recurse(a.right),this["binary"+a.operator](e,f,c);case q.LogicalExpression:return e=this.recurse(a.left),f=this.recurse(a.right),this["binary"+a.operator](e,f,c);case q.ConditionalExpression:return this["ternary?:"](this.recurse(a.test),this.recurse(a.alternate),this.recurse(a.consequent),c);case q.Identifier:return Ca(a.name,g.expression),g.identifier(a.name,g.expensiveChecks||Fb(a.name), c,d,g.expression);case q.MemberExpression:return e=this.recurse(a.object,!1,!!d),a.computed||(Ca(a.property.name,g.expression),f=a.property.name),a.computed&&(f=this.recurse(a.property)),a.computed?this.computedMember(e,f,c,d,g.expression):this.nonComputedMember(e,f,g.expensiveChecks,c,d,g.expression);case q.CallExpression:return h=[],m(a.arguments,function(a){h.push(g.recurse(a))}),a.filter&&(f=this.$filter(a.callee.name)),a.filter||(f=this.recurse(a.callee,!0)),a.filter?function(a,d,e,g){for(var m= [],q=0;q<h.length;++q)m.push(h[q](a,d,e,g));a=f.apply(t,m,g);return c?{context:t,name:t,value:a}:a}:function(a,d,e,r){var m=f(a,d,e,r),q;if(null!=m.value){oa(m.context,g.expression);ld(m.value,g.expression);q=[];for(var t=0;t<h.length;++t)q.push(oa(h[t](a,d,e,r),g.expression));q=oa(m.value.apply(m.context,q),g.expression)}return c?{value:q}:q};case q.AssignmentExpression:return e=this.recurse(a.left,!0,1),f=this.recurse(a.right),function(a,d,h,r){var m=e(a,d,h,r);a=f(a,d,h,r);oa(m.value,g.expression); m.context[m.name]=a;return c?{value:a}:a};case q.ArrayExpression:return h=[],m(a.elements,function(a){h.push(g.recurse(a))}),function(a,d,e,f){for(var g=[],m=0;m<h.length;++m)g.push(h[m](a,d,e,f));return c?{value:g}:g};case q.ObjectExpression:return h=[],m(a.properties,function(a){h.push({key:a.key.type===q.Identifier?a.key.name:""+a.key.value,value:g.recurse(a.value)})}),function(a,d,e,f){for(var g={},m=0;m<h.length;++m)g[h[m].key]=h[m].value(a,d,e,f);return c?{value:g}:g};case q.ThisExpression:return function(a){return c? {value:a}:a};case q.NGValueParameter:return function(a,d,e,f){return c?{value:e}:e}}},"unary+":function(a,c){return function(d,e,f,g){d=a(d,e,f,g);d=w(d)?+d:0;return c?{value:d}:d}},"unary-":function(a,c){return function(d,e,f,g){d=a(d,e,f,g);d=w(d)?-d:0;return c?{value:d}:d}},"unary!":function(a,c){return function(d,e,f,g){d=!a(d,e,f,g);return c?{value:d}:d}},"binary+":function(a,c,d){return function(e,f,g,h){var l=a(e,f,g,h);e=c(e,f,g,h);l=md(l,e);return d?{value:l}:l}},"binary-":function(a,c,d){return function(e, f,g,h){var l=a(e,f,g,h);e=c(e,f,g,h);l=(w(l)?l:0)-(w(e)?e:0);return d?{value:l}:l}},"binary*":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)*c(e,f,g,h);return d?{value:e}:e}},"binary/":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)/c(e,f,g,h);return d?{value:e}:e}},"binary%":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)%c(e,f,g,h);return d?{value:e}:e}},"binary===":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)===c(e,f,g,h);return d?{value:e}:e}},"binary!==":function(a, c,d){return function(e,f,g,h){e=a(e,f,g,h)!==c(e,f,g,h);return d?{value:e}:e}},"binary==":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)==c(e,f,g,h);return d?{value:e}:e}},"binary!=":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)!=c(e,f,g,h);return d?{value:e}:e}},"binary<":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)<c(e,f,g,h);return d?{value:e}:e}},"binary>":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)>c(e,f,g,h);return d?{value:e}:e}},"binary<=":function(a,c,d){return function(e, f,g,h){e=a(e,f,g,h)<=c(e,f,g,h);return d?{value:e}:e}},"binary>=":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)>=c(e,f,g,h);return d?{value:e}:e}},"binary&&":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)&&c(e,f,g,h);return d?{value:e}:e}},"binary||":function(a,c,d){return function(e,f,g,h){e=a(e,f,g,h)||c(e,f,g,h);return d?{value:e}:e}},"ternary?:":function(a,c,d,e){return function(f,g,h,l){f=a(f,g,h,l)?c(f,g,h,l):d(f,g,h,l);return e?{value:f}:f}},value:function(a,c){return function(){return c? {context:t,name:t,value:a}:a}},identifier:function(a,c,d,e,f){return function(g,h,l,k){g=h&&a in h?h:g;e&&1!==e&&g&&!g[a]&&(g[a]={});h=g?g[a]:t;c&&oa(h,f);return d?{context:g,name:a,value:h}:h}},computedMember:function(a,c,d,e,f){return function(g,h,l,k){var n=a(g,h,l,k),m,s;null!=n&&(m=c(g,h,l,k),Ca(m,f),e&&1!==e&&n&&!n[m]&&(n[m]={}),s=n[m],oa(s,f));return d?{context:n,name:m,value:s}:s}},nonComputedMember:function(a,c,d,e,f,g){return function(h,l,k,n){h=a(h,l,k,n);f&&1!==f&&h&&!h[c]&&(h[c]={}); l=null!=h?h[c]:t;(d||Fb(c))&&oa(l,g);return e?{context:h,name:c,value:l}:l}},inputs:function(a,c){return function(d,e,f,g){return g?g[c]:a(d,e,f)}}};var hc=function(a,c,d){this.lexer=a;this.$filter=c;this.options=d;this.ast=new q(this.lexer);this.astCompiler=d.csp?new sd(this.ast,c):new rd(this.ast,c)};hc.prototype={constructor:hc,parse:function(a){return this.astCompiler.compile(a,this.options.expensiveChecks)}};ga();ga();var Zf=Object.prototype.valueOf,Da=J("$sce"),pa={HTML:"html",CSS:"css",URL:"url", RESOURCE_URL:"resourceUrl",JS:"js"},ea=J("$compile"),X=U.createElement("a"),wd=Ba(O.location.href);xd.$inject=["$document"];Lc.$inject=["$provide"];yd.$inject=["$locale"];Ad.$inject=["$locale"];var Dd=".",ig={yyyy:Y("FullYear",4),yy:Y("FullYear",2,0,!0),y:Y("FullYear",1),MMMM:Hb("Month"),MMM:Hb("Month",!0),MM:Y("Month",2,1),M:Y("Month",1,1),dd:Y("Date",2),d:Y("Date",1),HH:Y("Hours",2),H:Y("Hours",1),hh:Y("Hours",2,-12),h:Y("Hours",1,-12),mm:Y("Minutes",2),m:Y("Minutes",1),ss:Y("Seconds",2),s:Y("Seconds", 1),sss:Y("Milliseconds",3),EEEE:Hb("Day"),EEE:Hb("Day",!0),a:function(a,c){return 12>a.getHours()?c.AMPMS[0]:c.AMPMS[1]},Z:function(a,c,d){a=-1*d;return a=(0<=a?"+":"")+(Gb(Math[0<a?"floor":"ceil"](a/60),2)+Gb(Math.abs(a%60),2))},ww:Fd(2),w:Fd(1),G:jc,GG:jc,GGG:jc,GGGG:function(a,c){return 0>=a.getFullYear()?c.ERANAMES[0]:c.ERANAMES[1]}},hg=/((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,gg=/^\-?\d+$/;zd.$inject=["$locale"];var dg=ra(M),eg=ra(rb);Bd.$inject= ["$parse"];var ie=ra({restrict:"E",compile:function(a,c){if(!c.href&&!c.xlinkHref)return function(a,c){if("a"===c[0].nodeName.toLowerCase()){var f="[object SVGAnimatedString]"===sa.call(c.prop("href"))?"xlink:href":"href";c.on("click",function(a){c.attr(f)||a.preventDefault()})}}}}),sb={};m(Ab,function(a,c){function d(a,d,f){a.$watch(f[e],function(a){f.$set(c,!!a)})}if("multiple"!=a){var e=wa("ng-"+c),f=d;"checked"===a&&(f=function(a,c,f){f.ngModel!==f[e]&&d(a,c,f)});sb[e]=function(){return{restrict:"A", priority:100,link:f}}}});m(Uc,function(a,c){sb[c]=function(){return{priority:100,link:function(a,e,f){if("ngPattern"===c&&"/"==f.ngPattern.charAt(0)&&(e=f.ngPattern.match(kg))){f.$set("ngPattern",new RegExp(e[1],e[2]));return}a.$watch(f[c],function(a){f.$set(c,a)})}}}});m(["src","srcset","href"],function(a){var c=wa("ng-"+a);sb[c]=function(){return{priority:99,link:function(d,e,f){var g=a,h=a;"href"===a&&"[object SVGAnimatedString]"===sa.call(e.prop("href"))&&(h="xlinkHref",f.$attr[h]="xlink:href", g=null);f.$observe(c,function(c){c?(f.$set(h,c),Ua&&g&&e.prop(g,f[h])):"href"===a&&f.$set(h,null)})}}}});var Ib={$addControl:v,$$renameControl:function(a,c){a.$name=c},$removeControl:v,$setValidity:v,$setDirty:v,$setPristine:v,$setSubmitted:v};Gd.$inject=["$element","$attrs","$scope","$animate","$interpolate"];var Od=function(a){return["$timeout",function(c){return{name:"form",restrict:a?"EAC":"E",controller:Gd,compile:function(d,e){d.addClass(Va).addClass(mb);var f=e.name?"name":a&&e.ngForm?"ngForm": !1;return{pre:function(a,d,e,k){if(!("action"in e)){var n=function(c){a.$apply(function(){k.$commitViewValue();k.$setSubmitted()});c.preventDefault()};d[0].addEventListener("submit",n,!1);d.on("$destroy",function(){c(function(){d[0].removeEventListener("submit",n,!1)},0,!1)})}var m=k.$$parentForm;f&&(Eb(a,k.$name,k,k.$name),e.$observe(f,function(c){k.$name!==c&&(Eb(a,k.$name,t,k.$name),m.$$renameControl(k,c),Eb(a,k.$name,k,k.$name))}));d.on("$destroy",function(){m.$removeControl(k);f&&Eb(a,e[f],t, k.$name);P(k,Ib)})}}}}}]},je=Od(),we=Od(!0),jg=/\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/,sg=/^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/,tg=/^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i,ug=/^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/,Pd=/^(\d{4})-(\d{2})-(\d{2})$/,Qd=/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/,mc=/^(\d{4})-W(\d\d)$/,Rd=/^(\d{4})-(\d\d)$/, Sd=/^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/,Td={text:function(a,c,d,e,f,g){kb(a,c,d,e,f,g);kc(e)},date:lb("date",Pd,Kb(Pd,["yyyy","MM","dd"]),"yyyy-MM-dd"),"datetime-local":lb("datetimelocal",Qd,Kb(Qd,"yyyy MM dd HH mm ss sss".split(" ")),"yyyy-MM-ddTHH:mm:ss.sss"),time:lb("time",Sd,Kb(Sd,["HH","mm","ss","sss"]),"HH:mm:ss.sss"),week:lb("week",mc,function(a,c){if(aa(a))return a;if(L(a)){mc.lastIndex=0;var d=mc.exec(a);if(d){var e=+d[1],f=+d[2],g=d=0,h=0,l=0,k=Ed(e),f=7*(f-1);c&&(d=c.getHours(),g= c.getMinutes(),h=c.getSeconds(),l=c.getMilliseconds());return new Date(e,0,k.getDate()+f,d,g,h,l)}}return NaN},"yyyy-Www"),month:lb("month",Rd,Kb(Rd,["yyyy","MM"]),"yyyy-MM"),number:function(a,c,d,e,f,g){Id(a,c,d,e);kb(a,c,d,e,f,g);e.$$parserName="number";e.$parsers.push(function(a){return e.$isEmpty(a)?null:ug.test(a)?parseFloat(a):t});e.$formatters.push(function(a){if(!e.$isEmpty(a)){if(!V(a))throw Lb("numfmt",a);a=a.toString()}return a});if(w(d.min)||d.ngMin){var h;e.$validators.min=function(a){return e.$isEmpty(a)|| A(h)||a>=h};d.$observe("min",function(a){w(a)&&!V(a)&&(a=parseFloat(a,10));h=V(a)&&!isNaN(a)?a:t;e.$validate()})}if(w(d.max)||d.ngMax){var l;e.$validators.max=function(a){return e.$isEmpty(a)||A(l)||a<=l};d.$observe("max",function(a){w(a)&&!V(a)&&(a=parseFloat(a,10));l=V(a)&&!isNaN(a)?a:t;e.$validate()})}},url:function(a,c,d,e,f,g){kb(a,c,d,e,f,g);kc(e);e.$$parserName="url";e.$validators.url=function(a,c){var d=a||c;return e.$isEmpty(d)||sg.test(d)}},email:function(a,c,d,e,f,g){kb(a,c,d,e,f,g);kc(e); e.$$parserName="email";e.$validators.email=function(a,c){var d=a||c;return e.$isEmpty(d)||tg.test(d)}},radio:function(a,c,d,e){A(d.name)&&c.attr("name",++nb);c.on("click",function(a){c[0].checked&&e.$setViewValue(d.value,a&&a.type)});e.$render=function(){c[0].checked=d.value==e.$viewValue};d.$observe("value",e.$render)},checkbox:function(a,c,d,e,f,g,h,l){var k=Jd(l,a,"ngTrueValue",d.ngTrueValue,!0),n=Jd(l,a,"ngFalseValue",d.ngFalseValue,!1);c.on("click",function(a){e.$setViewValue(c[0].checked,a&& a.type)});e.$render=function(){c[0].checked=e.$viewValue};e.$isEmpty=function(a){return!1===a};e.$formatters.push(function(a){return ka(a,k)});e.$parsers.push(function(a){return a?k:n})},hidden:v,button:v,submit:v,reset:v,file:v},Fc=["$browser","$sniffer","$filter","$parse",function(a,c,d,e){return{restrict:"E",require:["?ngModel"],link:{pre:function(f,g,h,l){l[0]&&(Td[M(h.type)]||Td.text)(f,g,h,l[0],c,a,d,e)}}}}],vg=/^(true|false|\d+)$/,Oe=function(){return{restrict:"A",priority:100,compile:function(a, c){return vg.test(c.ngValue)?function(a,c,f){f.$set("value",a.$eval(f.ngValue))}:function(a,c,f){a.$watch(f.ngValue,function(a){f.$set("value",a)})}}}},oe=["$compile",function(a){return{restrict:"AC",compile:function(c){a.$$addBindingClass(c);return function(c,e,f){a.$$addBindingInfo(e,f.ngBind);e=e[0];c.$watch(f.ngBind,function(a){e.textContent=a===t?"":a})}}}}],qe=["$interpolate","$compile",function(a,c){return{compile:function(d){c.$$addBindingClass(d);return function(d,f,g){d=a(f.attr(g.$attr.ngBindTemplate)); c.$$addBindingInfo(f,d.expressions);f=f[0];g.$observe("ngBindTemplate",function(a){f.textContent=a===t?"":a})}}}}],pe=["$sce","$parse","$compile",function(a,c,d){return{restrict:"A",compile:function(e,f){var g=c(f.ngBindHtml),h=c(f.ngBindHtml,function(a){return(a||"").toString()});d.$$addBindingClass(e);return function(c,e,f){d.$$addBindingInfo(e,f.ngBindHtml);c.$watch(h,function(){e.html(a.getTrustedHtml(g(c))||"")})}}}}],Ne=ra({restrict:"A",require:"ngModel",link:function(a,c,d,e){e.$viewChangeListeners.push(function(){a.$eval(d.ngChange)})}}), re=lc("",!0),te=lc("Odd",0),se=lc("Even",1),ue=Ma({compile:function(a,c){c.$set("ngCloak",t);a.removeClass("ng-cloak")}}),ve=[function(){return{restrict:"A",scope:!0,controller:"@",priority:500}}],Kc={},wg={blur:!0,focus:!0};m("click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste".split(" "),function(a){var c=wa("ng-"+a);Kc[c]=["$parse","$rootScope",function(d,e){return{restrict:"A",compile:function(f,g){var h= d(g[c],null,!0);return function(c,d){d.on(a,function(d){var f=function(){h(c,{$event:d})};wg[a]&&e.$$phase?c.$evalAsync(f):c.$apply(f)})}}}}]});var ye=["$animate",function(a){return{multiElement:!0,transclude:"element",priority:600,terminal:!0,restrict:"A",$$tlb:!0,link:function(c,d,e,f,g){var h,l,k;c.$watch(e.ngIf,function(c){c?l||g(function(c,f){l=f;c[c.length++]=U.createComment(" end ngIf: "+e.ngIf+" ");h={clone:c};a.enter(c,d.parent(),d)}):(k&&(k.remove(),k=null),l&&(l.$destroy(),l=null),h&&(k= qb(h.clone),a.leave(k).then(function(){k=null}),h=null))})}}}],ze=["$templateRequest","$anchorScroll","$animate",function(a,c,d){return{restrict:"ECA",priority:400,terminal:!0,transclude:"element",controller:ca.noop,compile:function(e,f){var g=f.ngInclude||f.src,h=f.onload||"",l=f.autoscroll;return function(e,f,m,s,q){var t=0,F,u,p,v=function(){u&&(u.remove(),u=null);F&&(F.$destroy(),F=null);p&&(d.leave(p).then(function(){u=null}),u=p,p=null)};e.$watch(g,function(g){var m=function(){!w(l)||l&&!e.$eval(l)|| c()},r=++t;g?(a(g,!0).then(function(a){if(r===t){var c=e.$new();s.template=a;a=q(c,function(a){v();d.enter(a,null,f).then(m)});F=c;p=a;F.$emit("$includeContentLoaded",g);e.$eval(h)}},function(){r===t&&(v(),e.$emit("$includeContentError",g))}),e.$emit("$includeContentRequested",g)):(v(),s.template=null)})}}}}],Qe=["$compile",function(a){return{restrict:"ECA",priority:-400,require:"ngInclude",link:function(c,d,e,f){/SVG/.test(d[0].toString())?(d.empty(),a(Nc(f.template,U).childNodes)(c,function(a){d.append(a)}, {futureParentElement:d})):(d.html(f.template),a(d.contents())(c))}}}],Ae=Ma({priority:450,compile:function(){return{pre:function(a,c,d){a.$eval(d.ngInit)}}}}),Me=function(){return{restrict:"A",priority:100,require:"ngModel",link:function(a,c,d,e){var f=c.attr(d.$attr.ngList)||", ",g="false"!==d.ngTrim,h=g?R(f):f;e.$parsers.push(function(a){if(!A(a)){var c=[];a&&m(a.split(h),function(a){a&&c.push(g?R(a):a)});return c}});e.$formatters.push(function(a){return G(a)?a.join(f):t});e.$isEmpty=function(a){return!a|| !a.length}}}},mb="ng-valid",Kd="ng-invalid",Va="ng-pristine",Jb="ng-dirty",Md="ng-pending",Lb=new J("ngModel"),xg=["$scope","$exceptionHandler","$attrs","$element","$parse","$animate","$timeout","$rootScope","$q","$interpolate",function(a,c,d,e,f,g,h,l,k,n){this.$modelValue=this.$viewValue=Number.NaN;this.$$rawModelValue=t;this.$validators={};this.$asyncValidators={};this.$parsers=[];this.$formatters=[];this.$viewChangeListeners=[];this.$untouched=!0;this.$touched=!1;this.$pristine=!0;this.$dirty= !1;this.$valid=!0;this.$invalid=!1;this.$error={};this.$$success={};this.$pending=t;this.$name=n(d.name||"",!1)(a);var r=f(d.ngModel),s=r.assign,q=r,C=s,F=null,u,p=this;this.$$setOptions=function(a){if((p.$options=a)&&a.getterSetter){var c=f(d.ngModel+"()"),g=f(d.ngModel+"($$$p)");q=function(a){var d=r(a);z(d)&&(d=c(a));return d};C=function(a,c){z(r(a))?g(a,{$$$p:p.$modelValue}):s(a,p.$modelValue)}}else if(!r.assign)throw Lb("nonassign",d.ngModel,ua(e));};this.$render=v;this.$isEmpty=function(a){return A(a)|| ""===a||null===a||a!==a};var K=e.inheritedData("$formController")||Ib,y=0;Hd({ctrl:this,$element:e,set:function(a,c){a[c]=!0},unset:function(a,c){delete a[c]},parentForm:K,$animate:g});this.$setPristine=function(){p.$dirty=!1;p.$pristine=!0;g.removeClass(e,Jb);g.addClass(e,Va)};this.$setDirty=function(){p.$dirty=!0;p.$pristine=!1;g.removeClass(e,Va);g.addClass(e,Jb);K.$setDirty()};this.$setUntouched=function(){p.$touched=!1;p.$untouched=!0;g.setClass(e,"ng-untouched","ng-touched")};this.$setTouched= function(){p.$touched=!0;p.$untouched=!1;g.setClass(e,"ng-touched","ng-untouched")};this.$rollbackViewValue=function(){h.cancel(F);p.$viewValue=p.$$lastCommittedViewValue;p.$render()};this.$validate=function(){if(!V(p.$modelValue)||!isNaN(p.$modelValue)){var a=p.$$rawModelValue,c=p.$valid,d=p.$modelValue,e=p.$options&&p.$options.allowInvalid;p.$$runValidators(a,p.$$lastCommittedViewValue,function(f){e||c===f||(p.$modelValue=f?a:t,p.$modelValue!==d&&p.$$writeModelToScope())})}};this.$$runValidators= function(a,c,d){function e(){var d=!0;m(p.$validators,function(e,f){var h=e(a,c);d=d&&h;g(f,h)});return d?!0:(m(p.$asyncValidators,function(a,c){g(c,null)}),!1)}function f(){var d=[],e=!0;m(p.$asyncValidators,function(f,h){var k=f(a,c);if(!k||!z(k.then))throw Lb("$asyncValidators",k);g(h,t);d.push(k.then(function(){g(h,!0)},function(a){e=!1;g(h,!1)}))});d.length?k.all(d).then(function(){h(e)},v):h(!0)}function g(a,c){l===y&&p.$setValidity(a,c)}function h(a){l===y&&d(a)}y++;var l=y;(function(){var a= p.$$parserName||"parse";if(u===t)g(a,null);else return u||(m(p.$validators,function(a,c){g(c,null)}),m(p.$asyncValidators,function(a,c){g(c,null)})),g(a,u),u;return!0})()?e()?f():h(!1):h(!1)};this.$commitViewValue=function(){var a=p.$viewValue;h.cancel(F);if(p.$$lastCommittedViewValue!==a||""===a&&p.$$hasNativeValidators)p.$$lastCommittedViewValue=a,p.$pristine&&this.$setDirty(),this.$$parseAndValidate()};this.$$parseAndValidate=function(){var c=p.$$lastCommittedViewValue;if(u=A(c)?t:!0)for(var d= 0;d<p.$parsers.length;d++)if(c=p.$parsers[d](c),A(c)){u=!1;break}V(p.$modelValue)&&isNaN(p.$modelValue)&&(p.$modelValue=q(a));var e=p.$modelValue,f=p.$options&&p.$options.allowInvalid;p.$$rawModelValue=c;f&&(p.$modelValue=c,p.$modelValue!==e&&p.$$writeModelToScope());p.$$runValidators(c,p.$$lastCommittedViewValue,function(a){f||(p.$modelValue=a?c:t,p.$modelValue!==e&&p.$$writeModelToScope())})};this.$$writeModelToScope=function(){C(a,p.$modelValue);m(p.$viewChangeListeners,function(a){try{a()}catch(d){c(d)}})}; this.$setViewValue=function(a,c){p.$viewValue=a;p.$options&&!p.$options.updateOnDefault||p.$$debounceViewValueCommit(c)};this.$$debounceViewValueCommit=function(c){var d=0,e=p.$options;e&&w(e.debounce)&&(e=e.debounce,V(e)?d=e:V(e[c])?d=e[c]:V(e["default"])&&(d=e["default"]));h.cancel(F);d?F=h(function(){p.$commitViewValue()},d):l.$$phase?p.$commitViewValue():a.$apply(function(){p.$commitViewValue()})};a.$watch(function(){var c=q(a);if(c!==p.$modelValue&&(p.$modelValue===p.$modelValue||c===c)){p.$modelValue= p.$$rawModelValue=c;u=t;for(var d=p.$formatters,e=d.length,f=c;e--;)f=d[e](f);p.$viewValue!==f&&(p.$viewValue=p.$$lastCommittedViewValue=f,p.$render(),p.$$runValidators(c,f,v))}return c})}],Le=["$rootScope",function(a){return{restrict:"A",require:["ngModel","^?form","^?ngModelOptions"],controller:xg,priority:1,compile:function(c){c.addClass(Va).addClass("ng-untouched").addClass(mb);return{pre:function(a,c,f,g){var h=g[0],l=g[1]||Ib;h.$$setOptions(g[2]&&g[2].$options);l.$addControl(h);f.$observe("name", function(a){h.$name!==a&&l.$$renameControl(h,a)});a.$on("$destroy",function(){l.$removeControl(h)})},post:function(c,e,f,g){var h=g[0];if(h.$options&&h.$options.updateOn)e.on(h.$options.updateOn,function(a){h.$$debounceViewValueCommit(a&&a.type)});e.on("blur",function(e){h.$touched||(a.$$phase?c.$evalAsync(h.$setTouched):c.$apply(h.$setTouched))})}}}}}],yg=/(\s+|^)default(\s+|$)/,Pe=function(){return{restrict:"A",controller:["$scope","$attrs",function(a,c){var d=this;this.$options=fa(a.$eval(c.ngModelOptions)); this.$options.updateOn!==t?(this.$options.updateOnDefault=!1,this.$options.updateOn=R(this.$options.updateOn.replace(yg,function(){d.$options.updateOnDefault=!0;return" "}))):this.$options.updateOnDefault=!0}]}},Be=Ma({terminal:!0,priority:1E3}),zg=J("ngOptions"),Ag=/^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\s+when\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/, Je=["$compile","$parse",function(a,c){function d(a,d,e){function f(a,c,d,e,g){this.selectValue=a;this.viewValue=c;this.label=d;this.group=e;this.disabled=g}function n(a){var c;if(!q&&Ea(a))c=a;else{c=[];for(var d in a)a.hasOwnProperty(d)&&"$"!==d.charAt(0)&&c.push(d)}return c}var m=a.match(Ag);if(!m)throw zg("iexp",a,ua(d));var s=m[5]||m[7],q=m[6];a=/ as /.test(m[0])&&m[1];var t=m[9];d=c(m[2]?m[1]:s);var v=a&&c(a)||d,u=t&&c(t),p=t?function(a,c){return u(e,c)}:function(a){return Ga(a)},w=function(a, c){return p(a,z(a,c))},y=c(m[2]||m[1]),A=c(m[3]||""),B=c(m[4]||""),N=c(m[8]),D={},z=q?function(a,c){D[q]=c;D[s]=a;return D}:function(a){D[s]=a;return D};return{trackBy:t,getTrackByValue:w,getWatchables:c(N,function(a){var c=[];a=a||[];for(var d=n(a),f=d.length,g=0;g<f;g++){var h=a===d?g:d[g],k=z(a[h],h),h=p(a[h],k);c.push(h);if(m[2]||m[1])h=y(e,k),c.push(h);m[4]&&(k=B(e,k),c.push(k))}return c}),getOptions:function(){for(var a=[],c={},d=N(e)||[],g=n(d),h=g.length,m=0;m<h;m++){var r=d===g?m:g[m],s= z(d[r],r),q=v(e,s),r=p(q,s),u=y(e,s),x=A(e,s),s=B(e,s),q=new f(r,q,u,x,s);a.push(q);c[r]=q}return{items:a,selectValueMap:c,getOptionFromViewValue:function(a){return c[w(a)]},getViewValueFromOption:function(a){return t?ca.copy(a.viewValue):a.viewValue}}}}}var e=U.createElement("option"),f=U.createElement("optgroup");return{restrict:"A",terminal:!0,require:["select","?ngModel"],link:function(c,h,l,k){function n(a,c){a.element=c;c.disabled=a.disabled;a.value!==c.value&&(c.value=a.selectValue);a.label!== c.label&&(c.label=a.label,c.textContent=a.label)}function r(a,c,d,e){c&&M(c.nodeName)===d?d=c:(d=e.cloneNode(!1),c?a.insertBefore(d,c):a.appendChild(d));return d}function s(a){for(var c;a;)c=a.nextSibling,Xb(a),a=c}function q(a){var c=p&&p[0],d=N&&N[0];if(c||d)for(;a&&(a===c||a===d);)a=a.nextSibling;return a}function t(){var a=D&&u.readValue();D=z.getOptions();var c={},d=h[0].firstChild;B&&h.prepend(p);d=q(d);D.items.forEach(function(a){var g,k;a.group?(g=c[a.group],g||(g=r(h[0],d,"optgroup",f),d= g.nextSibling,g.label=a.group,g=c[a.group]={groupElement:g,currentOptionElement:g.firstChild}),k=r(g.groupElement,g.currentOptionElement,"option",e),n(a,k),g.currentOptionElement=k.nextSibling):(k=r(h[0],d,"option",e),n(a,k),d=k.nextSibling)});Object.keys(c).forEach(function(a){s(c[a].currentOptionElement)});s(d);v.$render();if(!v.$isEmpty(a)){var g=u.readValue();(z.trackBy?ka(a,g):a===g)||(v.$setViewValue(g),v.$render())}}var v=k[1];if(v){var u=k[0];k=l.multiple;for(var p,w=0,A=h.children(),I=A.length;w< I;w++)if(""===A[w].value){p=A.eq(w);break}var B=!!p,N=y(e.cloneNode(!1));N.val("?");var D,z=d(l.ngOptions,h,c);k?(v.$isEmpty=function(a){return!a||0===a.length},u.writeValue=function(a){D.items.forEach(function(a){a.element.selected=!1});a&&a.forEach(function(a){(a=D.getOptionFromViewValue(a))&&!a.disabled&&(a.element.selected=!0)})},u.readValue=function(){var a=h.val()||[],c=[];m(a,function(a){a=D.selectValueMap[a];a.disabled||c.push(D.getViewValueFromOption(a))});return c},z.trackBy&&c.$watchCollection(function(){if(G(v.$viewValue))return v.$viewValue.map(function(a){return z.getTrackByValue(a)})}, function(){v.$render()})):(u.writeValue=function(a){var c=D.getOptionFromViewValue(a);c&&!c.disabled?h[0].value!==c.selectValue&&(N.remove(),B||p.remove(),h[0].value=c.selectValue,c.element.selected=!0,c.element.setAttribute("selected","selected")):null===a||B?(N.remove(),B||h.prepend(p),h.val(""),p.prop("selected",!0),p.attr("selected",!0)):(B||p.remove(),h.prepend(N),h.val("?"),N.prop("selected",!0),N.attr("selected",!0))},u.readValue=function(){var a=D.selectValueMap[h.val()];return a&&!a.disabled? (B||p.remove(),N.remove(),D.getViewValueFromOption(a)):null},z.trackBy&&c.$watch(function(){return z.getTrackByValue(v.$viewValue)},function(){v.$render()}));B?(p.remove(),a(p)(c),p.removeClass("ng-scope")):p=y(e.cloneNode(!1));t();c.$watchCollection(z.getWatchables,t)}}}}],Ce=["$locale","$interpolate","$log",function(a,c,d){var e=/{}/g,f=/^when(Minus)?(.+)$/;return{link:function(g,h,l){function k(a){h.text(a||"")}var n=l.count,r=l.$attr.when&&h.attr(l.$attr.when),s=l.offset||0,q=g.$eval(r)||{},t= {},w=c.startSymbol(),u=c.endSymbol(),p=w+n+"-"+s+u,y=ca.noop,z;m(l,function(a,c){var d=f.exec(c);d&&(d=(d[1]?"-":"")+M(d[2]),q[d]=h.attr(l.$attr[c]))});m(q,function(a,d){t[d]=c(a.replace(e,p))});g.$watch(n,function(c){var e=parseFloat(c),f=isNaN(e);f||e in q||(e=a.pluralCat(e-s));e===z||f&&V(z)&&isNaN(z)||(y(),f=t[e],A(f)?(null!=c&&d.debug("ngPluralize: no rule defined for '"+e+"' in "+r),y=v,k()):y=g.$watch(f,k),z=e)})}}}],De=["$parse","$animate",function(a,c){var d=J("ngRepeat"),e=function(a,c, d,e,k,m,r){a[d]=e;k&&(a[k]=m);a.$index=c;a.$first=0===c;a.$last=c===r-1;a.$middle=!(a.$first||a.$last);a.$odd=!(a.$even=0===(c&1))};return{restrict:"A",multiElement:!0,transclude:"element",priority:1E3,terminal:!0,$$tlb:!0,compile:function(f,g){var h=g.ngRepeat,l=U.createComment(" end ngRepeat: "+h+" "),k=h.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);if(!k)throw d("iexp",h);var n=k[1],r=k[2],s=k[3],q=k[4],k=n.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/); if(!k)throw d("iidexp",n);var v=k[3]||k[1],w=k[2];if(s&&(!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(s)||/^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(s)))throw d("badident",s);var u,p,z,A,I={$id:Ga};q?u=a(q):(z=function(a,c){return Ga(c)},A=function(a){return a});return function(a,f,g,k,n){u&&(p=function(c,d,e){w&&(I[w]=c);I[v]=d;I.$index=e;return u(a,I)});var q=ga();a.$watchCollection(r,function(g){var k,r,u=f[0],x,D=ga(),I,H,L,G,M,J,O;s&&(a[s]=g);if(Ea(g))M= g,r=p||z;else for(O in r=p||A,M=[],g)g.hasOwnProperty(O)&&"$"!==O.charAt(0)&&M.push(O);I=M.length;O=Array(I);for(k=0;k<I;k++)if(H=g===M?k:M[k],L=g[H],G=r(H,L,k),q[G])J=q[G],delete q[G],D[G]=J,O[k]=J;else{if(D[G])throw m(O,function(a){a&&a.scope&&(q[a.id]=a)}),d("dupes",h,G,L);O[k]={id:G,scope:t,clone:t};D[G]=!0}for(x in q){J=q[x];G=qb(J.clone);c.leave(G);if(G[0].parentNode)for(k=0,r=G.length;k<r;k++)G[k].$$NG_REMOVED=!0;J.scope.$destroy()}for(k=0;k<I;k++)if(H=g===M?k:M[k],L=g[H],J=O[k],J.scope){x= u;do x=x.nextSibling;while(x&&x.$$NG_REMOVED);J.clone[0]!=x&&c.move(qb(J.clone),null,y(u));u=J.clone[J.clone.length-1];e(J.scope,k,v,L,w,H,I)}else n(function(a,d){J.scope=d;var f=l.cloneNode(!1);a[a.length++]=f;c.enter(a,null,y(u));u=f;J.clone=a;D[J.id]=J;e(J.scope,k,v,L,w,H,I)});q=D})}}}}],Ee=["$animate",function(a){return{restrict:"A",multiElement:!0,link:function(c,d,e){c.$watch(e.ngShow,function(c){a[c?"removeClass":"addClass"](d,"ng-hide",{tempClasses:"ng-hide-animate"})})}}}],xe=["$animate", function(a){return{restrict:"A",multiElement:!0,link:function(c,d,e){c.$watch(e.ngHide,function(c){a[c?"addClass":"removeClass"](d,"ng-hide",{tempClasses:"ng-hide-animate"})})}}}],Fe=Ma(function(a,c,d){a.$watch(d.ngStyle,function(a,d){d&&a!==d&&m(d,function(a,d){c.css(d,"")});a&&c.css(a)},!0)}),Ge=["$animate",function(a){return{require:"ngSwitch",controller:["$scope",function(){this.cases={}}],link:function(c,d,e,f){var g=[],h=[],l=[],k=[],n=function(a,c){return function(){a.splice(c,1)}};c.$watch(e.ngSwitch|| e.on,function(c){var d,e;d=0;for(e=l.length;d<e;++d)a.cancel(l[d]);d=l.length=0;for(e=k.length;d<e;++d){var q=qb(h[d].clone);k[d].$destroy();(l[d]=a.leave(q)).then(n(l,d))}h.length=0;k.length=0;(g=f.cases["!"+c]||f.cases["?"])&&m(g,function(c){c.transclude(function(d,e){k.push(e);var f=c.element;d[d.length++]=U.createComment(" end ngSwitchWhen: ");h.push({clone:d});a.enter(d,f.parent(),f)})})})}}}],He=Ma({transclude:"element",priority:1200,require:"^ngSwitch",multiElement:!0,link:function(a,c,d,e, f){e.cases["!"+d.ngSwitchWhen]=e.cases["!"+d.ngSwitchWhen]||[];e.cases["!"+d.ngSwitchWhen].push({transclude:f,element:c})}}),Ie=Ma({transclude:"element",priority:1200,require:"^ngSwitch",multiElement:!0,link:function(a,c,d,e,f){e.cases["?"]=e.cases["?"]||[];e.cases["?"].push({transclude:f,element:c})}}),Ke=Ma({restrict:"EAC",link:function(a,c,d,e,f){if(!f)throw J("ngTransclude")("orphan",ua(c));f(function(a){c.empty();c.append(a)})}}),ke=["$templateCache",function(a){return{restrict:"E",terminal:!0, compile:function(c,d){"text/ng-template"==d.type&&a.put(d.id,c[0].text)}}}],Bg={$setViewValue:v,$render:v},Cg=["$element","$scope","$attrs",function(a,c,d){var e=this,f=new Sa;e.ngModelCtrl=Bg;e.unknownOption=y(U.createElement("option"));e.renderUnknownOption=function(c){c="? "+Ga(c)+" ?";e.unknownOption.val(c);a.prepend(e.unknownOption);a.val(c)};c.$on("$destroy",function(){e.renderUnknownOption=v});e.removeUnknownOption=function(){e.unknownOption.parent()&&e.unknownOption.remove()};e.readValue= function(){e.removeUnknownOption();return a.val()};e.writeValue=function(c){e.hasOption(c)?(e.removeUnknownOption(),a.val(c),""===c&&e.emptyOption.prop("selected",!0)):null==c&&e.emptyOption?(e.removeUnknownOption(),a.val("")):e.renderUnknownOption(c)};e.addOption=function(a,c){Ra(a,'"option value"');""===a&&(e.emptyOption=c);var d=f.get(a)||0;f.put(a,d+1)};e.removeOption=function(a){var c=f.get(a);c&&(1===c?(f.remove(a),""===a&&(e.emptyOption=t)):f.put(a,c-1))};e.hasOption=function(a){return!!f.get(a)}}], le=function(){return{restrict:"E",require:["select","?ngModel"],controller:Cg,link:function(a,c,d,e){var f=e[1];if(f){var g=e[0];g.ngModelCtrl=f;f.$render=function(){g.writeValue(f.$viewValue)};c.on("change",function(){a.$apply(function(){f.$setViewValue(g.readValue())})});if(d.multiple){g.readValue=function(){var a=[];m(c.find("option"),function(c){c.selected&&a.push(c.value)});return a};g.writeValue=function(a){var d=new Sa(a);m(c.find("option"),function(a){a.selected=w(d.get(a.value))})};var h, l=NaN;a.$watch(function(){l!==f.$viewValue||ka(h,f.$viewValue)||(h=ia(f.$viewValue),f.$render());l=f.$viewValue});f.$isEmpty=function(a){return!a||0===a.length}}}}}},ne=["$interpolate",function(a){function c(a){a[0].hasAttribute("selected")&&(a[0].selected=!0)}return{restrict:"E",priority:100,compile:function(d,e){if(A(e.value)){var f=a(d.text(),!0);f||e.$set("value",d.text())}return function(a,d,e){var k=d.parent(),m=k.data("$selectController")||k.parent().data("$selectController");m&&m.ngModelCtrl&& (f?a.$watch(f,function(a,f){e.$set("value",a);f!==a&&m.removeOption(f);m.addOption(a,d);m.ngModelCtrl.$render();c(d)}):(m.addOption(e.value,d),m.ngModelCtrl.$render(),c(d)),d.on("$destroy",function(){m.removeOption(e.value);m.ngModelCtrl.$render()}))}}}}],me=ra({restrict:"E",terminal:!1}),Hc=function(){return{restrict:"A",require:"?ngModel",link:function(a,c,d,e){e&&(d.required=!0,e.$validators.required=function(a,c){return!d.required||!e.$isEmpty(c)},d.$observe("required",function(){e.$validate()}))}}}, Gc=function(){return{restrict:"A",require:"?ngModel",link:function(a,c,d,e){if(e){var f,g=d.ngPattern||d.pattern;d.$observe("pattern",function(a){L(a)&&0<a.length&&(a=new RegExp("^"+a+"$"));if(a&&!a.test)throw J("ngPattern")("noregexp",g,a,ua(c));f=a||t;e.$validate()});e.$validators.pattern=function(a){return e.$isEmpty(a)||A(f)||f.test(a)}}}}},Jc=function(){return{restrict:"A",require:"?ngModel",link:function(a,c,d,e){if(e){var f=-1;d.$observe("maxlength",function(a){a=W(a);f=isNaN(a)?-1:a;e.$validate()}); e.$validators.maxlength=function(a,c){return 0>f||e.$isEmpty(c)||c.length<=f}}}}},Ic=function(){return{restrict:"A",require:"?ngModel",link:function(a,c,d,e){if(e){var f=0;d.$observe("minlength",function(a){f=W(a)||0;e.$validate()});e.$validators.minlength=function(a,c){return e.$isEmpty(c)||c.length>=f}}}}};O.angular.bootstrap?console.log("WARNING: Tried to load angular more than once."):(ce(),ee(ca),y(U).ready(function(){Zd(U,Ac)}))})(window,document);!window.angular.$$csp()&&window.angular.element(document).find("head").prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>'); //# sourceMappingURL=angular.min.js.map ```
/content/code_sandbox/public/vendor/datetimepicker/demo/AngularJS/angular-1.4.2.min.js
javascript
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
50,447
```html <!DOCTYPE html> <html> <head> <title>Period Range - Parameters</title> <link rel="stylesheet" type="text/css" href="../../src/DateTimePicker.css" /> <link rel="stylesheet" type="text/css" href="jquery.mobile-1.4.0.min.css" /> <script type="text/javascript" src="../jquery-1.11.0.min.js"></script> <script type="text/javascript" src="jquery.mobile-1.4.0.min.js"></script> <script type="text/javascript" src="../../src/DateTimePicker.js"></script> <script type="text/javascript"> $(document).ready(function() { // DOM Element Insertion and Plugin Initialisation on loading of first page if you are using DatePicker on first page $("#page1").append("<div id='dateBox'></div>"); // Add Element To DOM $("#dateBox").DateTimePicker(); // Plugin Initialization // Otherwise, DOM Element Insertion and Plugin Initialisation can be done on pageshow $("#page1, #page2").on("pageshow", function(event) { $(this).append("<div id='dateBox'></div>"); // Add Element To DOM $("#dateBox").DateTimePicker(); // Plugin Initialization }); // DOM Element Removal on pagehide method $("#page1, #page2").on("pagehide", function(event) { $("#dateBox").remove(); // Remove Element From DOM }); }); </script> </head> <body> <!-- Start of first page --> <div data-role="page" id="page1"> <div data-role="header"> <h1>Page 1</h1> </div><!-- /header --> <div role="main" class="ui-content"> <p><a href="#page2">Page 2</a></p> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> <a href="#popupBasic" data-rel="popup">Open Popup</a> <div data-role="popup" id="popupBasic"> <p>This is a completely basic popup, no options set.<p> </div> </div><!-- /content --> <div data-role="footer"> <h4>Page Footer</h4> </div><!-- /footer --> </div><!-- /page --> <!-- Start of second page --> <div data-role="page" id="page2"> <div data-role="header"> <h1>Page 2</h1> </div><!-- /header --> <div role="main" class="ui-content"> <p><a href="#page1">Page 1</a></p> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> </div><!-- /content --> <div data-role="footer"> <h4>Page Footer</h4> </div><!-- /footer --> </div><!-- /page --> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/jQuery Mobile Project/BasicExampleMobile.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
887
```html <!DOCTYPE html> <html> <head> <title>Period Range - Parameters</title> <link rel="stylesheet" type="text/css" href="../../src/DateTimePicker.css" /> <link rel="stylesheet" type="text/css" href="jquery.mobile-1.4.0.min.css" /> <script type="text/javascript" src="../jquery-1.11.0.min.js"></script> <script type="text/javascript" src="jquery.mobile-1.4.0.min.js"></script> <script type="text/javascript" src="../../src/DateTimePicker.js"></script> <style type="text/css"> .ui-header-fixed { z-index: 5000; } </style> <script type="text/javascript"> $(document).ready(function() { // DOM Element Insertion and Plugin Initialisation on loading of first page if you are using DatePicker on first page $("#page1").find(".ui-content").append("<div id='dateBox'></div>"); // Add Element To DOM $("#dateBox").DateTimePicker(); // Plugin Initialization // Otherwise, DOM Element Insertion and Plugin Initialisation can be done on pageshow $("#page1, #page2").on("pageshow", function(event) { $(this).find(".ui-content").append("<div id='dateBox'></div>"); // Add Element To DOM $("#dateBox").DateTimePicker(); // Plugin Initialization }); // DOM Element Removal on pagehide method $("#page1, #page2").on("pagehide", function(event) { $("#dateBox").remove(); // Remove Element From DOM }); }); </script> </head> <body> <!-- Start of first page --> <div data-role="page" id="page1"> <div class="ui-header-fixed" data-role="header" data-tap-toggle="false" data-position="fixed"> <h1>Page 1</h1> <a class="" href="#page2">Page 2</a> </div><!-- /header --> <div role="main" class="ui-content"> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> </div><!-- /content --> <div data-role="footer"> <h4>Page Footer</h4> </div><!-- /footer --> </div><!-- /page --> <!-- Start of second page --> <div data-role="page" id="page2"> <div class="ui-header-fixed" data-role="header" data-tap-toggle="false" data-position="fixed"> <h1>Page 2</h1> <a href="#page1">Page 1</a> </div><!-- /header --> <div role="main" class="ui-content"> <!------------------------ Date Picker ------------------------> <p>Date : </p> <input type="text" data-field="date" readonly> <!------------------------ Time Picker ------------------------> <p>Time : </p> <input type="text" data-field="time" readonly> <!---------------------- DateTime Picker ----------------------> <p>DateTime : </p> <input type="text" data-field="datetime" readonly> </div><!-- /content --> <div data-role="footer"> <h4>Page Footer</h4> </div><!-- /footer --> </div><!-- /page --> </body> </html> ```
/content/code_sandbox/public/vendor/datetimepicker/demo/jQuery Mobile Project/BasicExampleMobileWithLink.htm
html
2016-03-03T01:33:10
2024-08-16T12:05:02
Attendize
Attendize/Attendize
3,955
908