code
stringlengths
2
1.05M
/** * The reveal.js markdown plugin. Handles parsing of * markdown inside of presentations as well as loading * of external markdown documents. */ (function( root, factory ) { if( typeof exports === 'object' ) { module.exports = factory( require( './marked' ) ); } else { // Browser globals (root is window) root.RevealMarkdown = factory( root.marked ); root.RevealMarkdown.initialize(); } }( this, function( marked ) { if( typeof marked === 'undefined' ) { throw 'The reveal.js Markdown plugin requires marked to be loaded'; } if( typeof hljs !== 'undefined' ) { marked.setOptions({ highlight: function( lang, code ) { return hljs.highlightAuto( lang, code ).value; } }); } var DEFAULT_SLIDE_SEPARATOR = '^\r?\n---\r?\n$', DEFAULT_NOTES_SEPARATOR = 'note:', DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR = '\\\.element\\\s*?(.+?)$', DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR = '\\\.slide:\\\s*?(\\\S.+?)$'; var SCRIPT_END_PLACEHOLDER = '__SCRIPT_END__'; /** * Retrieves the markdown contents of a slide section * element. Normalizes leading tabs/whitespace. */ function getMarkdownFromSlide( section ) { var template = section.querySelector( 'script' ); // strip leading whitespace so it isn't evaluated as code var text = ( template || section ).textContent; // restore script end tags text = text.replace( new RegExp( SCRIPT_END_PLACEHOLDER, 'g' ), '</script>' ); var leadingWs = text.match( /^\n?(\s*)/ )[1].length, leadingTabs = text.match( /^\n?(\t*)/ )[1].length; if( leadingTabs > 0 ) { text = text.replace( new RegExp('\\n?\\t{' + leadingTabs + '}','g'), '\n' ); } else if( leadingWs > 1 ) { text = text.replace( new RegExp('\\n? {' + leadingWs + '}', 'g'), '\n' ); } return text; } /** * Given a markdown slide section element, this will * return all arguments that aren't related to markdown * parsing. Used to forward any other user-defined arguments * to the output markdown slide. */ function getForwardedAttributes( section ) { var attributes = section.attributes; var result = []; for( var i = 0, len = attributes.length; i < len; i++ ) { var name = attributes[i].name, value = attributes[i].value; // disregard attributes that are used for markdown loading/parsing if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue; if( value ) { result.push( name + '="' + value + '"' ); } else { result.push( name ); } } return result.join( ' ' ); } /** * Inspects the given options and fills out default * values for what's not defined. */ function getSlidifyOptions( options ) { options = options || {}; options.separator = options.separator || DEFAULT_SLIDE_SEPARATOR; options.notesSeparator = options.notesSeparator || DEFAULT_NOTES_SEPARATOR; options.attributes = options.attributes || ''; return options; } /** * Helper function for constructing a markdown slide. */ function createMarkdownSlide( content, options ) { options = getSlidifyOptions( options ); var notesMatch = content.split( new RegExp( options.notesSeparator, 'mgi' ) ); if( notesMatch.length === 2 ) { content = notesMatch[0] + '<aside class="notes" data-markdown>' + notesMatch[1].trim() + '</aside>'; } // prevent script end tags in the content from interfering // with parsing content = content.replace( /<\/script>/g, SCRIPT_END_PLACEHOLDER ); return '<script type="text/template">' + content + '</script>'; } /** * Parses a data string into multiple slides based * on the passed in separator arguments. */ function slidify( markdown, options ) { options = getSlidifyOptions( options ); var separatorRegex = new RegExp( options.separator + ( options.verticalSeparator ? '|' + options.verticalSeparator : '' ), 'mg' ), horizontalSeparatorRegex = new RegExp( options.separator ); var matches, lastIndex = 0, isHorizontal, wasHorizontal = true, content, sectionStack = []; // iterate until all blocks between separators are stacked up while( matches = separatorRegex.exec( markdown ) ) { notes = null; // determine direction (horizontal by default) isHorizontal = horizontalSeparatorRegex.test( matches[0] ); if( !isHorizontal && wasHorizontal ) { // create vertical stack sectionStack.push( [] ); } // pluck slide content from markdown input content = markdown.substring( lastIndex, matches.index ); if( isHorizontal && wasHorizontal ) { // add to horizontal stack sectionStack.push( content ); } else { // add to vertical stack sectionStack[sectionStack.length-1].push( content ); } lastIndex = separatorRegex.lastIndex; wasHorizontal = isHorizontal; } // add the remaining slide ( wasHorizontal ? sectionStack : sectionStack[sectionStack.length-1] ).push( markdown.substring( lastIndex ) ); var markdownSections = ''; // flatten the hierarchical stack, and insert <section data-markdown> tags for( var i = 0, len = sectionStack.length; i < len; i++ ) { // vertical if( sectionStack[i] instanceof Array ) { markdownSections += '<section '+ options.attributes +'>'; sectionStack[i].forEach( function( child ) { markdownSections += '<section data-markdown>' + createMarkdownSlide( child, options ) + '</section>'; } ); markdownSections += '</section>'; } else { markdownSections += '<section '+ options.attributes +' data-markdown>' + createMarkdownSlide( sectionStack[i], options ) + '</section>'; } } return markdownSections; } /** * Parses any current data-markdown slides, splits * multi-slide markdown into separate sections and * handles loading of external markdown. */ function processSlides() { var sections = document.querySelectorAll( '[data-markdown]'), section; for( var i = 0, len = sections.length; i < len; i++ ) { section = sections[i]; if( section.getAttribute( 'data-markdown' ).length ) { var xhr = new XMLHttpRequest(), url = section.getAttribute( 'data-markdown' ); datacharset = section.getAttribute( 'data-charset' ); // see https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute#Notes if( datacharset != null && datacharset != '' ) { xhr.overrideMimeType( 'text/html; charset=' + datacharset ); } xhr.onreadystatechange = function() { if( xhr.readyState === 4 ) { // file protocol yields status code 0 (useful for local debug, mobile applications etc.) if ( ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status === 0 ) { section.outerHTML = slidify( xhr.responseText, { separator: section.getAttribute( 'data-separator' ), verticalSeparator: section.getAttribute( 'data-separator-vertical' ), notesSeparator: section.getAttribute( 'data-separator-notes' ), attributes: getForwardedAttributes( section ) }); } else { section.outerHTML = '<section data-state="alert">' + 'ERROR: The attempt to fetch ' + url + ' failed with HTTP status ' + xhr.status + '.' + 'Check your browser\'s JavaScript console for more details.' + '<p>Remember that you need to serve the presentation HTML from a HTTP server.</p>' + '</section>'; } } }; xhr.open( 'GET', url, false ); try { xhr.send(); } catch ( e ) { alert( 'Failed to get the Markdown file ' + url + '. Make sure that the presentation and the file are served by a HTTP server and the file can be found there. ' + e ); } } else if( section.getAttribute( 'data-separator' ) || section.getAttribute( 'data-separator-vertical' ) || section.getAttribute( 'data-separator-notes' ) ) { section.outerHTML = slidify( getMarkdownFromSlide( section ), { separator: section.getAttribute( 'data-separator' ), verticalSeparator: section.getAttribute( 'data-separator-vertical' ), notesSeparator: section.getAttribute( 'data-separator-notes' ), attributes: getForwardedAttributes( section ) }); } else { section.innerHTML = createMarkdownSlide( getMarkdownFromSlide( section ) ); } } } /** * Check if a node value has the attributes pattern. * If yes, extract it and add that value as one or several attributes * the the terget element. * * You need Cache Killer on Chrome to see the effect on any FOM transformation * directly on refresh (F5) * http://stackoverflow.com/questions/5690269/disabling-chrome-cache-for-website-development/7000899#answer-11786277 */ function addAttributeInElement( node, elementTarget, separator ) { var mardownClassesInElementsRegex = new RegExp( separator, 'mg' ); var mardownClassRegex = new RegExp( "([^\"= ]+?)=\"([^\"=]+?)\"", 'mg' ); var nodeValue = node.nodeValue; if( matches = mardownClassesInElementsRegex.exec( nodeValue ) ) { var classes = matches[1]; nodeValue = nodeValue.substring( 0, matches.index ) + nodeValue.substring( mardownClassesInElementsRegex.lastIndex ); node.nodeValue = nodeValue; while( matchesClass = mardownClassRegex.exec( classes ) ) { elementTarget.setAttribute( matchesClass[1], matchesClass[2] ); } return true; } return false; } /** * Add attributes to the parent element of a text node, * or the element of an attribute node. */ function addAttributes( section, element, previousElement, separatorElementAttributes, separatorSectionAttributes ) { if ( element != null && element.childNodes != undefined && element.childNodes.length > 0 ) { previousParentElement = element; for( var i = 0; i < element.childNodes.length; i++ ) { childElement = element.childNodes[i]; if ( i > 0 ) { j = i - 1; while ( j >= 0 ) { aPreviousChildElement = element.childNodes[j]; if ( typeof aPreviousChildElement.setAttribute == 'function' && aPreviousChildElement.tagName != "BR" ) { previousParentElement = aPreviousChildElement; break; } j = j - 1; } } parentSection = section; if( childElement.nodeName == "section" ) { parentSection = childElement ; previousParentElement = childElement ; } if ( typeof childElement.setAttribute == 'function' || childElement.nodeType == Node.COMMENT_NODE ) { addAttributes( parentSection, childElement, previousParentElement, separatorElementAttributes, separatorSectionAttributes ); } } } if ( element.nodeType == Node.COMMENT_NODE ) { if ( addAttributeInElement( element, previousElement, separatorElementAttributes ) == false ) { addAttributeInElement( element, section, separatorSectionAttributes ); } } } /** * Converts any current data-markdown slides in the * DOM to HTML. */ function convertSlides() { var sections = document.querySelectorAll( '[data-markdown]'); for( var i = 0, len = sections.length; i < len; i++ ) { var section = sections[i]; // Only parse the same slide once if( !section.getAttribute( 'data-markdown-parsed' ) ) { section.setAttribute( 'data-markdown-parsed', true ); var notes = section.querySelector( 'aside.notes' ); var markdown = getMarkdownFromSlide( section ); section.innerHTML = marked( markdown ); addAttributes( section, section, null, section.getAttribute( 'data-element-attributes' ) || section.parentNode.getAttribute( 'data-element-attributes' ) || DEFAULT_ELEMENT_ATTRIBUTES_SEPARATOR, section.getAttribute( 'data-attributes' ) || section.parentNode.getAttribute( 'data-attributes' ) || DEFAULT_SLIDE_ATTRIBUTES_SEPARATOR); // If there were notes, we need to re-add them after // having overwritten the section's HTML if( notes ) { section.appendChild( notes ); } } } } // API return { initialize: function() { processSlides(); convertSlides(); }, // TODO: Do these belong in the API? processSlides: processSlides, convertSlides: convertSlides, slidify: slidify }; }));
'use strict'; var chai = require('chai'); var should = chai.should(); var bitcore = require('bitcore-lib'); var models = require('../../lib/models'); var WalletAddress = models.WalletAddress; describe('Wallet Address Model', function() { function checkAddress(key) { key.address.toString().should.equal('2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br'); key.walletId.toString('hex').should.equal('b4f97411dadf3882296997ade99f4a0891b07e768a76898b837ac41d2c2622e7'); } function checkAddressJSON(key) { key.address.should.equal('2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br'); key.walletId.should.equal('b4f97411dadf3882296997ade99f4a0891b07e768a76898b837ac41d2c2622e7'); } var walletId = new Buffer('b4f97411dadf3882296997ade99f4a0891b07e768a76898b837ac41d2c2622e7', 'hex'); describe('@constructor', function() { it('throw error without address', function() { (function() { var key = new WalletAddress(); }).should.throw(Error); }); it('with address', function() { var key = new WalletAddress(walletId, bitcore.Address('2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br')); should.exist(key); checkAddress(key); }); it('with strings', function() { var key = new WalletAddress( 'b4f97411dadf3882296997ade99f4a0891b07e768a76898b837ac41d2c2622e7', '2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br'); should.exist(key); checkAddress(key); }); it('with address non instance', function() { var key = WalletAddress(walletId, bitcore.Address('2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br')); should.exist(key); checkAddress(key); }); }); describe('@create', function() { it('will create an instance', function () { var key = WalletAddress.create(walletId, bitcore.Address('2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br')); should.exist(key); checkAddress(key); }); }); describe('#getKey', function() { it('will return database key', function() { var key = new WalletAddress(walletId, '2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br'); var dbKey = key.getKey(); Buffer.isBuffer(dbKey).should.equal(true); var expectedKey = walletId.toString('hex'); expectedKey += '02'; expectedKey += '6349a418fc4578d10a372b54b45c280cc8c4382f'; dbKey.toString('hex').should.equal(expectedKey); }); }); describe('#getValue', function() { it('will return empty buffer (expect to store additional info later)', function() { var key = new WalletAddress(walletId, '2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br'); var dbKey = key.getValue(); Buffer.isBuffer(dbKey).should.equal(true); dbKey.length.should.equal(0); }); }); describe('@fromBuffer', function() { it('will parse buffer', function() { var keyHex = walletId.toString('hex'); keyHex += '02'; keyHex += '6349a418fc4578d10a372b54b45c280cc8c4382f'; var key = WalletAddress.fromBuffer(new Buffer(keyHex, 'hex'), new Buffer(new Array(0)), bitcore.Networks.testnet); var keyString = WalletAddress.fromBuffer(keyHex, new Buffer(new Array(0)), bitcore.Networks.testnet); keyString.should.deep.equal(key); should.exist(key); }); }); describe('#toJSON', function() { it('will transform to JSON', function() { var key = new WalletAddress(walletId, bitcore.Address('2N2JD6wb56AfK4tfmM6PwdVmoYk2dCKf4Br')); checkAddressJSON(JSON.parse(JSON.stringify(key))); }); }); });
// Libraries required for testing const util = require('util'); const test = require('ava'); const cryptoRandomString = require('crypto-random-string'); const { factory } = require('factory-girl'); const phrases = require('../../config/phrases'); const utils = require('../utils'); test.before(utils.setupMongoose); test.before(utils.defineUserFactory); test.after.always(utils.teardownMongoose); test.beforeEach(utils.setupWebServer); test('creates new user', async (t) => { const { web } = t.context; const user = await factory.build('user'); const res = await web.post('/en/register').send({ email: user.email, password: '!@K#NLK!#N' }); t.is(res.status, 302); t.is(res.header.location, '/en/my-account'); }); test('fails registering with easy password', async (t) => { const { web } = t.context; const res = await web.post('/en/register').send({ email: 'emilydickinson@example.com', password: 'password' }); t.is(res.status, 400); t.is(res.body.message, phrases.INVALID_PASSWORD_STRENGHT); }); test('successfully registers with strong password', async (t) => { const { web } = t.context; const user = await factory.build('user'); const res = await web.post('/en/register').send({ email: user.email, password: 'Thi$i$@$r0ng3rP@$$W0rdMyDude' }); t.is(res.body.message, undefined); t.is(res.header.location, '/en/my-account'); t.is(res.status, 302); }); test('successfully registers with stronger password', async (t) => { const { web } = t.context; const password = await cryptoRandomString.async({ length: 50 }); const res = await web.post('/en/register').send({ email: 'test123@example.com', password }); t.is(res.body.message, undefined); t.is(res.header.location, '/en/my-account'); t.is(res.status, 302); }); test('fails registering invalid email', async (t) => { const { web } = t.context; const res = await web.post('/en/register').send({ email: 'test123', password: 'testpassword' }); t.is(res.status, 400); t.is(JSON.parse(res.text).message, phrases.INVALID_EMAIL); }); test("doesn't leak used email", async (t) => { const { web } = t.context; const user = await factory.create('user'); const res = await web.post('/en/register').send({ email: user.email, password: 'wrongpassword' }); t.is(res.status, 400); t.is(JSON.parse(res.text).message, phrases.PASSPORT_USER_EXISTS_ERROR); }); test('allows password reset for valid email (HTML)', async (t) => { const { web } = t.context; const user = await factory.create('user'); const res = await web .post('/en/forgot-password') .set({ Accept: 'text/html' }) .send({ email: user.email }); t.is(res.status, 302); t.is(res.header.location, '/'); }); test('allows password reset for valid email (JSON)', async (t) => { const { web } = t.context; const user = await factory.create('user'); const res = await web.post('/en/forgot-password').send({ email: user.email }); t.is(res.status, 302); t.is(res.header.location, '/'); }); test('resets password with valid email and token (HTML)', async (t) => { const { web } = t.context; const user = await factory.create('user', {}, { resetToken: 'token' }); const { email } = user; const password = '!@K#NLK!#N'; const res = await web .post(`/en/reset-password/token`) .set({ Accept: 'text/html' }) .send({ email, password }); t.is(res.status, 302); t.is(res.header.location, '/en'); }); test('resets password with valid email and token (JSON)', async (t) => { const { web } = t.context; const user = await factory.create('user', {}, { resetToken: 'token' }); const { email } = user; const password = '!@K#NLK!#N'; const res = await web .post(`/en/reset-password/token`) .send({ email, password }); t.is(res.status, 302); t.is(res.header.location, '/en'); }); test('fails resetting password for non-existent user', async (t) => { const { web } = t.context; const email = 'test7@example.com'; const password = '!@K#NLK!#N'; const res = await web .post('/en/reset-password/randomtoken') .send({ email, password }); t.is(res.status, 400); t.is(JSON.parse(res.text).message, phrases.INVALID_RESET_PASSWORD); }); test('fails resetting password with invalid reset token', async (t) => { const { web } = t.context; const user = await factory.create('user', {}, { resetToken: 'token' }); const { email } = user; const password = '!@K#NLK!#N'; const res = await web .post('/en/reset-password/wrongtoken') .send({ email, password }); t.is(res.status, 400); t.is(JSON.parse(res.text).message, phrases.INVALID_RESET_PASSWORD); }); test('fails resetting password with missing new password', async (t) => { const { web } = t.context; const user = await factory.create('user', {}, { resetToken: 'token' }); const { email } = user; const res = await web.post(`/en/reset-password/token`).send({ email }); t.is(res.status, 400); t.is(JSON.parse(res.text).message, phrases.INVALID_PASSWORD); }); test('fails resetting password with invalid email', async (t) => { const { web } = t.context; await factory.create('user', {}, { resetToken: 'token' }); const res = await web .post(`/en/reset-password/token`) .send({ email: 'wrongemail' }); t.is(res.status, 400); t.is(JSON.parse(res.text).message, phrases.INVALID_EMAIL); }); test('fails resetting password with invalid email + reset token match', async (t) => { const { web } = t.context; await factory.create('user', {}, { resetToken: 'token' }); const password = '!@K#NLK!#N'; const res = await web .post(`/en/reset-password/token`) .send({ email: 'wrongemail@example.com', password }); t.is(res.status, 400); t.is(JSON.parse(res.text).message, phrases.INVALID_RESET_PASSWORD); }); test('fails resetting password if new password is too weak', async (t) => { const { web } = t.context; const user = await factory.create('user', {}, { resetToken: 'token' }); const { email } = user; const res = await web .post(`/en/reset-password/token`) .send({ email, password: 'password' }); t.is(res.status, 400); t.is(JSON.parse(res.text).message, phrases.INVALID_PASSWORD_STRENGTH); }); test('fails resetting password if reset was already tried in the last 30 mins', async (t) => { const { web } = t.context; const user = await factory.create('user'); const { email } = user; await web.post('/en/forgot-password').send({ email }); const res = await web.post('/en/forgot-password').send({ email }); t.is(res.status, 400); t.is( JSON.parse(res.text).message, util.format(phrases.PASSWORD_RESET_LIMIT, 'in 30 minutes') ); });
'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = require('react'); var _react2 = _interopRequireDefault(_react); jest.dontMock('../Map'); jest.dontMock('../MapComponent'); var Map = require('../Map'); describe('Map', function () { beforeEach(function () { document.body.innerHTML = '<div id="test"></div>'; }); it('only renders the container div server-side', function () { var Component = (function (_React$Component) { _inherits(Component, _React$Component); function Component() { _classCallCheck(this, Component); _get(Object.getPrototypeOf(Component.prototype), 'constructor', this).apply(this, arguments); } _createClass(Component, [{ key: 'render', value: function render() { return _react2['default'].createElement( 'span', null, 'test' ); } }]); return Component; })(_react2['default'].Component); var component = _react2['default'].createElement( Map, null, _react2['default'].createElement(Component, null) ); var html = _react2['default'].renderToStaticMarkup(component, document.getElementById('test')); expect(html).toBe('<div id="map1"></div>'); }); it('initializes the map in the rendered container', function () { var component = _react2['default'].createElement(Map, null); var instance = _react2['default'].render(component, document.getElementById('test')); var node = _react2['default'].findDOMNode(instance); expect(node._leaflet).toBe(true); }); it('sets center and zoom props', function () { var center = [1.2, 3.4]; var zoom = 10; var component = _react2['default'].createElement(Map, { center: center, zoom: zoom }); var instance = _react2['default'].render(component, document.getElementById('test')); var mapLeaflet = instance.leafletElement; expect(mapLeaflet.getCenter().lat).toBe(center[0]); expect(mapLeaflet.getCenter().lng).toBe(center[1]); expect(mapLeaflet.getZoom()).toBe(zoom); }); it('updates center and zoom props', function () { var Component = (function (_React$Component2) { _inherits(Component, _React$Component2); function Component() { _classCallCheck(this, Component); _get(Object.getPrototypeOf(Component.prototype), 'constructor', this).call(this); this.state = { center: [1.2, 3.4], zoom: 10 }; } _createClass(Component, [{ key: 'getLeafletMap', value: function getLeafletMap() { return this.refs.map.leafletElement; } }, { key: 'updatePosition', value: function updatePosition() { this.setState({ center: [2.3, 4.5], zoom: 12 }); } }, { key: 'render', value: function render() { return _react2['default'].createElement(Map, { ref: 'map', center: this.state.center, zoom: this.state.zoom }); } }]); return Component; })(_react2['default'].Component); var instance = _react2['default'].render(_react2['default'].createElement(Component, null), document.getElementById('test')); var mapLeaflet = instance.getLeafletMap(); expect(mapLeaflet.getCenter().lat).toBe(1.2); expect(mapLeaflet.getCenter().lng).toBe(3.4); expect(mapLeaflet.getZoom()).toBe(10); instance.updatePosition(); expect(mapLeaflet.getCenter().lat).toBe(2.3); expect(mapLeaflet.getCenter().lng).toBe(4.5); expect(mapLeaflet.getZoom()).toBe(12); }); });
/*! jQuery UI - v1.10.4 - 2014-03-23 * http://jqueryui.com * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(t){t.datepicker.regional.es={closeText:"Cerrar",prevText:"&#x3C;Ant",nextText:"Sig&#x3E;",currentText:"Hoy",monthNames:["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"],monthNamesShort:["ene","feb","mar","abr","may","jun","jul","ogo","sep","oct","nov","dic"],dayNames:["domingo","lunes","martes","miércoles","jueves","viernes","sábado"],dayNamesShort:["dom","lun","mar","mié","juv","vie","sáb"],dayNamesMin:["D","L","M","X","J","V","S"],weekHeader:"Sm",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional.es)});
import React from 'react' import { createStore, combineReducers, compose, applyMiddleware } from 'redux' import { createDevTools } from 'redux-devtools' import LogMonitor from 'redux-devtools-log-monitor' import DockMonitor from 'redux-devtools-dock-monitor' import { routerReducer, routerMiddleware } from 'react-router-redux' export const DevTools = createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q"> <LogMonitor theme="tomorrow" preserveScrollTop={false} /> </DockMonitor> ) export function configureStore(history, initialState) { const reducer = combineReducers({ routing: routerReducer }) let devTools = [] if (typeof document !== 'undefined') { devTools = [ DevTools.instrument() ] } const store = createStore( reducer, initialState, compose( applyMiddleware( routerMiddleware(history) ), ...devTools ) ) return store }
/* bilibli * @朱一 */ var purl = require('./purl') var log = require('./log') var httpProxy = require('./httpProxy') function pad(num, n) { return (Array(n).join(0) + num).slice(-n) } exports.match = function (url) { return url.attr('host').indexOf('bilibili') >= 0 && /^\/video\/av\d+\/$/.test(url.attr('directory')) } exports.getVideos = function (url, callback) { log('开始解析bilibli视频地址') var aid = url.attr('directory').match(/^\/video\/av(\d+)\/$/)[1] var page = (function () { pageMatch = url.attr('file').match(/^index\_(\d+)\.html$/) return pageMatch ? pageMatch[1] : 1 }()) httpProxy( 'http://www.bilibili.com/m/html5', 'get', {aid: aid, page: page}, function (rs) { if (rs && rs.src) { log('获取到<a href="'+rs.src+'">视频地址</a>, 并开始解析bilibli弹幕') var source = [ ['bilibili', rs.src] ] httpProxy(rs.cid, 'get', {}, function (rs) { if (rs && rs.i) { var comments = [].concat(rs.i.d || []) comments = comments.map(function (comment) { var p = comment['@p'].split(',') switch (p[1] | 0) { case 4: p[1] = 'bottom'; break case 5: p[1] = 'top'; break default: p[1] = 'loop' } return { time: parseFloat(p[0]), pos: p[1], color: '#' + pad((p[3] | 0).toString(16), 6), text: comment['#text'] } }).sort(function (a, b) { return a.time - b.time }) log('一切顺利开始播放', 2) callback(source, comments) } else { log('解析bilibli弹幕失败, 但勉强可以播放', 2) callback(source) } }, {gzinflate:1, xml:1}) } else { log('解析bilibli视频地址失败', 2) callback(false) } }) }
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller.js'), _ = require('lodash'), UserEntry = mongoose.model('UserEntry'); /** * Create a User entry */ exports.create = function(req, res) { var entry = req.body; entry.netid = entry.netid.toLowerCase(); UserEntry.findOne({netid:entry.netid}, function(err, response){ if(err) return res.status(400).send(err); if(response){ entry = _.extend(response, entry); entry.updated = Date.now(); } else entry = new UserEntry(entry); entry.save(function(err) { if (err) return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); else res.jsonp(entry); }); }); }; /** * Show the current User entry */ exports.read = function(req, res) { var entry = req.entry; res.json(entry); }; /** * Update a User entry */ exports.update = function(req, res) { var entry = _.extend(req.entry , req.body); entry.updated = Date.now(); entry.save(function(err) { if (err) return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); else res.jsonp(entry); }); }; /** * Delete an User entry */ exports.delete = function(req, res) { var entry = _.extend(req.entry , {isActive:false}); entry.updated = Date.now(); entry.save(function(err) { if (err) return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); else res.jsonp(entry); }); }; /** * User entries middleware */ exports.userEntryByNetId = function(req, res, next, netid) { UserEntry.findOne({netid:netid}, function(err, entry){ if (err) return next(err); if (!entry) req.entry = null; else req.entry = entry; next(); }); };
const { resolve } = require(`path`) const { DuotoneGradientType, ImageCropFocusType, } = require(`gatsby-transformer-sharp/types`) const { queueImageResizing } = require(`gatsby-plugin-sharp`) const Debug = require(`debug`) const fs = require(`fs-extra`) const { GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLBoolean, } = require(`gatsby/graphql`) const sharp = require(`sharp`) const { ensureDir } = require(`fs-extra`) const generateSqip = require(`./generate-sqip`) const debug = Debug(`gatsby-transformer-sqip`) const SUPPORTED_NODES = [`ImageSharp`, `ContentfulAsset`] module.exports = async args => { const { type: { name }, } = args if (!SUPPORTED_NODES.includes(name)) { return {} } if (name === `ImageSharp`) { return sqipSharp(args) } if (name === `ContentfulAsset`) { return sqipContentful(args) } return {} } async function sqipSharp({ type, cache, getNodeAndSavePathDependency, store }) { const program = store.getState().program const cacheDir = resolve(`${program.directory}/.cache/sqip/`) await ensureDir(cacheDir) return { sqip: { type: new GraphQLObjectType({ name: `Sqip`, fields: { svg: { type: GraphQLString }, dataURI: { type: GraphQLString }, }, }), args: { blur: { type: GraphQLInt, defaultValue: 1 }, numberOfPrimitives: { type: GraphQLInt, defaultValue: 10 }, mode: { type: GraphQLInt, defaultValue: 0 }, width: { type: GraphQLInt, defaultValue: 256, }, height: { type: GraphQLInt, }, grayscale: { type: GraphQLBoolean, defaultValue: false, }, duotone: { type: DuotoneGradientType, defaultValue: false, }, cropFocus: { type: ImageCropFocusType, defaultValue: sharp.strategy.attention, }, rotate: { type: GraphQLInt, defaultValue: 0, }, }, async resolve(image, fieldArgs, context) { const { blur, numberOfPrimitives, mode, width, height, grayscale, duotone, cropFocus, rotate, } = fieldArgs const sharpArgs = { width, height, grayscale, duotone, cropFocus, rotate, } const file = getNodeAndSavePathDependency(image.parent, context.path) const job = await queueImageResizing({ file, args: sharpArgs }) if (!(await fs.exists(job.absolutePath))) { debug(`Preparing ${file.name}`) await job.finishedPromise } const { absolutePath } = job return generateSqip({ cache, cacheDir, absolutePath, numberOfPrimitives, blur, mode, }) }, }, } } async function sqipContentful({ type, cache, store }) { const { schemes: { ImageResizingBehavior, ImageCropFocusType }, } = require(`gatsby-source-contentful`) const cacheImage = require(`gatsby-source-contentful/cache-image`) const program = store.getState().program const cacheDir = resolve(`${program.directory}/.cache/sqip/`) await ensureDir(cacheDir) return { sqip: { type: new GraphQLObjectType({ name: `Sqip`, fields: { svg: { type: GraphQLString }, dataURI: { type: GraphQLString }, }, }), args: { blur: { type: GraphQLInt, defaultValue: 1, }, numberOfPrimitives: { type: GraphQLInt, defaultValue: 10, }, mode: { type: GraphQLInt, defaultValue: 0, }, width: { type: GraphQLInt, defaultValue: 256, }, height: { type: GraphQLInt, }, resizingBehavior: { type: ImageResizingBehavior, }, cropFocus: { type: ImageCropFocusType, defaultValue: null, }, background: { type: GraphQLString, defaultValue: null, }, }, async resolve(asset, fieldArgs, context) { const { file: { contentType }, } = asset if (contentType.indexOf(`image/`) !== 0) { return null } const { blur, numberOfPrimitives, mode, resizingBehavior, cropFocus, background, } = fieldArgs let { width, height } = fieldArgs if (width && height) { const aspectRatio = height / width width = 256 height = height * aspectRatio } const options = { width: 256, height, resizingBehavior, cropFocus, background, } const absolutePath = await cacheImage(store, asset, options) return generateSqip({ cache, cacheDir, absolutePath, numberOfPrimitives, blur, mode, }) }, }, } }
/** * @fileoverview added by tsickle * @suppress {checkTypes,extraRequire,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ import { Directive, ElementRef, HostListener, Input, IterableDiffers, Renderer2, SkipSelf } from '@angular/core'; import { SortDirection, SortingsService } from 'e2e4'; import { RTList } from './providers/list'; var SortDirective = /** @class */ (function () { function SortDirective(listService, sortingsService, renderer, el, differs) { var _this = this; this.listService = listService; this.sortingsService = sortingsService; this.renderer = renderer; this.sortItemRemovedCallback = function (removedItem) { if (removedItem.item && removedItem.item.fieldName === _this.fieldName) { _this.removeSortClasses(); } }; this.sortItemAddedCallback = function (addedItem) { if (addedItem.item && addedItem.item.fieldName === _this.fieldName) { _this.setSortClasses(addedItem.item); } }; this.sortingsDiffer = differs.find([]).create(null); this.nativeEl = el.nativeElement; } /** * @return {?} */ SortDirective.prototype.ngOnInit = /** * @return {?} */ function () { var _this = this; if (SortDirective.settings.sortableClassName) { this.renderer.addClass(this.nativeEl, SortDirective.settings.sortableClassName); } this.sortingsService.sortings.some(function (sortParameter) { if (sortParameter.fieldName === _this.fieldName) { _this.setSortClasses(sortParameter); return true; } return false; }); }; /** * @param {?} ctrlKeyPressed * @return {?} */ SortDirective.prototype.clickHandler = /** * @param {?} ctrlKeyPressed * @return {?} */ function (ctrlKeyPressed) { if (this.listService.ready && !this.disableSort) { this.sortingsService.setSort(this.fieldName, ctrlKeyPressed); this.listService.reloadData(); } }; /** * @return {?} */ SortDirective.prototype.ngDoCheck = /** * @return {?} */ function () { /** @type {?} */ var changes = this.sortingsDiffer.diff(this.sortingsService.sortings); if (changes) { changes.forEachRemovedItem(this.sortItemRemovedCallback); changes.forEachAddedItem(this.sortItemAddedCallback); } }; /** * @param {?} changes * @return {?} */ SortDirective.prototype.ngOnChanges = /** * @param {?} changes * @return {?} */ function (changes) { if (changes.disableSort && changes.disableSort.currentValue) { this.sortingsService.removeSort(this.fieldName); } }; /** * @private * @return {?} */ SortDirective.prototype.removeSortClasses = /** * @private * @return {?} */ function () { if (SortDirective.settings.sortAscClassName) { this.renderer.removeClass(this.nativeEl, SortDirective.settings.sortAscClassName); } if (SortDirective.settings.sortDescClassName) { this.renderer.removeClass(this.nativeEl, SortDirective.settings.sortDescClassName); } }; /** * @private * @param {?} sortParameter * @return {?} */ SortDirective.prototype.setSortClasses = /** * @private * @param {?} sortParameter * @return {?} */ function (sortParameter) { /** @type {?} */ var direction = sortParameter.direction; if (SortDirective.settings.sortAscClassName) { if (direction === SortDirection.Asc) { this.renderer.addClass(this.nativeEl, SortDirective.settings.sortAscClassName); } else { this.renderer.removeClass(this.nativeEl, SortDirective.settings.sortAscClassName); } } if (SortDirective.settings.sortDescClassName) { if (direction === SortDirection.Desc) { this.renderer.addClass(this.nativeEl, SortDirective.settings.sortDescClassName); } else { this.renderer.removeClass(this.nativeEl, SortDirective.settings.sortDescClassName); } } }; SortDirective.settings = { sortAscClassName: 'rt-sort-asc', sortDescClassName: 'rt-sort-desc', sortableClassName: 'rt-sortable' }; SortDirective.decorators = [ { type: Directive, args: [{ selector: '[rtSort]' },] }, ]; /** @nocollapse */ SortDirective.ctorParameters = function () { return [ { type: RTList, decorators: [{ type: SkipSelf }] }, { type: SortingsService, decorators: [{ type: SkipSelf }] }, { type: Renderer2 }, { type: ElementRef }, { type: IterableDiffers } ]; }; SortDirective.propDecorators = { fieldName: [{ type: Input, args: ['rtSort',] }], disableSort: [{ type: Input }], clickHandler: [{ type: HostListener, args: ['click', ['$event.ctrlKey'],] }] }; return SortDirective; }()); export { SortDirective }; if (false) { /** @type {?} */ SortDirective.settings; /** @type {?} */ SortDirective.prototype.fieldName; /** @type {?} */ SortDirective.prototype.disableSort; /** * @type {?} * @private */ SortDirective.prototype.nativeEl; /** * @type {?} * @private */ SortDirective.prototype.sortingsDiffer; /** * @type {?} * @private */ SortDirective.prototype.sortItemRemovedCallback; /** * @type {?} * @private */ SortDirective.prototype.sortItemAddedCallback; /** * @type {?} * @private */ SortDirective.prototype.listService; /** * @type {?} * @private */ SortDirective.prototype.sortingsService; /** * @type {?} * @private */ SortDirective.prototype.renderer; }
/** @module ember @submodule ember-views */ import { get } from 'ember-metal/property_get'; import { set } from 'ember-metal/property_set'; import { Mixin } from 'ember-metal/mixin'; import TargetActionSupport from 'ember-runtime/mixins/target_action_support'; const KEY_EVENTS = { 13: 'insertNewline', 27: 'cancel' }; /** `TextSupport` is a shared mixin used by both `Ember.TextField` and `Ember.TextArea`. `TextSupport` adds a number of methods that allow you to specify a controller action to invoke when a certain event is fired on your text field or textarea. The specifed controller action would get the current value of the field passed in as the only argument unless the value of the field is empty. In that case, the instance of the field itself is passed in as the only argument. Let's use the pressing of the escape key as an example. If you wanted to invoke a controller action when a user presses the escape key while on your field, you would use the `escape-press` attribute on your field like so: ```handlebars {{! application.hbs}} {{input escape-press='alertUser'}} ``` ```javascript App = Ember.Application.create(); App.ApplicationController = Ember.Controller.extend({ actions: { alertUser: function ( currentValue ) { alert( 'escape pressed, current value: ' + currentValue ); } } }); ``` The following chart is a visual representation of what takes place when the escape key is pressed in this scenario: ``` The Template +---------------------------+ | | | escape-press='alertUser' | | | TextSupport Mixin +----+----------------------+ +-------------------------------+ | | cancel method | | escape button pressed | | +-------------------------------> | checks for the `escape-press` | | attribute and pulls out the | +-------------------------------+ | `alertUser` value | | action name 'alertUser' +-------------------------------+ | sent to controller v Controller +------------------------------------------ + | | | actions: { | | alertUser: function( currentValue ){ | | alert( 'the esc key was pressed!' ) | | } | | } | | | +-------------------------------------------+ ``` Here are the events that we currently support along with the name of the attribute you would need to use on your field. To reiterate, you would use the attribute name like so: ```handlebars {{input attribute-name='controllerAction'}} ``` ``` +--------------------+----------------+ | | | | event | attribute name | +--------------------+----------------+ | new line inserted | insert-newline | | | | | enter key pressed | insert-newline | | | | | cancel key pressed | escape-press | | | | | focusin | focus-in | | | | | focusout | focus-out | | | | | keypress | key-press | | | | | keyup | key-up | | | | | keydown | key-down | +--------------------+----------------+ ``` @class TextSupport @namespace Ember @uses Ember.TargetActionSupport @extends Ember.Mixin @private */ export default Mixin.create(TargetActionSupport, { value: '', attributeBindings: [ 'autocapitalize', 'autocorrect', 'autofocus', 'disabled', 'form', 'maxlength', 'placeholder', 'readonly', 'required', 'selectionDirection', 'spellcheck', 'tabindex', 'title' ], placeholder: null, disabled: false, maxlength: null, init() { this._super(...arguments); this.on('paste', this, this._elementValueDidChange); this.on('cut', this, this._elementValueDidChange); this.on('input', this, this._elementValueDidChange); }, /** The action to be sent when the user presses the return key. This is similar to the `{{action}}` helper, but is fired when the user presses the return key when editing a text field, and sends the value of the field as the context. @property action @type String @default null @private */ action: null, /** The event that should send the action. Options are: * `enter`: the user pressed enter * `keyPress`: the user pressed a key @property onEvent @type String @default enter @private */ onEvent: 'enter', /** Whether the `keyUp` event that triggers an `action` to be sent continues propagating to other views. By default, when the user presses the return key on their keyboard and the text field has an `action` set, the action will be sent to the view's controller and the key event will stop propagating. If you would like parent views to receive the `keyUp` event even after an action has been dispatched, set `bubbles` to true. @property bubbles @type Boolean @default false @private */ bubbles: false, interpretKeyEvents(event) { let map = KEY_EVENTS; let method = map[event.keyCode]; this._elementValueDidChange(); if (method) { return this[method](event); } }, _elementValueDidChange() { // Using readDOMAttr will ensure that HTMLBars knows the last // value. set(this, 'value', this.readDOMAttr('value')); }, change(event) { this._elementValueDidChange(event); }, /** Allows you to specify a controller action to invoke when either the `enter` key is pressed or, in the case of the field being a textarea, when a newline is inserted. To use this method, give your field an `insert-newline` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `insert-newline` attribute, please reference the example near the top of this file. @method insertNewline @param {Event} event @private */ insertNewline(event) { sendAction('enter', this, event); sendAction('insert-newline', this, event); }, /** Allows you to specify a controller action to invoke when the escape button is pressed. To use this method, give your field an `escape-press` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `escape-press` attribute, please reference the example near the top of this file. @method cancel @param {Event} event @private */ cancel(event) { sendAction('escape-press', this, event); }, /** Allows you to specify a controller action to invoke when a field receives focus. To use this method, give your field a `focus-in` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `focus-in` attribute, please reference the example near the top of this file. @method focusIn @param {Event} event @private */ focusIn(event) { sendAction('focus-in', this, event); }, /** Allows you to specify a controller action to invoke when a field loses focus. To use this method, give your field a `focus-out` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `focus-out` attribute, please reference the example near the top of this file. @method focusOut @param {Event} event @private */ focusOut(event) { this._elementValueDidChange(event); sendAction('focus-out', this, event); }, /** Allows you to specify a controller action to invoke when a key is pressed. To use this method, give your field a `key-press` attribute. The value of that attribute should be the name of the action in your controller you that wish to invoke. For an example on how to use the `key-press` attribute, please reference the example near the top of this file. @method keyPress @param {Event} event @private */ keyPress(event) { sendAction('key-press', this, event); }, /** Allows you to specify a controller action to invoke when a key-up event is fired. To use this method, give your field a `key-up` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `key-up` attribute, please reference the example near the top of this file. @method keyUp @param {Event} event @private */ keyUp(event) { this.interpretKeyEvents(event); this.sendAction('key-up', get(this, 'value'), event); }, /** Allows you to specify a controller action to invoke when a key-down event is fired. To use this method, give your field a `key-down` attribute. The value of that attribute should be the name of the action in your controller that you wish to invoke. For an example on how to use the `key-down` attribute, please reference the example near the top of this file. @method keyDown @param {Event} event @private */ keyDown(event) { this.sendAction('key-down', get(this, 'value'), event); } }); // In principle, this shouldn't be necessary, but the legacy // sendAction semantics for TextField are different from // the component semantics so this method normalizes them. function sendAction(eventName, view, event) { let action = get(view, 'attrs.' + eventName) || get(view, eventName); let on = get(view, 'onEvent'); let value = get(view, 'value'); // back-compat support for keyPress as an event name even though // it's also a method name that consumes the event (and therefore // incompatible with sendAction semantics). if (on === eventName || (on === 'keyPress' && eventName === 'key-press')) { view.sendAction('action', value); } view.sendAction(eventName, value); if (action || on === eventName) { if (!get(view, 'bubbles')) { event.stopPropagation(); } } }
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'font', 'he', { fontSize: { label: 'גודל', voiceLabel: 'גודל', panelTitle: 'גודל' }, label: 'גופן', panelTitle: 'גופן', voiceLabel: 'גופן' } );
"use strict"; var path_1 = require('path'); var logger_1 = require('../logger/logger'); var Constants = require('../util/constants'); var helpers_1 = require('../util/helpers'); function calculateUnusedComponents(dependencyMap) { return calculateUnusedComponentsImpl(dependencyMap, process.env[Constants.ENV_VAR_IONIC_ANGULAR_ENTRY_POINT]); } exports.calculateUnusedComponents = calculateUnusedComponents; function calculateUnusedComponentsImpl(dependencyMap, importee) { var filteredMap = filterMap(dependencyMap); processImportTree(filteredMap, importee); calculateUnusedIonicProviders(filteredMap); return generateResults(filteredMap); } exports.calculateUnusedComponentsImpl = calculateUnusedComponentsImpl; function generateResults(dependencyMap) { var toPurgeMap = new Map(); var updatedMap = new Map(); dependencyMap.forEach(function (importeeSet, modulePath) { if ((importeeSet && importeeSet.size > 0) || requiredModule(modulePath)) { logger_1.Logger.debug("[treeshake] generateResults: " + modulePath + " is not purged"); updatedMap.set(modulePath, importeeSet); } else { logger_1.Logger.debug("[treeshake] generateResults: " + modulePath + " is purged"); toPurgeMap.set(modulePath, importeeSet); } }); return { updatedDependencyMap: updatedMap, purgedModules: toPurgeMap }; } function requiredModule(modulePath) { var mainJsFile = helpers_1.changeExtension(process.env[Constants.ENV_APP_ENTRY_POINT], '.js'); var mainTsFile = helpers_1.changeExtension(process.env[Constants.ENV_APP_ENTRY_POINT], '.ts'); var appModule = helpers_1.changeExtension(process.env[Constants.ENV_APP_NG_MODULE_PATH], '.js'); var appModuleNgFactory = getAppModuleNgFactoryPath(); return modulePath === mainJsFile || modulePath === mainTsFile || modulePath === appModule || modulePath === appModuleNgFactory; } function filterMap(dependencyMap) { var filteredMap = new Map(); dependencyMap.forEach(function (importeeSet, modulePath) { if (isIonicComponentOrAppSource(modulePath)) { filteredMap.set(modulePath, importeeSet); } }); return filteredMap; } function processImportTree(dependencyMap, importee) { var importees = []; dependencyMap.forEach(function (importeeSet, modulePath) { if (importeeSet && importeeSet.has(importee)) { importeeSet.delete(importee); // if it importer by an `ngfactory` file, we probably aren't going to be able to purge it var ngFactoryImportee = false; var importeeList = Array.from(importeeSet); for (var _i = 0, importeeList_1 = importeeList; _i < importeeList_1.length; _i++) { var entry = importeeList_1[_i]; if (isNgFactory(entry)) { ngFactoryImportee = true; break; } } if (!ngFactoryImportee) { importees.push(modulePath); } } }); importees.forEach(function (importee) { return processImportTree(dependencyMap, importee); }); } function calculateUnusedIonicProviders(dependencyMap) { logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: beginning to purge providers"); logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to purge action sheet controller"); processIonicProviders(dependencyMap, process.env[Constants.ENV_ACTION_SHEET_CONTROLLER_PATH]); logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to purge alert controller"); processIonicProviders(dependencyMap, process.env[Constants.ENV_ALERT_CONTROLLER_PATH]); logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to loading controller"); processIonicProviders(dependencyMap, process.env[Constants.ENV_LOADING_CONTROLLER_PATH]); logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to modal controller"); processIonicProviders(dependencyMap, process.env[Constants.ENV_MODAL_CONTROLLER_PATH]); logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to picker controller"); processIonicProviders(dependencyMap, process.env[Constants.ENV_PICKER_CONTROLLER_PATH]); logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to popover controller"); processIonicProviders(dependencyMap, process.env[Constants.ENV_POPOVER_CONTROLLER_PATH]); logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to toast controller"); processIonicProviders(dependencyMap, process.env[Constants.ENV_TOAST_CONTROLLER_PATH]); // check if the controllers were deleted, if so, purge the component too logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to action sheet component"); processIonicProviderComponents(dependencyMap, process.env[Constants.ENV_ACTION_SHEET_CONTROLLER_PATH], process.env[Constants.ENV_ACTION_SHEET_COMPONENT_FACTORY_PATH]); logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to alert component"); processIonicProviderComponents(dependencyMap, process.env[Constants.ENV_ALERT_CONTROLLER_PATH], process.env[Constants.ENV_ALERT_COMPONENT_FACTORY_PATH]); logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to loading component"); processIonicProviderComponents(dependencyMap, process.env[Constants.ENV_LOADING_CONTROLLER_PATH], process.env[Constants.ENV_LOADING_COMPONENT_FACTORY_PATH]); logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to modal component"); processIonicProviderComponents(dependencyMap, process.env[Constants.ENV_MODAL_CONTROLLER_PATH], process.env[Constants.ENV_MODAL_COMPONENT_FACTORY_PATH]); logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to picker component"); processIonicProviderComponents(dependencyMap, process.env[Constants.ENV_PICKER_CONTROLLER_PATH], process.env[Constants.ENV_PICKER_COMPONENT_FACTORY_PATH]); logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to popover component"); processIonicProviderComponents(dependencyMap, process.env[Constants.ENV_POPOVER_CONTROLLER_PATH], process.env[Constants.ENV_POPOVER_COMPONENT_FACTORY_PATH]); logger_1.Logger.debug("[treeshake] calculateUnusedIonicProviders: attempting to toast component"); processIonicProviderComponents(dependencyMap, process.env[Constants.ENV_TOAST_CONTROLLER_PATH], process.env[Constants.ENV_TOAST_COMPONENT_FACTORY_PATH]); } function processIonicProviderComponents(dependencyMap, providerPath, componentPath) { var importeeSet = dependencyMap.get(providerPath); if (importeeSet && importeeSet.size === 0) { processIonicProviders(dependencyMap, componentPath); } } function getAppModuleNgFactoryPath() { var appNgModulePath = process.env[Constants.ENV_APP_NG_MODULE_PATH]; var jsVersion = helpers_1.changeExtension(appNgModulePath, '.js'); return helpers_1.convertFilePathToNgFactoryPath(jsVersion); } exports.getAppModuleNgFactoryPath = getAppModuleNgFactoryPath; function processIonicProviders(dependencyMap, providerPath) { var importeeSet = dependencyMap.get(providerPath); var appModuleNgFactoryPath = getAppModuleNgFactoryPath(); // we can only purge an ionic provider if it is imported from one module, which is the AppModuleNgFactory if (importeeSet && importeeSet.size === 1 && importeeSet.has(appModuleNgFactoryPath)) { logger_1.Logger.debug("[treeshake] processIonicProviders: Purging " + providerPath); importeeSet.delete(appModuleNgFactoryPath); // loop over the dependency map and remove this provider from importee sets processImportTreeForProviders(dependencyMap, providerPath); } } function processImportTreeForProviders(dependencyMap, importee) { var importees = []; dependencyMap.forEach(function (importeeSet, modulePath) { if (importeeSet.has(importee)) { importeeSet.delete(importee); importees.push(modulePath); } }); importees.forEach(function (importee) { return processImportTreeForProviders(dependencyMap, importee); }); } function isIonicComponentOrAppSource(modulePath) { // for now, just use a simple filter of if a file is in ionic-angular/components var ionicAngularComponentDir = path_1.join(process.env[Constants.ENV_VAR_IONIC_ANGULAR_DIR], 'components'); var srcDir = process.env[Constants.ENV_VAR_SRC_DIR]; return modulePath.indexOf(ionicAngularComponentDir) >= 0 || modulePath.indexOf(srcDir) >= 0; } exports.isIonicComponentOrAppSource = isIonicComponentOrAppSource; function isNgFactory(modulePath) { return modulePath.indexOf('.ngfactory.') >= 0; } exports.isNgFactory = isNgFactory; function purgeUnusedImportsAndExportsFromIndex(indexFilePath, indexFileContent, modulePathsToPurge) { logger_1.Logger.debug("[treeshake] purgeUnusedImportsFromIndex: Starting to purge import/exports ... "); for (var _i = 0, modulePathsToPurge_1 = modulePathsToPurge; _i < modulePathsToPurge_1.length; _i++) { var modulePath = modulePathsToPurge_1[_i]; // I cannot get the './' prefix to show up when using path api logger_1.Logger.debug("[treeshake] purgeUnusedImportsFromIndex: Removing " + modulePath + " from " + indexFilePath); var extensionless = helpers_1.changeExtension(modulePath, ''); var relativeImportPath = './' + path_1.relative(path_1.dirname(indexFilePath), extensionless); var importPath = helpers_1.toUnixPath(relativeImportPath); logger_1.Logger.debug("[treeshake] purgeUnusedImportsFromIndex: Removing imports with path " + importPath); var importRegex = generateImportRegex(importPath); // replace the import if it's found var results = null; while ((results = importRegex.exec(indexFileContent)) && results.length) { indexFileContent = indexFileContent.replace(importRegex, ''); } results = null; var exportRegex = generateExportRegex(importPath); logger_1.Logger.debug("[treeshake] purgeUnusedImportsFromIndex: Removing exports with path " + importPath); while ((results = exportRegex.exec(indexFileContent)) && results.length) { indexFileContent = indexFileContent.replace(exportRegex, ''); } } logger_1.Logger.debug("[treeshake] purgeUnusedImportsFromIndex: Starting to purge import/exports ... DONE"); return indexFileContent; } exports.purgeUnusedImportsAndExportsFromIndex = purgeUnusedImportsAndExportsFromIndex; function generateImportRegex(relativeImportPath) { var cleansedString = helpers_1.escapeStringForRegex(relativeImportPath); return new RegExp("import.*?{(.+)}.*?from.*?'" + cleansedString + "';"); } function generateExportRegex(relativeExportPath) { var cleansedString = helpers_1.escapeStringForRegex(relativeExportPath); return new RegExp("export.*?{(.+)}.*?from.*?'" + cleansedString + "';"); } function purgeComponentNgFactoryImportAndUsage(appModuleNgFactoryPath, appModuleNgFactoryContent, componentFactoryPath) { logger_1.Logger.debug("[treeshake] purgeComponentNgFactoryImportAndUsage: Starting to purge component ngFactory import/export ..."); var extensionlessComponentFactoryPath = helpers_1.changeExtension(componentFactoryPath, ''); var relativeImportPath = path_1.relative(path_1.dirname(appModuleNgFactoryPath), extensionlessComponentFactoryPath); var importPath = helpers_1.toUnixPath(relativeImportPath); logger_1.Logger.debug("[treeshake] purgeComponentNgFactoryImportAndUsage: Purging imports from " + importPath); var importRegex = generateWildCardImportRegex(importPath); var results = importRegex.exec(appModuleNgFactoryContent); if (results && results.length >= 2) { appModuleNgFactoryContent = appModuleNgFactoryContent.replace(importRegex, ''); var namedImport = results[1].trim(); logger_1.Logger.debug("[treeshake] purgeComponentNgFactoryImportAndUsage: Purging code using named import " + namedImport); var purgeFromConstructor = generateRemoveComponentFromConstructorRegex(namedImport); appModuleNgFactoryContent = appModuleNgFactoryContent.replace(purgeFromConstructor, ''); } logger_1.Logger.debug("[treeshake] purgeComponentNgFactoryImportAndUsage: Starting to purge component ngFactory import/export ... DONE"); return appModuleNgFactoryContent; } exports.purgeComponentNgFactoryImportAndUsage = purgeComponentNgFactoryImportAndUsage; function purgeProviderControllerImportAndUsage(appModuleNgFactoryPath, appModuleNgFactoryContent, providerPath) { logger_1.Logger.debug("[treeshake] purgeProviderControllerImportAndUsage: Starting to purge provider controller and usage ..."); var extensionlessComponentFactoryPath = helpers_1.changeExtension(providerPath, ''); var relativeImportPath = path_1.relative(path_1.dirname(process.env[Constants.ENV_VAR_IONIC_ANGULAR_DIR]), extensionlessComponentFactoryPath); var importPath = helpers_1.toUnixPath(relativeImportPath); logger_1.Logger.debug("[treeshake] purgeProviderControllerImportAndUsage: Looking for imports from " + importPath); var importRegex = generateWildCardImportRegex(importPath); var results = importRegex.exec(appModuleNgFactoryContent); if (results && results.length >= 2) { var namedImport = results[1].trim(); // purge the getter var purgeGetterRegEx = generateRemoveGetterFromImportRegex(namedImport); var purgeGetterResults = purgeGetterRegEx.exec(appModuleNgFactoryContent); var purgeIfRegEx = generateRemoveIfStatementRegex(namedImport); var purgeIfResults = purgeIfRegEx.exec(appModuleNgFactoryContent); if (purgeGetterResults && purgeIfResults) { logger_1.Logger.debug("[treeshake] purgeProviderControllerImportAndUsage: Purging imports " + namedImport); appModuleNgFactoryContent = appModuleNgFactoryContent.replace(importRegex, ''); logger_1.Logger.debug("[treeshake] purgeProviderControllerImportAndUsage: Purging getter logic using " + namedImport); var getterContentToReplace = purgeGetterResults[0]; var newGetterContent = "/*" + getterContentToReplace + "*/"; appModuleNgFactoryContent = appModuleNgFactoryContent.replace(getterContentToReplace, newGetterContent); logger_1.Logger.debug("[treeshake] purgeProviderControllerImportAndUsage: Purging additional logic using " + namedImport); var purgeIfContentToReplace = purgeIfResults[0]; var newPurgeIfContent = "/*" + purgeIfContentToReplace + "*/"; appModuleNgFactoryContent = appModuleNgFactoryContent.replace(purgeIfContentToReplace, newPurgeIfContent); } } logger_1.Logger.debug("[treeshake] purgeProviderControllerImportAndUsage: Starting to purge provider controller and usage ... DONE"); return appModuleNgFactoryContent; } exports.purgeProviderControllerImportAndUsage = purgeProviderControllerImportAndUsage; function purgeProviderClassNameFromIonicModuleForRoot(indexFileContent, providerClassName) { logger_1.Logger.debug("[treeshake] purgeProviderClassNameFromIonicModuleForRoot: Purging reference in the ionicModule forRoot method ..."); var regex = generateIonicModulePurgeProviderRegex(providerClassName); indexFileContent = indexFileContent.replace(regex, ''); logger_1.Logger.debug("[treeshake] purgeProviderClassNameFromIonicModuleForRoot: Purging reference in the ionicModule forRoot method ... DONE"); return indexFileContent; } exports.purgeProviderClassNameFromIonicModuleForRoot = purgeProviderClassNameFromIonicModuleForRoot; function generateWildCardImportRegex(relativeImportPath) { var cleansedString = helpers_1.escapeStringForRegex(relativeImportPath); return new RegExp("import.*?as(.*?)from '" + cleansedString + "';"); } function generateRemoveComponentFromConstructorRegex(namedImport) { return new RegExp(namedImport + "..*?,"); } function generateRemoveGetterFromImportRegex(namedImport) { var regexString = "(get _(.*?)_(\\d*)\\(\\) {([\\s\\S][^}]*?)" + namedImport + "([\\s\\S]*?)}([\\s\\S]*?)})"; return new RegExp(regexString); } exports.generateRemoveGetterFromImportRegex = generateRemoveGetterFromImportRegex; function generateRemoveIfStatementRegex(namedImport) { return new RegExp("if \\(\\(token === " + namedImport + ".([\\S]*?)\\)\\) {([\\S\\s]*?)}", "gm"); } function generateIonicModulePurgeProviderRegex(className) { return new RegExp("(^([\\s]*)" + className + ",\\n)", "m"); }
'use strict' const assert = require('assert') const childProcess = require('child_process') const electronPackager = require('electron-packager') const fs = require('fs-extra') const includePathInPackagedApp = require('./include-path-in-packaged-app') const getLicenseText = require('./get-license-text') const path = require('path') const spawnSync = require('./spawn-sync') const CONFIG = require('../config') module.exports = function () { const appName = getAppName() console.log(`Running electron-packager on ${CONFIG.intermediateAppPath} with app name "${appName}"`) return runPackager({ 'app-bundle-id': 'com.github.atom', 'app-copyright': `Copyright © 2014-${(new Date()).getFullYear()} GitHub, Inc. All rights reserved.`, 'app-version': CONFIG.appMetadata.version, 'arch': process.platform === 'darwin' ? 'x64' : process.arch, // OS X is 64-bit only 'asar': {unpack: buildAsarUnpackGlobExpression()}, 'build-version': CONFIG.appMetadata.version, 'download': {cache: CONFIG.electronDownloadPath}, 'dir': CONFIG.intermediateAppPath, 'extend-info': path.join(CONFIG.repositoryRootPath, 'resources', 'mac', 'atom-Info.plist'), 'helper-bundle-id': 'com.github.atom.helper', 'icon': getIcon(), 'name': appName, 'out': CONFIG.buildOutputPath, 'overwrite': true, 'platform': process.platform, 'version': CONFIG.appMetadata.electronVersion, 'version-string': { 'CompanyName': 'GitHub, Inc.', 'FileDescription': 'Atom', 'ProductName': 'Atom' } }).then((packagedAppPath) => { let bundledResourcesPath if (process.platform === 'darwin') { bundledResourcesPath = path.join(packagedAppPath, 'Contents', 'Resources') setAtomHelperVersion(packagedAppPath) } else if (process.platform === 'linux') { bundledResourcesPath = path.join(packagedAppPath, 'resources') chmodNodeFiles(packagedAppPath) } else { bundledResourcesPath = path.join(packagedAppPath, 'resources') } return copyNonASARResources(packagedAppPath, bundledResourcesPath).then(() => { console.log(`Application bundle created at ${packagedAppPath}`) return packagedAppPath }) }) } function copyNonASARResources (packagedAppPath, bundledResourcesPath) { console.log(`Copying non-ASAR resources to ${bundledResourcesPath}`) fs.copySync( path.join(CONFIG.repositoryRootPath, 'apm', 'node_modules', 'atom-package-manager'), path.join(bundledResourcesPath, 'app', 'apm'), {filter: includePathInPackagedApp} ) if (process.platform !== 'win32') { // Existing symlinks on user systems point to an outdated path, so just symlink it to the real location of the apm binary. // TODO: Change command installer to point to appropriate path and remove this fallback after a few releases. fs.symlinkSync(path.join('..', '..', 'bin', 'apm'), path.join(bundledResourcesPath, 'app', 'apm', 'node_modules', '.bin', 'apm')) fs.copySync(path.join(CONFIG.repositoryRootPath, 'atom.sh'), path.join(bundledResourcesPath, 'app', 'atom.sh')) } if (process.platform === 'darwin') { fs.copySync(path.join(CONFIG.repositoryRootPath, 'resources', 'mac', 'file.icns'), path.join(bundledResourcesPath, 'file.icns')) } else if (process.platform === 'linux') { fs.copySync(path.join(CONFIG.repositoryRootPath, 'resources', 'app-icons', CONFIG.channel, 'png', '1024.png'), path.join(packagedAppPath, 'atom.png')) } else if (process.platform === 'win32') { [ 'atom.cmd', 'atom.sh', 'atom.js', 'apm.cmd', 'apm.sh', 'file.ico', 'folder.ico' ] .forEach(file => fs.copySync(path.join('resources', 'win', file), path.join(bundledResourcesPath, 'cli', file))) } console.log(`Writing LICENSE.md to ${bundledResourcesPath}`) return getLicenseText().then((licenseText) => { fs.writeFileSync(path.join(bundledResourcesPath, 'LICENSE.md'), licenseText) }) } function setAtomHelperVersion (packagedAppPath) { const frameworksPath = path.join(packagedAppPath, 'Contents', 'Frameworks') const helperPListPath = path.join(frameworksPath, 'Atom Helper.app', 'Contents', 'Info.plist') console.log(`Setting Atom Helper Version for ${helperPListPath}`) spawnSync('/usr/libexec/PlistBuddy', ['-c', `Add CFBundleVersion string ${CONFIG.appMetadata.version}`, helperPListPath]) spawnSync('/usr/libexec/PlistBuddy', ['-c', `Add CFBundleShortVersionString string ${CONFIG.appMetadata.version}`, helperPListPath]) } function chmodNodeFiles (packagedAppPath) { console.log(`Changing permissions for node files in ${packagedAppPath}`) childProcess.execSync(`find "${packagedAppPath}" -type f -name *.node -exec chmod a-x {} \\;`) } function buildAsarUnpackGlobExpression () { const unpack = [ '*.node', 'ctags-config', 'ctags-darwin', 'ctags-linux', 'ctags-win32.exe', path.join('**', 'node_modules', 'spellchecker', '**'), path.join('**', 'node_modules', 'dugite', 'git', '**'), path.join('**', 'node_modules', 'github', 'bin', '**'), path.join('**', 'resources', 'atom.png') ] return `{${unpack.join(',')}}` } function getAppName () { if (process.platform === 'darwin') { return CONFIG.appName } else { return 'atom' } } function getIcon () { switch (process.platform) { case 'darwin': return path.join(CONFIG.repositoryRootPath, 'resources', 'app-icons', CONFIG.channel, 'atom.icns') case 'linux': // Don't pass an icon, as the dock/window list icon is set via the icon // option in the BrowserWindow constructor in atom-window.coffee. return null default: return path.join(CONFIG.repositoryRootPath, 'resources', 'app-icons', CONFIG.channel, 'atom.ico') } } function runPackager (options) { return new Promise((resolve, reject) => { electronPackager(options, (err, packageOutputDirPaths) => { if (err) { reject(err) throw new Error(err) } else { assert(packageOutputDirPaths.length === 1, 'Generated more than one electron application!') const packagedAppPath = renamePackagedAppDir(packageOutputDirPaths[0]) resolve(packagedAppPath) } }) }) } function renamePackagedAppDir (packageOutputDirPath) { let packagedAppPath if (process.platform === 'darwin') { const appBundleName = getAppName() + '.app' packagedAppPath = path.join(CONFIG.buildOutputPath, appBundleName) if (fs.existsSync(packagedAppPath)) fs.removeSync(packagedAppPath) fs.renameSync(path.join(packageOutputDirPath, appBundleName), packagedAppPath) } else if (process.platform === 'linux') { const appName = CONFIG.channel !== 'stable' ? `atom-${CONFIG.channel}` : 'atom' let architecture if (process.arch === 'ia32') { architecture = 'i386' } else if (process.arch === 'x64') { architecture = 'amd64' } else { architecture = process.arch } packagedAppPath = path.join(CONFIG.buildOutputPath, `${appName}-${CONFIG.appMetadata.version}-${architecture}`) if (fs.existsSync(packagedAppPath)) fs.removeSync(packagedAppPath) fs.renameSync(packageOutputDirPath, packagedAppPath) } else { packagedAppPath = path.join(CONFIG.buildOutputPath, CONFIG.appName) if (process.platform === 'win32' && process.arch !== 'ia32') { packagedAppPath += ` ${process.arch}` } if (fs.existsSync(packagedAppPath)) fs.removeSync(packagedAppPath) fs.renameSync(packageOutputDirPath, packagedAppPath) } return packagedAppPath }
import { Matrix3, Vector3, Color } from 'three'; /** * https://github.com/gkjohnson/ply-exporter-js * * Usage: * const exporter = new PLYExporter(); * * // second argument is a list of options * exporter.parse(mesh, data => console.log(data), { binary: true, excludeAttributes: [ 'color' ], littleEndian: true }); * * Format Definition: * http://paulbourke.net/dataformats/ply/ */ class PLYExporter { parse( object, onDone, options ) { if ( onDone && typeof onDone === 'object' ) { console.warn( 'THREE.PLYExporter: The options parameter is now the third argument to the "parse" function. See the documentation for the new API.' ); options = onDone; onDone = undefined; } // Iterate over the valid meshes in the object function traverseMeshes( cb ) { object.traverse( function ( child ) { if ( child.isMesh === true ) { const mesh = child; const geometry = mesh.geometry; if ( geometry.isBufferGeometry !== true ) { throw new Error( 'THREE.PLYExporter: Geometry is not of type THREE.BufferGeometry.' ); } if ( geometry.hasAttribute( 'position' ) === true ) { cb( mesh, geometry ); } } } ); } // Default options const defaultOptions = { binary: false, excludeAttributes: [], // normal, uv, color, index littleEndian: false }; options = Object.assign( defaultOptions, options ); const excludeAttributes = options.excludeAttributes; let includeNormals = false; let includeColors = false; let includeUVs = false; // count the vertices, check which properties are used, // and cache the BufferGeometry let vertexCount = 0; let faceCount = 0; object.traverse( function ( child ) { if ( child.isMesh === true ) { const mesh = child; const geometry = mesh.geometry; if ( geometry.isBufferGeometry !== true ) { throw new Error( 'THREE.PLYExporter: Geometry is not of type THREE.BufferGeometry.' ); } const vertices = geometry.getAttribute( 'position' ); const normals = geometry.getAttribute( 'normal' ); const uvs = geometry.getAttribute( 'uv' ); const colors = geometry.getAttribute( 'color' ); const indices = geometry.getIndex(); if ( vertices === undefined ) { return; } vertexCount += vertices.count; faceCount += indices ? indices.count / 3 : vertices.count / 3; if ( normals !== undefined ) includeNormals = true; if ( uvs !== undefined ) includeUVs = true; if ( colors !== undefined ) includeColors = true; } } ); const tempColor = new Color(); const includeIndices = excludeAttributes.indexOf( 'index' ) === - 1; includeNormals = includeNormals && excludeAttributes.indexOf( 'normal' ) === - 1; includeColors = includeColors && excludeAttributes.indexOf( 'color' ) === - 1; includeUVs = includeUVs && excludeAttributes.indexOf( 'uv' ) === - 1; if ( includeIndices && faceCount !== Math.floor( faceCount ) ) { // point cloud meshes will not have an index array and may not have a // number of vertices that is divisble by 3 (and therefore representable // as triangles) console.error( 'PLYExporter: Failed to generate a valid PLY file with triangle indices because the ' + 'number of indices is not divisible by 3.' ); return null; } const indexByteCount = 4; let header = 'ply\n' + `format ${ options.binary ? ( options.littleEndian ? 'binary_little_endian' : 'binary_big_endian' ) : 'ascii' } 1.0\n` + `element vertex ${vertexCount}\n` + // position 'property float x\n' + 'property float y\n' + 'property float z\n'; if ( includeNormals === true ) { // normal header += 'property float nx\n' + 'property float ny\n' + 'property float nz\n'; } if ( includeUVs === true ) { // uvs header += 'property float s\n' + 'property float t\n'; } if ( includeColors === true ) { // colors header += 'property uchar red\n' + 'property uchar green\n' + 'property uchar blue\n'; } if ( includeIndices === true ) { // faces header += `element face ${faceCount}\n` + 'property list uchar int vertex_index\n'; } header += 'end_header\n'; // Generate attribute data const vertex = new Vector3(); const normalMatrixWorld = new Matrix3(); let result = null; if ( options.binary === true ) { // Binary File Generation const headerBin = new TextEncoder().encode( header ); // 3 position values at 4 bytes // 3 normal values at 4 bytes // 3 color channels with 1 byte // 2 uv values at 4 bytes const vertexListLength = vertexCount * ( 4 * 3 + ( includeNormals ? 4 * 3 : 0 ) + ( includeColors ? 3 : 0 ) + ( includeUVs ? 4 * 2 : 0 ) ); // 1 byte shape desciptor // 3 vertex indices at ${indexByteCount} bytes const faceListLength = includeIndices ? faceCount * ( indexByteCount * 3 + 1 ) : 0; const output = new DataView( new ArrayBuffer( headerBin.length + vertexListLength + faceListLength ) ); new Uint8Array( output.buffer ).set( headerBin, 0 ); let vOffset = headerBin.length; let fOffset = headerBin.length + vertexListLength; let writtenVertices = 0; traverseMeshes( function ( mesh, geometry ) { const vertices = geometry.getAttribute( 'position' ); const normals = geometry.getAttribute( 'normal' ); const uvs = geometry.getAttribute( 'uv' ); const colors = geometry.getAttribute( 'color' ); const indices = geometry.getIndex(); normalMatrixWorld.getNormalMatrix( mesh.matrixWorld ); for ( let i = 0, l = vertices.count; i < l; i ++ ) { vertex.x = vertices.getX( i ); vertex.y = vertices.getY( i ); vertex.z = vertices.getZ( i ); vertex.applyMatrix4( mesh.matrixWorld ); // Position information output.setFloat32( vOffset, vertex.x, options.littleEndian ); vOffset += 4; output.setFloat32( vOffset, vertex.y, options.littleEndian ); vOffset += 4; output.setFloat32( vOffset, vertex.z, options.littleEndian ); vOffset += 4; // Normal information if ( includeNormals === true ) { if ( normals != null ) { vertex.x = normals.getX( i ); vertex.y = normals.getY( i ); vertex.z = normals.getZ( i ); vertex.applyMatrix3( normalMatrixWorld ).normalize(); output.setFloat32( vOffset, vertex.x, options.littleEndian ); vOffset += 4; output.setFloat32( vOffset, vertex.y, options.littleEndian ); vOffset += 4; output.setFloat32( vOffset, vertex.z, options.littleEndian ); vOffset += 4; } else { output.setFloat32( vOffset, 0, options.littleEndian ); vOffset += 4; output.setFloat32( vOffset, 0, options.littleEndian ); vOffset += 4; output.setFloat32( vOffset, 0, options.littleEndian ); vOffset += 4; } } // UV information if ( includeUVs === true ) { if ( uvs != null ) { output.setFloat32( vOffset, uvs.getX( i ), options.littleEndian ); vOffset += 4; output.setFloat32( vOffset, uvs.getY( i ), options.littleEndian ); vOffset += 4; } else { output.setFloat32( vOffset, 0, options.littleEndian ); vOffset += 4; output.setFloat32( vOffset, 0, options.littleEndian ); vOffset += 4; } } // Color information if ( includeColors === true ) { if ( colors != null ) { tempColor .fromBufferAttribute( colors, i ) .convertLinearToSRGB(); output.setUint8( vOffset, Math.floor( tempColor.r * 255 ) ); vOffset += 1; output.setUint8( vOffset, Math.floor( tempColor.g * 255 ) ); vOffset += 1; output.setUint8( vOffset, Math.floor( tempColor.b * 255 ) ); vOffset += 1; } else { output.setUint8( vOffset, 255 ); vOffset += 1; output.setUint8( vOffset, 255 ); vOffset += 1; output.setUint8( vOffset, 255 ); vOffset += 1; } } } if ( includeIndices === true ) { // Create the face list if ( indices !== null ) { for ( let i = 0, l = indices.count; i < l; i += 3 ) { output.setUint8( fOffset, 3 ); fOffset += 1; output.setUint32( fOffset, indices.getX( i + 0 ) + writtenVertices, options.littleEndian ); fOffset += indexByteCount; output.setUint32( fOffset, indices.getX( i + 1 ) + writtenVertices, options.littleEndian ); fOffset += indexByteCount; output.setUint32( fOffset, indices.getX( i + 2 ) + writtenVertices, options.littleEndian ); fOffset += indexByteCount; } } else { for ( let i = 0, l = vertices.count; i < l; i += 3 ) { output.setUint8( fOffset, 3 ); fOffset += 1; output.setUint32( fOffset, writtenVertices + i, options.littleEndian ); fOffset += indexByteCount; output.setUint32( fOffset, writtenVertices + i + 1, options.littleEndian ); fOffset += indexByteCount; output.setUint32( fOffset, writtenVertices + i + 2, options.littleEndian ); fOffset += indexByteCount; } } } // Save the amount of verts we've already written so we can offset // the face index on the next mesh writtenVertices += vertices.count; } ); result = output.buffer; } else { // Ascii File Generation // count the number of vertices let writtenVertices = 0; let vertexList = ''; let faceList = ''; traverseMeshes( function ( mesh, geometry ) { const vertices = geometry.getAttribute( 'position' ); const normals = geometry.getAttribute( 'normal' ); const uvs = geometry.getAttribute( 'uv' ); const colors = geometry.getAttribute( 'color' ); const indices = geometry.getIndex(); normalMatrixWorld.getNormalMatrix( mesh.matrixWorld ); // form each line for ( let i = 0, l = vertices.count; i < l; i ++ ) { vertex.x = vertices.getX( i ); vertex.y = vertices.getY( i ); vertex.z = vertices.getZ( i ); vertex.applyMatrix4( mesh.matrixWorld ); // Position information let line = vertex.x + ' ' + vertex.y + ' ' + vertex.z; // Normal information if ( includeNormals === true ) { if ( normals != null ) { vertex.x = normals.getX( i ); vertex.y = normals.getY( i ); vertex.z = normals.getZ( i ); vertex.applyMatrix3( normalMatrixWorld ).normalize(); line += ' ' + vertex.x + ' ' + vertex.y + ' ' + vertex.z; } else { line += ' 0 0 0'; } } // UV information if ( includeUVs === true ) { if ( uvs != null ) { line += ' ' + uvs.getX( i ) + ' ' + uvs.getY( i ); } else { line += ' 0 0'; } } // Color information if ( includeColors === true ) { if ( colors != null ) { tempColor .fromBufferAttribute( colors, i ) .convertLinearToSRGB(); line += ' ' + Math.floor( tempColor.r * 255 ) + ' ' + Math.floor( tempColor.g * 255 ) + ' ' + Math.floor( tempColor.b * 255 ); } else { line += ' 255 255 255'; } } vertexList += line + '\n'; } // Create the face list if ( includeIndices === true ) { if ( indices !== null ) { for ( let i = 0, l = indices.count; i < l; i += 3 ) { faceList += `3 ${ indices.getX( i + 0 ) + writtenVertices }`; faceList += ` ${ indices.getX( i + 1 ) + writtenVertices }`; faceList += ` ${ indices.getX( i + 2 ) + writtenVertices }\n`; } } else { for ( let i = 0, l = vertices.count; i < l; i += 3 ) { faceList += `3 ${ writtenVertices + i } ${ writtenVertices + i + 1 } ${ writtenVertices + i + 2 }\n`; } } faceCount += indices ? indices.count / 3 : vertices.count / 3; } writtenVertices += vertices.count; } ); result = `${ header }${vertexList}${ includeIndices ? `${faceList}\n` : '\n' }`; } if ( typeof onDone === 'function' ) requestAnimationFrame( () => onDone( result ) ); return result; } } export { PLYExporter };
import { JOSENotSupported } from '../util/errors.js'; const bitLengths = new Map([ ['A128CBC-HS256', 256], ['A128GCM', 128], ['A192CBC-HS384', 384], ['A192GCM', 192], ['A256CBC-HS512', 512], ['A256GCM', 256], ]); const factory = (random) => (alg) => { const bitLength = bitLengths.get(alg); if (!bitLength) { throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg}`); } return random(new Uint8Array(bitLength >> 3)); }; export default factory; export { bitLengths };
var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; (function (factory) { if (typeof module === 'object' && typeof module.exports === 'object') { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === 'function' && define.amd) { define(["require", "exports", '@angular/core', '../../config/config', '../ion'], factory); } })(function (require, exports) { "use strict"; var core_1 = require('@angular/core'); var config_1 = require('../../config/config'); var ion_1 = require('../ion'); /** * @name Badge * @module ionic * @description * Badges are simple components in Ionic containing numbers or text. You can display a badge to indicate that there is new information associated with the item it is on. * @see {@link /docs/v2/components/#badges Badges Component Docs} */ var Badge = (function (_super) { __extends(Badge, _super); function Badge(config, elementRef, renderer) { _super.call(this, config, elementRef, renderer, 'badge'); } Object.defineProperty(Badge.prototype, "color", { /** * @input {string} The color to use from your Sass `$colors` map. * Default options are: `"primary"`, `"secondary"`, `"danger"`, `"light"`, and `"dark"`. * For more information, see [Theming your App](/docs/v2/theming/theming-your-app). */ set: function (val) { this._setColor(val); }, enumerable: true, configurable: true }); Object.defineProperty(Badge.prototype, "mode", { /** * @input {string} The mode determines which platform styles to use. * Possible values are: `"ios"`, `"md"`, or `"wp"`. * For more information, see [Platform Styles](/docs/v2/theming/platform-specific-styles). */ set: function (val) { this._setMode(val); }, enumerable: true, configurable: true }); Badge.decorators = [ { type: core_1.Directive, args: [{ selector: 'ion-badge' },] }, ]; /** @nocollapse */ Badge.ctorParameters = [ { type: config_1.Config, }, { type: core_1.ElementRef, }, { type: core_1.Renderer, }, ]; Badge.propDecorators = { 'color': [{ type: core_1.Input },], 'mode': [{ type: core_1.Input },], }; return Badge; }(ion_1.Ion)); exports.Badge = Badge; }); //# sourceMappingURL=badge.js.map
const merge = require('webpack-merge'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); const devConfig = require('./webpack.extension-dev.js'); module.exports = merge(devConfig, { mode: 'production', devtool: false, plugins: [ new UglifyJsPlugin() ] });
/* Siesta 2.0.5 Copyright(c) 2009-2013 Bryntum AB http://bryntum.com/contact http://bryntum.com/products/siesta/license */ /** @class Siesta.Test.Action.Type @extends Siesta.Test.Action @mixin Siesta.Test.Action.Role.HasTarget This action will {@link Siesta.Test.Browser#type type} the provided {@link #text} into the provided {@link #target}. For more information about how you can type special characters and hold special keys such as ALT or SHIFT, please see the docs for the {@link Siesta.Test.Browser#type type} method. The target can be a DOM element or, in case you are using the Siesta.Test.ExtJS class - an instance of a Ext.Component (field component for example). This action can be included in a `t.chain` call with the "type" shortcut. **Note** that unlike other actions, in its compact form the value of the "type" property should contain the text to type, not the target of action. t.chain( { // "type" into the currently focused DOM element type : 'Some text[ENTER]' }, // or { action : 'type', target : someDOMElement, text : 'Some text', options : { shiftKey : true } }, // or { // NOTE: "type" contains text to type, not the action target as in other actions type : 'Some text', target : someDOMElement } ); */ Class('Siesta.Test.Action.Type', { isa : Siesta.Test.Action, does : Siesta.Test.Action.Role.HasTarget, has : { requiredTestMethod : 'type', /** * @cfg {String} text * * The text to type into the target */ text : '', /** * @cfg {Object} options * * Any options that will be used when simulating the event. For information about possible * config options, please see: <https://developer.mozilla.org/en-US/docs/DOM/event.initMouseEvent> */ options : null }, methods : { process : function () { // By default use the current focused element as target this.target = this.target || this.test.activeElement(); // additional "getTarget" to allow functions as "target" value this.test.type(this.getTarget(), this.text, this.next, null, this.options); } } }); Siesta.Test.ActionRegistry().registerAction('type', Siesta.Test.Action.Type)
import userActionCreators from './userActionCreators'; export default { userActionCreators: userActionCreators };
/* Plugin: jQuery Parallax Version 1.1.3 Author: Ian Lunn Twitter: @IanLunn Author URL: http://www.ianlunn.co.uk/ Plugin URL: http://www.ianlunn.co.uk/plugins/jquery-parallax/ Dual licensed under the MIT and GPL licenses: http://www.opensource.org/licenses/mit-license.php http://www.gnu.org/licenses/gpl.html */ (function( $ ){ var $window = $(window); var windowHeight = $window.height(); $window.resize(function () { windowHeight = $window.height(); }); $.fn.parallax = function(xpos, speedFactor, outerHeight) { var $this = $(this); var getHeight; var firstTop; var paddingTop = 0; //get the starting position of each element to have parallax applied to it $this.each(function(){ firstTop = $this.offset().top; }); if (outerHeight) { getHeight = function(jqo) { return jqo.outerHeight(true); }; } else { getHeight = function(jqo) { return jqo.height(); }; } // setup defaults if arguments aren't specified if (arguments.length < 1 || xpos === null) xpos = "50%"; if (arguments.length < 2 || speedFactor === null) speedFactor = 0.1; if (arguments.length < 3 || outerHeight === null) outerHeight = true; // function to be called whenever the window is scrolled or resized function update(){ var pos = $window.scrollTop(); $this.each(function(){ var $element = $(this); var top = $element.offset().top; var height = getHeight($element); // Check if totally above or totally below viewport if (top + height < pos || top > pos + windowHeight) { return; } $this.css('backgroundPosition', xpos + " " + Math.round((firstTop - pos) * speedFactor) + "px"); }); } $window.bind('scroll', update).resize(function() { $this.each(function(){ firstTop = $this.offset().top; }); update(); }); update(); }; })(jQuery);
Package.describe({ summary: "Send email messages", version: "1.0.12" }); Npm.depends({ // Pinned at older version. 0.1.16+ uses mimelib, not mimelib-noiconv which is // much bigger. We need a better solution. mailcomposer: "0.1.15", simplesmtp: "0.3.10", "stream-buffers": "0.2.5"}); Package.onUse(function (api) { api.use('underscore', 'server'); api.export(['Email', 'EmailInternals'], 'server'); api.export('EmailTest', 'server', {testOnly: true}); api.addFiles('email.js', 'server'); }); Package.onTest(function (api) { api.use('email', 'server'); api.use('tinytest'); api.addFiles('email_tests.js', 'server'); });
/** * Select2 Czech translation. * * Author: Michal Marek <ahoj@michal-marek.cz> * Author - sklonovani: David Vallner <david@vallner.net> */ (function ($) { "use strict"; // use text for the numbers 2 through 4 var smallNumbers = { 2: function(masc) { return (masc ? "dva" : "dvě"); }, 3: function() { return "tři"; }, 4: function() { return "čtyři"; } } $.fn.select2.locales['cs'] = { formatNoMatches: function () { return "Nenalezeny žádné položky"; }, formatInputTooShort: function (input, min) { var n = min - input.length; if (n == 1) { return "Prosím zadejte ještě jeden znak"; } else if (n <= 4) { return "Prosím zadejte ještě další "+smallNumbers[n](true)+" znaky"; } else { return "Prosím zadejte ještě dalších "+n+" znaků"; } }, formatInputTooLong: function (input, max) { var n = input.length - max; if (n == 1) { return "Prosím zadejte o jeden znak méně"; } else if (n <= 4) { return "Prosím zadejte o "+smallNumbers[n](true)+" znaky méně"; } else { return "Prosím zadejte o "+n+" znaků méně"; } }, formatSelectionTooBig: function (limit) { if (limit == 1) { return "Můžete zvolit jen jednu položku"; } else if (limit <= 4) { return "Můžete zvolit maximálně "+smallNumbers[limit](false)+" položky"; } else { return "Můžete zvolit maximálně "+limit+" položek"; } }, formatLoadMore: function (pageNumber) { return "Načítají se další výsledky…"; }, formatSearching: function () { return "Vyhledávání…"; } }; $.extend($.fn.select2.defaults, $.fn.select2.locales['cs']); })(jQuery);
(function Screen($angular) { "use strict"; /** * @directive viScreen * @type {Function} * @param ngVideoOptions {Object} */ $angular.module('ngVideo').directive('viScreen', ['ngVideoOptions', function ngScreenDirective(ngVideoOptions) { return { /** * @property restrict * @type {String} */ restrict: ngVideoOptions.RESTRICT, /** * @method link * @param scope {Object} * @param element {Object} * @return {void} */ link: function link(scope, element) { if (ngVideoOptions.SCREEN_CHANGE) { // When the video player screen is clicked, we'll toggle the playing // state of the current video, if there is one. element.bind('click', function() { if (!scope.loading) { scope.toggleState(); } }); } } } }]); })(window.angular);
/** * @fileoverview * Shuffl card plug-in for simple card containing tabular data. * * The original intent was to have a collection card for the table, and * represent each row as a separate card, but on closer examination this * would create problems about when or which cards should be deleted, * e.g., when the table is reloaded. So, instead, I've gone for a table * resource, with the intent that, in due course, individual rows can be * pulled out as separate cards when required. * * Also, I think this approach is better suited for working with existing * research data sets - the card-first approach may be more appropriate for * primary data capture activities. * * @author Graham Klyne * @version $Id$ * * Coypyright (C) 2009, University of Oxford * * Licensed under the MIT License. You may obtain a copy of the License at: * * http://www.opensource.org/licenses/mit-license.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // ---------------------------------------------------------------- // Globals and data // ---------------------------------------------------------------- /** * Check shuffl namespace */ if (typeof shuffl == "undefined") { alert("shuffl-card-datatable.js: shuffl-base.js must be loaded first"); } if (typeof shuffl.card == "undefined") { alert("shuffl-card-datatable.js: shuffl-cardhandlers.js must be loaded before this"); } /** * Create namespace for this card type */ shuffl.card.datatable = {}; /** * Temporary default data for testing... * TODO: reset this when done testing */ shuffl.card.datatable.table = [ [ "", "col1", "col2", "col3", "col4_is_much_wider", "col5" ] , [ "1", "1.1", "1.2", "1.3", "1.4", "1.5" ] , [ "2", "2.1", "2.2", "2.3", "2.4", "2.5" ] , [ "3", "3.1", "3.2", "3.3", "3.4", "3.5" ] , [ "4", "4.1", "4.2", "4.3", "4.4", "4.5" ] , [ "5", "5.1", "5.2", "5.3", "5.4", "5.5" ] , [ "6", "6.1", "6.2", "6.3", "6.4", "6.5" ] , [ "7", "7.1", "7.2", "7.3", "7.4", "7.5" ] , [ "8", "8.1", "8.2", "8.3", "8.4", "8.5" ] , [ "End." ] ]; /** * jQuery base element for building new cards (used by shuffl.makeCard) */ shuffl.card.datatable.blank = jQuery( "<div class='shuffl-card-setsize shuffl-series' style='z-index:10;'>\n"+ " <chead>\n"+ " <chandle><c></c></chandle>" + " <ctitle>card title</ctitle>\n"+ " </chead>\n"+ " <crow>\n"+ " <curi>card_ZZZ uri</curi>\n"+ " </crow>\n"+ " <crow>\n"+ " <cbody class='shuffl-nodrag'>\n"+ " <table>\n"+ " <tr><th></th><th>col1</th><th>col2</th><th>col3</th></tr>\n"+ " <tr><td>row1</td><td>1.1</td><td>1.2</td><td>1.3</td></tr>\n"+ " <tr><td>row1</td><td>2.1</td><td>2.2</td><td>2.3</td></tr>\n"+ " <tr><td>End.</td></tr>\n"+ " </table>\n"+ " </cbody>\n"+ " </crow>\n"+ " <cfoot>\n"+ " <cident>card_ZZZ_ident</cident>:<cclass>card_ZZZ class</cclass>\n"+ " (<ctags>card_ZZZ tags</ctags>)\n"+ " </cfoot>"+ "</div>"); /** * Template for initializing a card model, and * creating new card object for serialization. */ shuffl.card.datatable.datamap = { 'shuffl:title': { def: '@id' } , 'shuffl:tags': { def: '@tags', type: 'array' } , 'shuffl:uri': { def: "" } , 'shuffl:table': { def: shuffl.card.datatable.table } }; /** * Creates and return a new card instance. * * @param cardtype type identifier for the new card element * @param cardcss CSS class name(s) for the new card element * @param cardid local card identifier - a local name for the card, * which may be combined with a base URI to form a URI * for the card. * @param carddata an object or string containing additional data used in * constructing the body of the card. This is either a * string or an object structure with fields * 'shuffl:title', 'shuffl:tags' and 'shuffl:table'. * @return a jQuery object representing the new card. */ shuffl.card.datatable.newCard = function (cardtype, cardcss, cardid, carddata) { //log.debug("shuffl.card.datatable.newCard: "+ // cardtype+", "+cardcss+", "+cardid+", "+carddata); // Initialize the card object var card = shuffl.card.datatable.blank.clone(); card.data('shuffl:type' , cardtype); card.data('shuffl:id', cardid); card.data("shuffl:tojson", shuffl.card.datatable.serialize); card.attr('id', cardid); card.addClass(cardcss); card.find("cident").text(cardid); // Set card id text card.find("cclass").text(cardtype); // Set card class/type text card.data("resizeAlso", "cbody"); card.resizable(); // Set up model listener and user input handlers shuffl.bindLineEditable(card, "shuffl:title", "ctitle"); shuffl.bindLineEditable(card, "shuffl:tags", "ctags"); shuffl.bindLineEditable(card, "shuffl:uri", "curi"); var cbody = card.find("cbody"); card.modelBind("shuffl:table", shuffl.modelSetTable(cbody, 1, shuffl.modelSetSeries(card))); // Initialize the model shuffl.initModel(card, carddata, shuffl.card.datatable.datamap, {id: cardid, tags: [cardtype]} ); // Finally, set listener for changes to URI value to read new data // This comes last so that the initialization of shuffl:uri does not // trigger a read when initializing a card. card.modelBind("shuffl:uri", function (event, data) { log.debug("Read "+data.newval+" into data table"); jQuery.getCSV(data.newval, function (data, status) { ////log.debug("- data "+jQuery.toJSON(data)); card.model("shuffl:table", data); card.data('shuffl:datamod', true); }); }); return card; }; /** * Serializes a tabular data card to JSON for storage * * @param card a jQuery object corresponding to the card * @return an object containing the card data */ shuffl.card.datatable.serialize = function (card) { return shuffl.serializeModel(card, shuffl.card.datatable.datamap); }; /** * Add new card type factories */ shuffl.addCardFactory("shuffl-datatable-yellow", "stock-yellow", shuffl.card.datatable.newCard); shuffl.addCardFactory("shuffl-datatable-blue", "stock-blue", shuffl.card.datatable.newCard); shuffl.addCardFactory("shuffl-datatable-green", "stock-green", shuffl.card.datatable.newCard); shuffl.addCardFactory("shuffl-datatable-orange", "stock-orange", shuffl.card.datatable.newCard); shuffl.addCardFactory("shuffl-datatable-pink", "stock-pink", shuffl.card.datatable.newCard); shuffl.addCardFactory("shuffl-datatable-purple", "stock-purple", shuffl.card.datatable.newCard); // End.
var parseBits = function(data, bits, offset, invert, callback) { offset = offset || 0; invert = invert || false; callback = callback || function(lastValue, newValue, bits) { return (lastValue * Math.pow(2, bits)) + newValue; }; var offsetBytes = offset >> 3; var inv = function(value) { if (invert) { return ~value & 0xff; } return value; }; // read first (maybe partial) byte var mask = 0xff; var firstBits = 8 - (offset % 8); if (bits < firstBits) { mask = (0xff << (8 - bits)) & 0xff; firstBits = bits; } if (offset) { mask = mask >> (offset % 8); } var result = 0; if ((offset % 8) + bits >= 8) { result = callback(0, inv(data[offsetBytes]) & mask, firstBits); } // read bytes var bytes = (bits + offset) >> 3; for (var i = offsetBytes + 1; i < bytes; i++) { result = callback(result, inv(data[i]), 8); } // bits to read, that are not a complete byte var lastBits = (bits + offset) % 8; if (lastBits > 0) { result = callback(result, inv(data[bytes]) >> (8 - lastBits), lastBits); } return result; }; var parseFloatFromBits = function(data, precisionBits, exponentBits) { var bias = Math.pow(2, exponentBits - 1) - 1; var sign = parseBits(data, 1); var exponent = parseBits(data, exponentBits, 1); if (exponent === 0) { return 0; } // parse mantissa var precisionBitsCounter = 1; var parsePrecisionBits = function(lastValue, newValue, bits) { if (lastValue === 0) { lastValue = 1; } for (var i = 1; i <= bits; i++) { precisionBitsCounter /= 2; if ((newValue & (0x1 << (bits - i))) > 0) { lastValue += precisionBitsCounter; } } return lastValue; }; var mantissa = parseBits(data, precisionBits, exponentBits + 1, false, parsePrecisionBits); // special cases if (exponent == (Math.pow(2, exponentBits + 1) - 1)) { if (mantissa === 0) { return (sign === 0) ? Infinity : -Infinity; } return NaN; } // normale number return ((sign === 0) ? 1 : -1) * Math.pow(2, exponent - bias) * mantissa; }; var parseBool = function(value) { return (parseBits(value, 8) == 1); }; var parseInt16 = function(value) { if (parseBits(value, 1) == 1) { return -1 * (parseBits(value, 15, 1, true) + 1); } return parseBits(value, 15, 1); }; var parseInt32 = function(value) { if (parseBits(value, 1) == 1) { return -1 * (parseBits(value, 31, 1, true) + 1); } return parseBits(value, 31, 1); }; var parseInt64 = function(value) { if (parseBits(value, 1) == 1) { return -1 * (parseBits(value, 63, 1, true) + 1); } return parseBits(value, 63, 1); }; var parseFloat32 = function(value) { return parseFloatFromBits(value, 23, 8); }; var parseFloat64 = function(value) { return parseFloatFromBits(value, 52, 11); }; var parseNumeric = function(value) { var sign = parseBits(value, 16, 32); if (sign == 0xc000) { return NaN; } var weight = Math.pow(10000, parseBits(value, 16, 16)); var result = 0; var digits = []; var ndigits = parseBits(value, 16); for (var i = 0; i < ndigits; i++) { result += parseBits(value, 16, 64 + (16 * i)) * weight; weight /= 10000; } var scale = Math.pow(10, parseBits(value, 16, 48)); return ((sign === 0) ? 1 : -1) * Math.round(result * scale) / scale; }; var parseDate = function(isUTC, value) { var sign = parseBits(value, 1); var rawValue = parseBits(value, 63, 1); // discard usecs and shift from 2000 to 1970 var result = new Date((((sign === 0) ? 1 : -1) * rawValue / 1000) + 946684800000); if (!isUTC) { result.setTime(result.getTime() + result.getTimezoneOffset() * 60000); } // add microseconds to the date result.usec = rawValue % 1000; result.getMicroSeconds = function() { return this.usec; }; result.setMicroSeconds = function(value) { this.usec = value; }; result.getUTCMicroSeconds = function() { return this.usec; }; return result; }; var parseArray = function(value) { var dim = parseBits(value, 32); var flags = parseBits(value, 32, 32); var elementType = parseBits(value, 32, 64); var offset = 96; var dims = []; for (var i = 0; i < dim; i++) { // parse dimension dims[i] = parseBits(value, 32, offset); offset += 32; // ignore lower bounds offset += 32; } var parseElement = function(elementType) { // parse content length var length = parseBits(value, 32, offset); offset += 32; // parse null values if (length == 0xffffffff) { return null; } var result; if ((elementType == 0x17) || (elementType == 0x14)) { // int/bigint result = parseBits(value, length * 8, offset); offset += length * 8; return result; } else if (elementType == 0x19) { // string result = value.toString(this.encoding, offset >> 3, (offset += (length << 3)) >> 3); return result; } else { console.log("ERROR: ElementType not implemented: " + elementType); } }; var parse = function(dimension, elementType) { var array = []; var i; if (dimension.length > 1) { var count = dimension.shift(); for (i = 0; i < count; i++) { array[i] = parse(dimension, elementType); } dimension.unshift(count); } else { for (i = 0; i < dimension[0]; i++) { array[i] = parseElement(elementType); } } return array; }; return parse(dims, elementType); }; var parseText = function(value) { return value.toString('utf8'); }; var parseBool = function(value) { return (parseBits(value, 8) > 0); }; var init = function(register) { register(20, parseInt64); register(21, parseInt16); register(23, parseInt32); register(26, parseInt32); register(1700, parseNumeric); register(700, parseFloat32); register(701, parseFloat64); register(16, parseBool); register(1114, parseDate.bind(null, false)); register(1184, parseDate.bind(null, true)); register(1007, parseArray); register(1016, parseArray); register(1008, parseArray); register(1009, parseArray); register(25, parseText); }; module.exports = { init: init };
//This script creates a gridded circle on the Dynamic Lighting layer, based on a specific token to be used as magical darkness, then moves that token to the map // This is based on a darkness concept contributed by Avi on the forum: // https://app.roll20.net/forum/post/5899495/stupid-roll20-tricks-and-some-clever-ones //The circle approximation code is based on theAaron's !dlcircle script, simplified to handle only circles rather than ellipses //To use: // Create a character whose token has the desired image of the darkness generated, and drag that token to the map. // Add an Ability macro to call !dldark and set as a token action /* SYNTAX !dldark <buffer> <makeGrid> <sendToMapLayer> "buffer" < # > Optional. Default = 0 reduce the radius of the darkness by this many pixels. allows the source of the darkness to be seen at the outer border of the darkness. "makeGrid" < true/false > Optional. Default = true draw a grid inside of the darkness circle. the grid will be aligned with the map grid based on page settings "SendToMapLayer" < true/false > Optional. Default = true send the source token to the map layer after creating the DL path? if true, will send to map layer and peform a z-order "ToFront" if false, will keep on token layer and peform a z-order "ToBack" STD EXAMPLES !dldark !dldark 15 true !dldark ?{buffer radius?|15} true false De-linking EXAMPLES !dldarkclear token unlinks selected token and corresponding dynamic lighting path (requires token selection) !dldarkclear tok (Alias) unlinks selected token and corresponding dynamic lighting path (requires token selection) !dldarkclear page unlinks all tokens and corresponding dynamic lighting paths from the current page (requires token selection) !dldarkclear campaign unlinks all tokens and corresponding dynamic lighting paths from the ENTIRE CAMPAIGN (Use caution!) */ const dldark = (() => { const scriptName = "DLdark"; const version = '0.3'; const schemaVersion = '0.1'; const byTOKEN = 'TOKEN'; const byPATH = 'PATH'; const clearTOKEN = 'TOKEN'; const clearALL = 'ALL'; const checkInstall = function() { log(scriptName + ' v' + version + ' initialized.'); //delete state[scriptName]; if( ! _.has(state, scriptName) || state[scriptName].version !== schemaVersion) { log(' > Updating Schema to v'+schemaVersion+' <'); switch(state[scriptName] && state[scriptName].version) { case 0.1: /* falls through */ case 'UpdateSchemaVersion': state[scriptName].version = schemaVersion; break; default: state[scriptName] = { version: schemaVersion, links: [] }; break; } } //log(state[scriptName]); }; const clearCache = function(who, tokID=undefined, pageID=undefined) { //no arguments passed, clear all pinked pairs in ENTIRE CAMPAIGN if(!tokID && !pageID) { state[scriptName] = { version: schemaVersion, links: [] }; sendChat(scriptName,`/w "${who}" `+ 'DL darkness unlinked across ENTIRE CAMPAIGN!'); return; } //token only if (tokID) { //iterate through linked pairs in state object to find pairs associated with tokID for (let i = state[scriptName].links.length-1; i>-1; i--) { if (state[scriptName].links[i].tokID === tokID) { //remove linked pair ids from state object state[scriptName].links.splice(i,1); sendChat(scriptName,`/w "${who}" `+ 'DL darkness unlinked for tokID = ' + tokID); } } } //all linked tokens in current page if (pageID) { //iterate through linked pairs in state object to find pairs associated with pageID for (let i = state[scriptName].links.length-1; i>-1; i--) { if (state[scriptName].links[i].pageID === pageID) { //remove linked pair ids from state object state[scriptName].links.splice(i,1); } } sendChat(scriptName,`/w "${who}" `+ 'DL darkness unlinked for all tokens in pageID = ' + pageID); } //log(state[scriptName]); } const makeLinkedPair = function(tokID, pathID, pageID='') { let link = { tokID: tokID, pathID: pathID, pageID: pageID }; state[scriptName].links.push(link); return link; } //Return array of {tokID, pathID} pairs from state object, given tokenID or pathID based on searchType. Returns undefined if none found. const getLinkedPairs = function(ID, searchType) { let pair = state[scriptName].links.filter(function (p) { if (searchType === byTOKEN) { return p.tokID === ID; } else { return p.pathID === ID; } }); if (pair.length>0) { return pair; } else { return undefined; } } //Circle/ellipse building portion of function is modified from TheAaron's "dlcircle" script const buildCircleGrid = function(who, rad, left, top, makeGrid, gridSize) { const centerX = rad const centerY = rad let circlePoints; let gridPoints = "" try { const at = (theta) => ({x: Math.cos(theta)*rad, y: Math.sin(theta)*rad}); let steps = Math.min(Math.max(Math.round( (Math.PI*2*Math.sqrt((2*rad*rad)/2))/35),4),20); const stepSize = Math.PI/(2*steps); let acc=[[],[],[],[]]; let th=0; _.times(steps+1,()=>{ let pt=at(th); acc[0].push([pt.x,pt.y]); acc[1].push([-pt.x,pt.y]); acc[2].push([-pt.x,-pt.y]); acc[3].push([pt.x,-pt.y]); th+=stepSize; }); acc = acc[0].concat( acc[1].reverse().slice(1), acc[2].slice(1), acc[3].reverse().slice(1) ); //We will take this string, strip the last "]", append the grid points to the path, then add the trailing "]" when we return the full JSON circlePoints = JSON.stringify(acc.map((v,i)=>([(i?'L':'M'),rad+v[0],rad+v[1]]))); circlePoints = circlePoints.substring(0, circlePoints.length - 1); if (makeGrid) { //Define grid points & build JSON string let x1 = 0, x2 = 0, y1 = 0, y2 = 0; let x = 0, y = 0; //Try to align the darkness path to the actual map grid //remember, path coords are relative to (left, top) of the path object, NOT to the map grid. let startX = gridSize - (left-rad) % gridSize; let startY = gridSize - (top-rad) % gridSize; //build the grid for (x = startX; x <= 2*rad; x+=gridSize) { if( x >= 0) { //vertical lines y1 = centerY + Math.sqrt(rad*rad-(x-centerX)*(x-centerX)); y2 = centerY - Math.sqrt(rad*rad-(x-centerX)*(x-centerX)); gridPoints = gridPoints + ",[\"M\"," + x.toString() + "," + y1.toString() + "]"; gridPoints = gridPoints + ",[\"L\"," + x.toString() + "," + y2.toString() + "]"; for (y = startY; y <= 2*rad; y+=gridSize) { if( y >= 0) { //horizontal lines x1 = centerX + Math. sqrt(rad*rad-(y-centerY)*(y-centerY)); x2 = centerX - Math. sqrt(rad*rad-(y-centerY)*(y-centerY)); gridPoints = gridPoints + ",[\"M\"," + x1.toString() + "," + y.toString() + "]"; gridPoints = gridPoints + ",[\"L\"," + x2.toString() + "," + y.toString() + "]"; } } } } } //this is the entire path return circlePoints + gridPoints + "]"; } catch(err) { sendChat(scriptName,`/w "${who}" `+ 'Unhandled exception: ' + err.message); } }; //Move DL path to remain under source token const handleTokenChange = function(obj,prev) { //find all paths linked to token, returns an array of {tokID, pathID} pairs, or undefined let pair = getLinkedPairs(obj.get('id'), byTOKEN); if (pair && obj && prev) { //calc delta X & Y let dX = obj.get('left') - prev['left'] let dY = obj.get('top') - prev['top'] //move path object(s) based on source token movement for (let i = 0; i < pair.length; i++) { let path = getObj('path', pair[i].pathID); if (path) { let newX = parseInt(path.get('left')) + dX; let newY = parseInt(path.get('top')) + dY; path.set({left:newX, top:newY}); } } } } const handleRemoveToken = function(obj) { let tokID = obj['id']; //iterate through linked pairs in state object to find pairs associated with tokID for (let i = state[scriptName].links.length-1; i>-1; i--) { if (state[scriptName].links[i].tokID === tokID) { //get associated path object and remove if it still exists let path = getObj('path',state[scriptName].links[i].pathID); if (path) { path.remove(); //note: when the path is removed, the handleRemovePath function will take care of deleting the linked pair from state object } else { //remove linked pair ids from state object (shouldn't ever get called, but here just in case) state[scriptName].links.splice(i,1); } } } //log(state[scriptName]); }; const handleRemovePath = function(obj) { let pathID = obj['id']; for (let i = state[scriptName].links.length-1; i>-1; i--) { if (state[scriptName].links[i].pathID === pathID) { //remove linked pair ids from state object state[scriptName].links.splice(i,1); } } //log(state[scriptName]); }; const handleInput = function(msg) { let who, tok, tokID, pageID; try { //---------------------------------------------------------------------------- // Optional script operation - clears linked pairs // e.g. !dldarkclear tok //clears all linked pairs associated with the selected token // !dldarkclear page //clears all linked pairs on current page // !dldarkclear campaign //clears all linked pairs in ENTIRE CAMPAIGN //---------------------------------------------------------------------------- if(msg.type=="api" && msg.content.indexOf("!dldarkclear")==0) { who = getObj('player',msg.playerid).get('_displayname'); let cmd = msg.content.split(/\s+/); if (cmd.length > 1) { if (msg.selected !== undefined) { tokID = msg.selected[0]['_id']; tok = getObj("graphic",tokID); pageID = tok.get('pageid'); } switch(cmd[1].toLowerCase()) { case 'tok': if (tokID) { let clearTok = clearCache(who, tokID); } else { sendChat(scriptName,`/w "${who}" `+ 'Error. You must select a token to proceed with this command.'); return; } break; case 'token': if (tokID) { let clearTok = clearCache(who, tokID); } else { sendChat(scriptName,`/w "${who}" `+ 'Error. You must select a token to proceed with this command.'); return; } break; case 'page': if (tokID) { let clearTok = clearCache(who, undefined, pageID); } else { sendChat(scriptName,`/w "${who}" `+ 'Error. You must select a token to proceed with this command.'); return; } break; case 'campaign': let clear = clearCache(who); break; default: sendChat(scriptName,`/w "${who}" `+ 'Unknown argument. Format is \"!dldarkclear tok/page/campaign\"'); break; } } return; } //-------------------------------------------------------------------- // Normal script operation //-------------------------------------------------------------------- if(msg.type=="api" && msg.content.indexOf("!dldark")==0) { let selected = msg.selected; let buffer = 0; let makeGrid = true; let sendToMap = true; who = getObj('player',msg.playerid).get('_displayname'); if (selected===undefined) { sendChat(scriptName,`/w "${who}" `+ 'You must select a token to proceed'); return; } let cmd = msg.content.split(/\s+/); if (cmd.length > 1) { if (isNaN(cmd[1])) { sendChat(scriptName,`/w "${who}" `+ 'Non-numeric buffer detected. Format is \"!dldark # boolean boolean\"'); return; } else { buffer = parseInt(cmd[1]); } } if (cmd.length > 2) { if (_.contains(['true', 'yes', '1'], cmd[2].toLowerCase())) { makeGrid = true; } else if (_.contains(['false', 'no', '0'], cmd[2].toLowerCase())) { makeGrid = false; } else { sendChat(scriptName,`/w "${who}" `+ 'Non-boolean makeGrid flag detected. Format is \"!dldark # boolean boolean\"'); return; } } if (cmd.length > 3) { if (_.contains(['true', 'yes', '1'], cmd[3].toLowerCase())) { sendToMap = true; } else if (_.contains(['false', 'no', '0'], cmd[3].toLowerCase())) { sendToMap = false; } else { sendChat(scriptName,`/w "${who}" `+ 'Non-boolean sendToMapLayer flag detected. Format is \"!dldark # boolean boolean\"'); return; } } tok = getObj("graphic",selected[0]._id); let left = tok.get("left"); let top = tok.get("top"); let pageID = tok.get("pageid"); //page grid settings let thePage = getObj("page", pageID); //let pageScaleNumber = thePage.get("scale_number"); let pageGridSize = 70 * thePage.get("snapping_increment"); if ( pageGridSize === 0) { //gridless map support //override user input makeGrid = false; } let radius = (tok.get("width"))/2 - buffer; let pathstring = buildCircleGrid(who, radius, left, top, makeGrid, pageGridSize); let path = createObj("path", { pageid: tok.get("pageid"), path: pathstring, fill: "transparent", stroke: "#ff0000", layer: "walls", stroke_width: 5, width: radius*2, height: radius*2, left: tok.get("left"), top: tok.get("top"), }); //log(path.get("id")); if (path) { if (sendToMap) { tok.set("layer", "map"); toFront(tok); } else { toBack(tok); } //create a link between the source token and the darkness path (stored in state object) let newLink = makeLinkedPair(tok.get('_id'), path.get('_id'), tok.get('pageid')); sendChat(scriptName,`/w "${who}" `+ 'Darkness created on Dynamic Lighting layer'); } else { sendChat(scriptName,`/w "${who}" `+ 'Unknown error. createObj failed. DL path not created.'); return; } } } catch(err) { sendChat('dldarkAPI',`/w "${who}" `+ 'Unhandled exception: ' + err.message); } }; const registerEventHandlers = function() { on('chat:message', handleInput); on('change:graphic', handleTokenChange); on('destroy:graphic', handleRemoveToken); on('destroy:path', handleRemovePath); }; on("ready",() => { checkInstall(); registerEventHandlers(); }); })();
/** * Test description * ================ * * Starting with an empty project (no package.json) * - jam publish package-one * - jam publish package-two (depends on package-one) * - jam install package-two, test installation succeeded * - jam ls, test packages are listed * - jam remove package-two, test it's removed */ var couchdb = require('../../lib/couchdb'), logger = require('../../lib/logger'), env = require('../../lib/env'), utils = require('../utils'), async = require('async'), http = require('http'), path = require('path'), ncp = require('ncp').ncp, fs = require('fs'), _ = require('underscore'); var pathExists = fs.exists || path.exists; logger.clean_exit = true; // CouchDB database URL to use for testing var TESTDB = process.env['JAM_TEST_DB'], BIN = path.resolve(__dirname, '../../bin/jam.js'), ENV = {JAM_TEST: 'true', JAM_TEST_DB: TESTDB}; if (!TESTDB) { throw 'JAM_TEST_DB environment variable not set'; } // remove trailing-slash from TESTDB URL TESTDB = TESTDB.replace(/\/$/, ''); exports.setUp = function (callback) { // change to integration test directory before running test this._cwd = process.cwd(); process.chdir(__dirname); // recreate any existing test db couchdb(TESTDB).deleteDB(function (err) { if (err && err.error !== 'not_found') { return callback(err); } // create test db couchdb(TESTDB).createDB(callback); }); }; exports.tearDown = function (callback) { // change back to original working directory after running test process.chdir(this._cwd); // delete test db couchdb(TESTDB).deleteDB(callback); }; exports['empty project'] = { setUp: function (callback) { this.project_dir = path.resolve(env.temp, 'jamtest-' + Math.random()); // set current project to empty directory ncp('./fixtures/project-empty', this.project_dir, callback); }, /* tearDown: function (callback) { var that = this; // timeout to try and wait until dir is no-longer busy on windows //utils.myrimraf(that.project_dir, callback); }, */ 'publish, install, ls, remove': function (test) { test.expect(6); var that = this; process.chdir(that.project_dir); var pkgone = path.resolve(__dirname, 'fixtures', 'package-one'), pkgtwo = path.resolve(__dirname, 'fixtures', 'package-two'); async.series([ async.apply(utils.runJam, ['publish', pkgone], {env: ENV}), async.apply(utils.runJam, ['publish', pkgtwo], {env: ENV}), async.apply(utils.runJam, ['install', 'package-two'], {env: ENV}), function (cb) { // test that main.js was installed from package var a = fs.readFileSync(path.resolve(pkgone, 'main.js')); var b = fs.readFileSync( path.resolve(that.project_dir, 'jam/package-one/main.js') ); test.equal(a.toString(), b.toString()); var c = fs.readFileSync(path.resolve(pkgtwo, 'two.js')); var d = fs.readFileSync( path.resolve(that.project_dir, 'jam/package-two/two.js') ); test.equal(c.toString(), d.toString()); // make sure the requirejs config includes the new package var cfg = utils.freshRequire( path.resolve(that.project_dir, 'jam', 'require.config') ); var packages= _.sortBy(cfg.packages, function (p) { return p.name; }); test.same(packages, [ { name: 'package-one', location: 'jam/package-one' }, { name: 'package-two', location: 'jam/package-two', main: 'two.js' } ]); cb(); }, function (cb) { utils.runJam(['ls'], function (err, stdout, stderr) { if (err) { return cb(err); } var lines = stdout.replace(/\n$/, '').split('\n'); test.same(lines.sort(), [ ' package-one \u001b[33m0.0.1\u001b[39m', ' package-two \u001b[33m0.0.1\u001b[39m' ]); cb(); }); }, function (cb) { var args = ['remove', 'package-two']; utils.runJam(args, function (err, stdout, stderr) { if (err) { return cb(err); } var cfg = utils.freshRequire( path.resolve(that.project_dir, 'jam', 'require.config') ); test.same(cfg.packages.sort(), [ { name: 'package-one', location: 'jam/package-one' } ]); var p = path.resolve(that.project_dir, 'jam/package-two'); pathExists(p, function (exists) { test.ok(!exists, 'package-two directory removed'); cb(); }); }); } ], test.done); } };
/** * Created by middleca on 1/23/15. */ 'use strict'; var when = require('when'); var pipeline = require('when/pipeline'); var wifiscanner = require('node-wifiscanner2'); var WifiUtilities = { scan: function() { var dfd = when.defer(); wifiscanner.scan(function(err, data) { if (err) { dfd.reject(err); } else { dfd.resolve(data); } }); return dfd.promise; }, objToArr: function(obj) { var arr = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { arr.push(obj[key]); } } return arr; }, /** * Alphabetize, de-duplicate, * @param {Array} list * @returns {Promise} promise that resolves with the list */ cleanApList: function(list) { list = list.sort(function(a, b) { if (a.ssid && !b.ssid) { return 1; } else if (b.ssid && !a.ssid) { return -1; } return a.ssid.localeCompare(b.ssid); }); var names = {}; list.map(function(a) { names[a.ssid] = names[a.ssid] || a; if (a.signal_level > names[a.ssid].signal_level) { names[a.ssid] = a; } }); list = WifiUtilities.objToArr(names); return when.resolve(list); }, displayAPList: function(list) { console.log('I found these Wi-Fi Access Points:'); var formatLine = function(ap, idx) { if (!ap) { return ''; } //only show quotes if there is weird whitespace if (ap.ssid !== ap.ssid.trimLeft().trimRight()) { ap.ssid = '"' + ap.ssid + '"'; } var arr = [ idx + 1, '.)\t', ap.ssid ]; //only show channel info if we have it if (ap.channel) { arr.push('\t\t + (channel ' + ap.channel + ')'); } return arr.join(''); }; var lines = list.map(formatLine); console.log(lines.join('\n')); return when.resolve(); }, scanAndListAPs: function() { return pipeline([ WifiUtilities.scan, WifiUtilities.cleanApList, WifiUtilities.displayAPList ]); } }; module.exports = WifiUtilities;
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ describe('console', () => { let React; let ReactDOM; let act; let fakeConsole; let mockError; let mockInfo; let mockLog; let mockWarn; let patchConsole; let unpatchConsole; beforeEach(() => { jest.resetModules(); const Console = require('react-devtools-shared/src/backend/console'); patchConsole = Console.patch; unpatchConsole = Console.unpatch; // Patch a fake console so we can verify with tests below. // Patching the real console is too complicated, // because Jest itself has hooks into it as does our test env setup. mockError = jest.fn(); mockInfo = jest.fn(); mockLog = jest.fn(); mockWarn = jest.fn(); fakeConsole = { error: mockError, info: mockInfo, log: mockLog, warn: mockWarn, }; Console.dangerous_setTargetConsoleForTesting(fakeConsole); // Note the Console module only patches once, // so it's important to patch the test console before injection. patchConsole({ appendComponentStack: true, breakOnWarn: false, }); const inject = global.__REACT_DEVTOOLS_GLOBAL_HOOK__.inject; global.__REACT_DEVTOOLS_GLOBAL_HOOK__.inject = internals => { inject(internals); Console.registerRenderer(internals); }; React = require('react'); ReactDOM = require('react-dom'); const utils = require('./utils'); act = utils.act; }); function normalizeCodeLocInfo(str) { return ( str && str.replace(/\n +(?:at|in) ([\S]+)[^\n]*/g, function(m, name) { return '\n in ' + name + ' (at **)'; }) ); } it('should not patch console methods that do not receive component stacks', () => { expect(fakeConsole.error).not.toBe(mockError); expect(fakeConsole.info).toBe(mockInfo); expect(fakeConsole.log).toBe(mockLog); expect(fakeConsole.warn).not.toBe(mockWarn); }); it('should only patch the console once', () => { const {error, warn} = fakeConsole; patchConsole({ appendComponentStack: true, breakOnWarn: false, }); expect(fakeConsole.error).toBe(error); expect(fakeConsole.warn).toBe(warn); }); it('should un-patch when requested', () => { expect(fakeConsole.error).not.toBe(mockError); expect(fakeConsole.warn).not.toBe(mockWarn); unpatchConsole(); expect(fakeConsole.error).toBe(mockError); expect(fakeConsole.warn).toBe(mockWarn); }); it('should pass through logs when there is no current fiber', () => { expect(mockLog).toHaveBeenCalledTimes(0); expect(mockWarn).toHaveBeenCalledTimes(0); expect(mockError).toHaveBeenCalledTimes(0); fakeConsole.log('log'); fakeConsole.warn('warn'); fakeConsole.error('error'); expect(mockLog).toHaveBeenCalledTimes(1); expect(mockLog.mock.calls[0]).toHaveLength(1); expect(mockLog.mock.calls[0][0]).toBe('log'); expect(mockWarn).toHaveBeenCalledTimes(1); expect(mockWarn.mock.calls[0]).toHaveLength(1); expect(mockWarn.mock.calls[0][0]).toBe('warn'); expect(mockError).toHaveBeenCalledTimes(1); expect(mockError.mock.calls[0]).toHaveLength(1); expect(mockError.mock.calls[0][0]).toBe('error'); }); it('should not append multiple stacks', () => { const Child = ({children}) => { fakeConsole.warn('warn\n in Child (at fake.js:123)'); fakeConsole.error('error', '\n in Child (at fake.js:123)'); return null; }; act(() => ReactDOM.render(<Child />, document.createElement('div'))); expect(mockWarn).toHaveBeenCalledTimes(1); expect(mockWarn.mock.calls[0]).toHaveLength(1); expect(mockWarn.mock.calls[0][0]).toBe( 'warn\n in Child (at fake.js:123)', ); expect(mockError).toHaveBeenCalledTimes(1); expect(mockError.mock.calls[0]).toHaveLength(2); expect(mockError.mock.calls[0][0]).toBe('error'); expect(mockError.mock.calls[0][1]).toBe('\n in Child (at fake.js:123)'); }); it('should append component stacks to errors and warnings logged during render', () => { const Intermediate = ({children}) => children; const Parent = ({children}) => ( <Intermediate> <Child /> </Intermediate> ); const Child = ({children}) => { fakeConsole.error('error'); fakeConsole.log('log'); fakeConsole.warn('warn'); return null; }; act(() => ReactDOM.render(<Parent />, document.createElement('div'))); expect(mockLog).toHaveBeenCalledTimes(1); expect(mockLog.mock.calls[0]).toHaveLength(1); expect(mockLog.mock.calls[0][0]).toBe('log'); expect(mockWarn).toHaveBeenCalledTimes(1); expect(mockWarn.mock.calls[0]).toHaveLength(2); expect(mockWarn.mock.calls[0][0]).toBe('warn'); expect(normalizeCodeLocInfo(mockWarn.mock.calls[0][1])).toEqual( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockError).toHaveBeenCalledTimes(1); expect(mockError.mock.calls[0]).toHaveLength(2); expect(mockError.mock.calls[0][0]).toBe('error'); expect(normalizeCodeLocInfo(mockError.mock.calls[0][1])).toBe( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); }); it('should append component stacks to errors and warnings logged from effects', () => { const Intermediate = ({children}) => children; const Parent = ({children}) => ( <Intermediate> <Child /> </Intermediate> ); const Child = ({children}) => { React.useLayoutEffect(() => { fakeConsole.error('active error'); fakeConsole.log('active log'); fakeConsole.warn('active warn'); }); React.useEffect(() => { fakeConsole.error('passive error'); fakeConsole.log('passive log'); fakeConsole.warn('passive warn'); }); return null; }; act(() => ReactDOM.render(<Parent />, document.createElement('div'))); expect(mockLog).toHaveBeenCalledTimes(2); expect(mockLog.mock.calls[0]).toHaveLength(1); expect(mockLog.mock.calls[0][0]).toBe('active log'); expect(mockLog.mock.calls[1]).toHaveLength(1); expect(mockLog.mock.calls[1][0]).toBe('passive log'); expect(mockWarn).toHaveBeenCalledTimes(2); expect(mockWarn.mock.calls[0]).toHaveLength(2); expect(mockWarn.mock.calls[0][0]).toBe('active warn'); expect(normalizeCodeLocInfo(mockWarn.mock.calls[0][1])).toEqual( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockWarn.mock.calls[1]).toHaveLength(2); expect(mockWarn.mock.calls[1][0]).toBe('passive warn'); expect(normalizeCodeLocInfo(mockWarn.mock.calls[1][1])).toEqual( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockError).toHaveBeenCalledTimes(2); expect(mockError.mock.calls[0]).toHaveLength(2); expect(mockError.mock.calls[0][0]).toBe('active error'); expect(normalizeCodeLocInfo(mockError.mock.calls[0][1])).toBe( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockError.mock.calls[1]).toHaveLength(2); expect(mockError.mock.calls[1][0]).toBe('passive error'); expect(normalizeCodeLocInfo(mockError.mock.calls[1][1])).toBe( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); }); it('should append component stacks to errors and warnings logged from commit hooks', () => { const Intermediate = ({children}) => children; const Parent = ({children}) => ( <Intermediate> <Child /> </Intermediate> ); class Child extends React.Component<any> { componentDidMount() { fakeConsole.error('didMount error'); fakeConsole.log('didMount log'); fakeConsole.warn('didMount warn'); } componentDidUpdate() { fakeConsole.error('didUpdate error'); fakeConsole.log('didUpdate log'); fakeConsole.warn('didUpdate warn'); } render() { return null; } } const container = document.createElement('div'); act(() => ReactDOM.render(<Parent />, container)); act(() => ReactDOM.render(<Parent />, container)); expect(mockLog).toHaveBeenCalledTimes(2); expect(mockLog.mock.calls[0]).toHaveLength(1); expect(mockLog.mock.calls[0][0]).toBe('didMount log'); expect(mockLog.mock.calls[1]).toHaveLength(1); expect(mockLog.mock.calls[1][0]).toBe('didUpdate log'); expect(mockWarn).toHaveBeenCalledTimes(2); expect(mockWarn.mock.calls[0]).toHaveLength(2); expect(mockWarn.mock.calls[0][0]).toBe('didMount warn'); expect(normalizeCodeLocInfo(mockWarn.mock.calls[0][1])).toEqual( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockWarn.mock.calls[1]).toHaveLength(2); expect(mockWarn.mock.calls[1][0]).toBe('didUpdate warn'); expect(normalizeCodeLocInfo(mockWarn.mock.calls[1][1])).toEqual( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockError).toHaveBeenCalledTimes(2); expect(mockError.mock.calls[0]).toHaveLength(2); expect(mockError.mock.calls[0][0]).toBe('didMount error'); expect(normalizeCodeLocInfo(mockError.mock.calls[0][1])).toBe( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockError.mock.calls[1]).toHaveLength(2); expect(mockError.mock.calls[1][0]).toBe('didUpdate error'); expect(normalizeCodeLocInfo(mockError.mock.calls[1][1])).toBe( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); }); it('should append component stacks to errors and warnings logged from gDSFP', () => { const Intermediate = ({children}) => children; const Parent = ({children}) => ( <Intermediate> <Child /> </Intermediate> ); class Child extends React.Component<any, any> { state = {}; static getDerivedStateFromProps() { fakeConsole.error('error'); fakeConsole.log('log'); fakeConsole.warn('warn'); return null; } render() { return null; } } act(() => ReactDOM.render(<Parent />, document.createElement('div'))); expect(mockLog).toHaveBeenCalledTimes(1); expect(mockLog.mock.calls[0]).toHaveLength(1); expect(mockLog.mock.calls[0][0]).toBe('log'); expect(mockWarn).toHaveBeenCalledTimes(1); expect(mockWarn.mock.calls[0]).toHaveLength(2); expect(mockWarn.mock.calls[0][0]).toBe('warn'); expect(normalizeCodeLocInfo(mockWarn.mock.calls[0][1])).toEqual( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockError).toHaveBeenCalledTimes(1); expect(mockError.mock.calls[0]).toHaveLength(2); expect(mockError.mock.calls[0][0]).toBe('error'); expect(normalizeCodeLocInfo(mockError.mock.calls[0][1])).toBe( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); }); it('should append stacks after being uninstalled and reinstalled', () => { const Child = ({children}) => { fakeConsole.warn('warn'); fakeConsole.error('error'); return null; }; unpatchConsole(); act(() => ReactDOM.render(<Child />, document.createElement('div'))); expect(mockWarn).toHaveBeenCalledTimes(1); expect(mockWarn.mock.calls[0]).toHaveLength(1); expect(mockWarn.mock.calls[0][0]).toBe('warn'); expect(mockError).toHaveBeenCalledTimes(1); expect(mockError.mock.calls[0]).toHaveLength(1); expect(mockError.mock.calls[0][0]).toBe('error'); patchConsole({ appendComponentStack: true, breakOnWarn: false, }); act(() => ReactDOM.render(<Child />, document.createElement('div'))); expect(mockWarn).toHaveBeenCalledTimes(2); expect(mockWarn.mock.calls[1]).toHaveLength(2); expect(mockWarn.mock.calls[1][0]).toBe('warn'); expect(normalizeCodeLocInfo(mockWarn.mock.calls[1][1])).toEqual( '\n in Child (at **)', ); expect(mockError).toHaveBeenCalledTimes(2); expect(mockError.mock.calls[1]).toHaveLength(2); expect(mockError.mock.calls[1][0]).toBe('error'); expect(normalizeCodeLocInfo(mockError.mock.calls[1][1])).toBe( '\n in Child (at **)', ); }); it('should be resilient to prepareStackTrace', () => { Error.prepareStackTrace = function(error, callsites) { const stack = ['An error occurred:', error.message]; for (let i = 0; i < callsites.length; i++) { const callsite = callsites[i]; stack.push( '\t' + callsite.getFunctionName(), '\t\tat ' + callsite.getFileName(), '\t\ton line ' + callsite.getLineNumber(), ); } return stack.join('\n'); }; const Intermediate = ({children}) => children; const Parent = ({children}) => ( <Intermediate> <Child /> </Intermediate> ); const Child = ({children}) => { fakeConsole.error('error'); fakeConsole.log('log'); fakeConsole.warn('warn'); return null; }; act(() => ReactDOM.render(<Parent />, document.createElement('div'))); expect(mockLog).toHaveBeenCalledTimes(1); expect(mockLog.mock.calls[0]).toHaveLength(1); expect(mockLog.mock.calls[0][0]).toBe('log'); expect(mockWarn).toHaveBeenCalledTimes(1); expect(mockWarn.mock.calls[0]).toHaveLength(2); expect(mockWarn.mock.calls[0][0]).toBe('warn'); expect(normalizeCodeLocInfo(mockWarn.mock.calls[0][1])).toEqual( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); expect(mockError).toHaveBeenCalledTimes(1); expect(mockError.mock.calls[0]).toHaveLength(2); expect(mockError.mock.calls[0][0]).toBe('error'); expect(normalizeCodeLocInfo(mockError.mock.calls[0][1])).toBe( '\n in Child (at **)\n in Intermediate (at **)\n in Parent (at **)', ); }); });
import { Vector3 } from '../../../../build/three.module.js'; import { InputNode } from '../core/InputNode.js'; import { NodeUtils } from '../core/NodeUtils.js'; class Vector3Node extends InputNode { constructor( x, y, z ) { super( 'v3' ); this.value = x instanceof Vector3 ? x : new Vector3( x, y, z ); } generateReadonly( builder, output, uuid, type/*, ns, needsUpdate*/ ) { return builder.format( 'vec3( ' + this.x + ', ' + this.y + ', ' + this.z + ' )', type, output ); } copy( source ) { super.copy( source ); this.value.copy( source ); return this; } toJSON( meta ) { let data = this.getJSONNode( meta ); if ( ! data ) { data = this.createJSONNode( meta ); data.x = this.x; data.y = this.y; data.z = this.z; if ( this.readonly === true ) data.readonly = true; } return data; } } Vector3Node.prototype.nodeType = 'Vector3'; NodeUtils.addShortcuts( Vector3Node.prototype, 'value', [ 'x', 'y', 'z' ] ); export { Vector3Node };
/** * Created by zed on 15/12/26. */
"use strict"; const Constants = require("../../../Constants"); const Events = Constants.Events; const Endpoints = Constants.Endpoints; const apiRequest = require("../../../core/ApiRequest"); module.exports = function(channelId, messageId) { return new Promise((rs, rj) => { var request = apiRequest .del(this, `${Endpoints.PINS(channelId)}/${messageId}`); this._queueManager.put(request, (err, res) => { if (err || !res.ok) return rj(err); this._messages.update({ id: messageId, channel_id: channelId, pinned: false }); rs(); }); }); };
5; (58 - 32); false && (true || !true) ? 3 : 2 - 5; window.document.childNodes.length--; "this " + window + window + " is a pair of `\n\"windows\"\n`"; window + " will come first this time"; window.scrollTo(35, 67); [].concat([1, 2, 3, 4]); /['"`\/]/; /['"`\/]/gi; [(_a = {}, _a["a" + "c"] = 1, _a.undefined = 44, _a[55] = "happ", _a.null = 5, _a["a"] = 14, _a.b = { "c": undefined }, _a.c = null, _a)]; window["addEventListener"] = null; new String("this") instanceof Array; delete window["someKey"]; typeof []; (function () { return 5; }); (function (a, b) { }); (function (a, b, c) { }); (function withName(d, f, g) { }); (_b = window)["addEventListener"].apply(_b, [1, 2, 3]); undefined; null; var _a, _b;
// TEST_1 @Component({ selector: 'app' }) @View({ template: ` <h1>Test</h1><p>Test</p> `, styles: [` .test { color: #f00; } smile:before { content: "\\000B"; } .common { color: #808080; } `], directives: [CORE_DIRECTIVES] }) export class App {}
;(function($){'use strict';$.fn.fitVids=function(options){var settings={customSelector:null,ignore:null};if(!document.getElementById('fit-vids-style')){var head=document.head||document.getElementsByTagName('head')[0];var css='.fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}';var div=document.createElement("div");div.innerHTML='<p>x</p><style id="fit-vids-style">'+css+'</style>';head.appendChild(div.childNodes[1]);} if(options){$.extend(settings,options);} return this.each(function(){var selectors=['iframe[src*="player.vimeo.com"]','iframe[src*="youtube.com"]','iframe[src*="youtube-nocookie.com"]','iframe[src*="kickstarter.com"][src*="video.html"]','object','embed'];if(settings.customSelector){selectors.push(settings.customSelector);} var ignoreList='.fitvidsignore';if(settings.ignore){ignoreList=ignoreList+', '+settings.ignore;} var $allVideos=$(this).find(selectors.join(','));$allVideos=$allVideos.not('object object');$allVideos=$allVideos.not(ignoreList);$allVideos.each(function(){var $this=$(this);if($this.parents(ignoreList).length>0){return;} if(this.tagName.toLowerCase()==='embed'&&$this.parent('object').length||$this.parent('.fluid-width-video-wrapper').length){return;} if((!$this.css('height')&&!$this.css('width'))&&(isNaN($this.attr('height'))||isNaN($this.attr('width')))) {$this.attr('height',9);$this.attr('width',16);} var height=(this.tagName.toLowerCase()==='object'||($this.attr('height')&&!isNaN(parseInt($this.attr('height'),10))))?parseInt($this.attr('height'),10):$this.height(),width=!isNaN(parseInt($this.attr('width'),10))?parseInt($this.attr('width'),10):$this.width(),aspectRatio=height/width;if(!$this.attr('id')){var videoID='fitvid'+Math.floor(Math.random()*999999);$this.attr('id',videoID);} $this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top',(aspectRatio*100)+'%');$this.removeAttr('height').removeAttr('width');});});};})(window.jQuery||window.Zepto);
'use strict'; var _ = require('lodash'); var $ = require('./util/preconditions'); var errors = require('./errors'); var Base58Check = require('./encoding/base58check'); var Networks = require('./networks'); var Hash = require('./crypto/hash'); var JSUtil = require('./util/js'); var Script = require('./script'); var PublicKey = require('./publickey'); /** * Instantiate an address from an address String or Buffer, a public key or script hash Buffer, * or an instance of {@link PublicKey} or {@link Script}. * * This is an immutable class, and if the first parameter provided to this constructor is an * `Address` instance, the same argument will be returned. * * An address has two key properties: `network` and `type`. The type is either * `Address.PayToPublicKeyHash` (value is the `'pubkeyhash'` string) * or `Address.PayToScriptHash` (the string `'scripthash'`). The network is an instance of {@link Network}. * You can quickly check whether an address is of a given kind by using the methods * `isPayToPublicKeyHash` and `isPayToScriptHash` * * @example * ```javascript * // validate that an input field is valid * var error = Address.getValidationError(input, 'testnet'); * if (!error) { * var address = Address(input, 'testnet'); * } else { * // invalid network or checksum (typo?) * var message = error.messsage; * } * * // get an address from a public key * var address = Address(publicKey, 'testnet').toString(); * ``` * * @param {*} data - The encoded data in various formats * @param {Network|String|number=} network - The network: 'livenet' or 'testnet' * @param {string=} type - The type of address: 'script' or 'pubkey' * @returns {Address} A new valid and frozen instance of an Address * @constructor */ function Address(data, network, type) { /* jshint maxcomplexity: 12 */ /* jshint maxstatements: 20 */ if (!(this instanceof Address)) { return new Address(data, network, type); } if (_.isArray(data) && _.isNumber(network)) { return Address.createMultisig(data, network, type); } if (data instanceof Address) { // Immutable instance return data; } $.checkArgument(data, 'First argument is required, please include address data.', 'guide/address.html'); if (network && !Networks.get(network)) { throw new TypeError('Second argument must be "livenet" or "testnet".'); } if (type && (type !== Address.PayToPublicKeyHash && type !== Address.PayToScriptHash)) { throw new TypeError('Third argument must be "pubkeyhash" or "scripthash".'); } var info = this._classifyArguments(data, network, type); // set defaults if not set info.network = info.network || Networks.get(network) || Networks.defaultNetwork; info.type = info.type || type || Address.PayToPublicKeyHash; JSUtil.defineImmutable(this, { hashBuffer: info.hashBuffer, network: info.network, type: info.type }); return this; } /** * Internal function used to split different kinds of arguments of the constructor * @param {*} data - The encoded data in various formats * @param {Network|String|number=} network - The network: 'livenet' or 'testnet' * @param {string=} type - The type of address: 'script' or 'pubkey' * @returns {Object} An "info" object with "type", "network", and "hashBuffer" */ Address.prototype._classifyArguments = function(data, network, type) { /* jshint maxcomplexity: 10 */ // transform and validate input data if ((data instanceof Buffer || data instanceof Uint8Array) && data.length === 20) { return Address._transformHash(data); } else if ((data instanceof Buffer || data instanceof Uint8Array) && data.length === 21) { return Address._transformBuffer(data, network, type); } else if (data instanceof PublicKey) { return Address._transformPublicKey(data); } else if (data instanceof Script) { return Address._transformScript(data, network); } else if (typeof(data) === 'string') { return Address._transformString(data, network, type); } else if (_.isObject(data)) { return Address._transformObject(data); } else { throw new TypeError('First argument is an unrecognized data format.'); } }; /** @static */ Address.PayToPublicKeyHash = 'pubkeyhash'; /** @static */ Address.PayToScriptHash = 'scripthash'; /** * @param {Buffer} hash - An instance of a hash Buffer * @returns {Object} An object with keys: hashBuffer * @private */ Address._transformHash = function(hash) { var info = {}; if (!(hash instanceof Buffer) && !(hash instanceof Uint8Array)) { throw new TypeError('Address supplied is not a buffer.'); } if (hash.length !== 20) { throw new TypeError('Address hashbuffers must be exactly 20 bytes.'); } info.hashBuffer = hash; return info; }; /** * Deserializes an address serialized through `Address#toObject()` * @param {Object} data * @param {string} data.hash - the hash that this address encodes * @param {string} data.type - either 'pubkeyhash' or 'scripthash' * @param {Network=} data.network - the name of the network associated * @return {Address} */ Address._transformObject = function(data) { $.checkArgument(data.hash || data.hashBuffer, 'Must provide a `hash` or `hashBuffer` property'); $.checkArgument(data.type, 'Must provide a `type` property'); return { hashBuffer: data.hash ? new Buffer(data.hash, 'hex') : data.hashBuffer, network: Networks.get(data.network) || Networks.defaultNetwork, type: data.type }; }; /** * Internal function to discover the network and type based on the first data byte * * @param {Buffer} buffer - An instance of a hex encoded address Buffer * @returns {Object} An object with keys: network and type * @private */ Address._classifyFromVersion = function(buffer) { var version = {}; var pubkeyhashNetwork = Networks.get(buffer[0], 'pubkeyhash'); var scripthashNetwork = Networks.get(buffer[0], 'scripthash'); if (pubkeyhashNetwork) { version.network = pubkeyhashNetwork; version.type = Address.PayToPublicKeyHash; } else if (scripthashNetwork) { version.network = scripthashNetwork; version.type = Address.PayToScriptHash; } return version; }; /** * Internal function to transform a bitcoin address buffer * * @param {Buffer} buffer - An instance of a hex encoded address Buffer * @param {string=} network - The network: 'livenet' or 'testnet' * @param {string=} type - The type: 'pubkeyhash' or 'scripthash' * @returns {Object} An object with keys: hashBuffer, network and type * @private */ Address._transformBuffer = function(buffer, network, type) { /* jshint maxcomplexity: 9 */ var info = {}; if (!(buffer instanceof Buffer) && !(buffer instanceof Uint8Array)) { throw new TypeError('Address supplied is not a buffer.'); } if (buffer.length !== 1 + 20) { throw new TypeError('Address buffers must be exactly 21 bytes.'); } network = Networks.get(network); var bufferVersion = Address._classifyFromVersion(buffer); if (!bufferVersion.network || (network && network !== bufferVersion.network)) { throw new TypeError('Address has mismatched network type.'); } if (!bufferVersion.type || (type && type !== bufferVersion.type)) { throw new TypeError('Address has mismatched type.'); } info.hashBuffer = buffer.slice(1); info.network = bufferVersion.network; info.type = bufferVersion.type; return info; }; /** * Internal function to transform a {@link PublicKey} * * @param {PublicKey} pubkey - An instance of PublicKey * @returns {Object} An object with keys: hashBuffer, type * @private */ Address._transformPublicKey = function(pubkey) { var info = {}; if (!(pubkey instanceof PublicKey)) { throw new TypeError('Address must be an instance of PublicKey.'); } info.hashBuffer = Hash.sha256ripemd160(pubkey.toBuffer()); info.type = Address.PayToPublicKeyHash; return info; }; /** * Internal function to transform a {@link Script} into a `info` object. * * @param {Script} script - An instance of Script * @returns {Object} An object with keys: hashBuffer, type * @private */ Address._transformScript = function(script, network) { $.checkArgument(script instanceof Script, 'script must be a Script instance'); var info = script.getAddressInfo(network); if (!info) { throw new errors.Script.CantDeriveAddress(script); } return info; }; /** * Creates a P2SH address from a set of public keys and a threshold. * * The addresses will be sorted lexicographically, as that is the trend in bitcoin. * To create an address from unsorted public keys, use the {@link Script#buildMultisigOut} * interface. * * @param {Array} publicKeys - a set of public keys to create an address * @param {number} threshold - the number of signatures needed to release the funds * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet' * @return {Address} */ Address.createMultisig = function(publicKeys, threshold, network) { network = network || publicKeys[0].network || Networks.defaultNetwork; return Address.payingTo(Script.buildMultisigOut(publicKeys, threshold), network); }; /** * Internal function to transform a bitcoin address string * * @param {string} data * @param {String|Network=} network - either a Network instance, 'livenet', or 'testnet' * @param {string=} type - The type: 'pubkeyhash' or 'scripthash' * @returns {Object} An object with keys: hashBuffer, network and type * @private */ Address._transformString = function(data, network, type) { if (typeof(data) !== 'string') { throw new TypeError('data parameter supplied is not a string.'); } data = data.trim(); var addressBuffer = Base58Check.decode(data); var info = Address._transformBuffer(addressBuffer, network, type); return info; }; /** * Instantiate an address from a PublicKey instance * * @param {PublicKey} data * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet' * @returns {Address} A new valid and frozen instance of an Address */ Address.fromPublicKey = function(data, network) { var info = Address._transformPublicKey(data); network = network || Networks.defaultNetwork; return new Address(info.hashBuffer, network, info.type); }; /** * Instantiate an address from a ripemd160 public key hash * * @param {Buffer} hash - An instance of buffer of the hash * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet' * @returns {Address} A new valid and frozen instance of an Address */ Address.fromPublicKeyHash = function(hash, network) { var info = Address._transformHash(hash); return new Address(info.hashBuffer, network, Address.PayToPublicKeyHash); }; /** * Instantiate an address from a ripemd160 script hash * * @param {Buffer} hash - An instance of buffer of the hash * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet' * @returns {Address} A new valid and frozen instance of an Address */ Address.fromScriptHash = function(hash, network) { $.checkArgument(hash, 'hash parameter is required'); var info = Address._transformHash(hash); return new Address(info.hashBuffer, network, Address.PayToScriptHash); }; /** * Builds a p2sh address paying to script. This will hash the script and * use that to create the address. * If you want to extract an address associated with a script instead, * see {{Address#fromScript}} * * @param {Script} script - An instance of Script * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet' * @returns {Address} A new valid and frozen instance of an Address */ Address.payingTo = function(script, network) { $.checkArgument(script, 'script is required'); $.checkArgument(script instanceof Script, 'script must be instance of Script'); return Address.fromScriptHash(Hash.sha256ripemd160(script.toBuffer()), network); }; /** * Extract address from a Script. The script must be of one * of the following types: p2pkh input, p2pkh output, p2sh input * or p2sh output. * This will analyze the script and extract address information from it. * If you want to transform any script to a p2sh Address paying * to that script's hash instead, use {{Address#payingTo}} * * @param {Script} script - An instance of Script * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet' * @returns {Address} A new valid and frozen instance of an Address */ Address.fromScript = function(script, network) { $.checkArgument(script instanceof Script, 'script must be a Script instance'); var info = Address._transformScript(script, network); return new Address(info.hashBuffer, network, info.type); }; /** * Instantiate an address from a buffer of the address * * @param {Buffer} buffer - An instance of buffer of the address * @param {String|Network=} network - either a Network instance, 'livenet', or 'testnet' * @param {string=} type - The type of address: 'script' or 'pubkey' * @returns {Address} A new valid and frozen instance of an Address */ Address.fromBuffer = function(buffer, network, type) { var info = Address._transformBuffer(buffer, network, type); return new Address(info.hashBuffer, info.network, info.type); }; /** * Instantiate an address from an address string * * @param {string} str - An string of the bitcoin address * @param {String|Network=} network - either a Network instance, 'livenet', or 'testnet' * @param {string=} type - The type of address: 'script' or 'pubkey' * @returns {Address} A new valid and frozen instance of an Address */ Address.fromString = function(str, network, type) { var info = Address._transformString(str, network, type); return new Address(info.hashBuffer, info.network, info.type); }; /** * Instantiate an address from JSON * * @param {string} json - An JSON string or Object with keys: hash, network and type * @returns {Address} A new valid instance of an Address */ Address.fromJSON = function fromJSON(json) { if (JSUtil.isValidJSON(json)) { json = JSON.parse(json); } $.checkState( JSUtil.isHexa(json.hash), 'Unexpected hash property, "' + json.hash + '", expected to be hex.' ); var hashBuffer = new Buffer(json.hash, 'hex'); return new Address(hashBuffer, json.network, json.type); }; /** * Will return a validation error if exists * * @example * ```javascript * // a network mismatch error * var error = Address.getValidationError('15vkcKf7gB23wLAnZLmbVuMiiVDc1Nm4a2', 'testnet'); * ``` * * @param {string} data - The encoded data * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet' * @param {string} type - The type of address: 'script' or 'pubkey' * @returns {null|Error} The corresponding error message */ Address.getValidationError = function(data, network, type) { var error; try { /* jshint nonew: false */ new Address(data, network, type); } catch (e) { error = e; } return error; }; /** * Will return a boolean if an address is valid * * @example * ```javascript * assert(Address.isValid('15vkcKf7gB23wLAnZLmbVuMiiVDc1Nm4a2', 'livenet')); * ``` * * @param {string} data - The encoded data * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet' * @param {string} type - The type of address: 'script' or 'pubkey' * @returns {boolean} The corresponding error message */ Address.isValid = function(data, network, type) { return !Address.getValidationError(data, network, type); }; /** * Returns true if an address is of pay to public key hash type * @return boolean */ Address.prototype.isPayToPublicKeyHash = function() { return this.type === Address.PayToPublicKeyHash; }; /** * Returns true if an address is of pay to script hash type * @return boolean */ Address.prototype.isPayToScriptHash = function() { return this.type === Address.PayToScriptHash; }; /** * Will return a buffer representation of the address * * @returns {Buffer} Bitcoin address buffer */ Address.prototype.toBuffer = function() { var version = new Buffer([this.network[this.type]]); var buf = Buffer.concat([version, this.hashBuffer]); return buf; }; /** * @returns {Object} A plain object with the address information */ Address.prototype.toObject = function toObject() { return { hash: this.hashBuffer.toString('hex'), type: this.type, network: this.network.toString() }; }; /** * @returns {string} A JSON representation of a plain object with the address information */ Address.prototype.toJSON = function toJSON() { return JSON.stringify(this.toObject()); }; /** * Will return a the string representation of the address * * @returns {string} Bitcoin address */ Address.prototype.toString = function() { return Base58Check.encode(this.toBuffer()); }; /** * Will return a string formatted for the console * * @returns {string} Bitcoin address */ Address.prototype.inspect = function() { return '<Address: ' + this.toString() + ', type: ' + this.type + ', network: ' + this.network + '>'; }; module.exports = Address;
L.Control.Panel = L.Control.extend({ initialize: function(options) { L.Control.prototype.initialize.call(this, null, options); L.Util.setOptions(this, options); }, onAdd: function(map) { this.hidden = true; map.activePanel = this; this._initLayout(); return this._container; }, show: function(feature) { var closeHTML = "<div id='close-" + this._container.id + "' class='close-panel'></div>"; this._container.innerHTML = closeHTML + this.options.template.generateContent(feature); $("#" + this._container.id).removeClass("panel-control-hidden"); this.hidden = false; if (this.options.onShow) { this.options.onShow(); } }, hide: function(feature) { this._container.innerHTML = ""; $("#" + this._container.id).addClass("panel-control-hidden"); this.hidden = true; }, _initLayout: function() { var mapHeight = this._map.getSize().y; var panelHeight = mapHeight; var panelWidth = this.options.width || 200; var panelId = this.options.id || 'panel-control'; this._container = L.DomUtil.create('div', 'panel-control-hidden'); this._container.id = panelId; this._container.style.height = panelHeight + "px"; this._container.style.width = panelWidth + "px"; this._container.style.margin = "0px"; if (!L.Browser.touch) { L.DomEvent.disableClickPropagation(this._container); } else { L.DomEvent.addListener(this._container, 'click', L.DomEvent.stopPropagation); } } });
/*global define*/ define([ '../Core/defaultValue', '../Core/defined', '../Core/defineProperties', '../Core/DeveloperError', '../Core/Event', './createPropertyDescriptor' ], function( defaultValue, defined, defineProperties, DeveloperError, Event, createPropertyDescriptor) { 'use strict'; /** * Describes a two dimensional icon located at the position of the containing {@link Entity}. * <p> * <div align='center'> * <img src='images/Billboard.png' width='400' height='300' /><br /> * Example billboards * </div> * </p> * * @alias BillboardGraphics * @constructor * * @param {Object} [options] Object with the following properties: * @param {Property} [options.image] A Property specifying the Image, URI, or Canvas to use for the billboard. * @param {Property} [options.show=true] A boolean Property specifying the visibility of the billboard. * @param {Property} [options.scale=1.0] A numeric Property specifying the scale to apply to the image size. * @param {Property} [options.horizontalOrigin=HorizontalOrigin.CENTER] A Property specifying the {@link HorizontalOrigin}. * @param {Property} [options.verticalOrigin=VerticalOrigin.CENTER] A Property specifying the {@link VerticalOrigin}. * @param {Property} [options.eyeOffset=Cartesian3.ZERO] A {@link Cartesian3} Property specifying the eye offset. * @param {Property} [options.pixelOffset=Cartesian2.ZERO] A {@link Cartesian2} Property specifying the pixel offset. * @param {Property} [options.rotation=0] A numeric Property specifying the rotation about the alignedAxis. * @param {Property} [options.alignedAxis=Cartesian3.ZERO] A {@link Cartesian3} Property specifying the unit vector axis of rotation. * @param {Property} [options.width] A numeric Property specifying the width of the billboard in pixels, overriding the native size. * @param {Property} [options.height] A numeric Property specifying the height of the billboard in pixels, overriding the native size. * @param {Property} [options.color=Color.WHITE] A Property specifying the tint {@link Color} of the image. * @param {Property} [options.scaleByDistance] A {@link NearFarScalar} Property used to scale the point based on distance from the camera. * @param {Property} [options.translucencyByDistance] A {@link NearFarScalar} Property used to set translucency based on distance from the camera. * @param {Property} [options.pixelOffsetScaleByDistance] A {@link NearFarScalar} Property used to set pixelOffset based on distance from the camera. * @param {Property} [options.imageSubRegion] A Property specifying a {@link BoundingRectangle} that defines a sub-region of the image to use for the billboard, rather than the entire image, measured in pixels from the bottom-left. * @param {Property} [options.sizeInMeters] A boolean Property specifying whether this billboard's size should be measured in meters. * @param {Property} [options.heightReference=HeightReference.NONE] A Property specifying what the height is relative to. * @param {Property} [options.distanceDisplayCondition] A Property specifying at what distance from the camera that this billboard will be displayed. * * @demo {@link http://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=Billboards.html|Cesium Sandcastle Billboard Demo} */ function BillboardGraphics(options) { this._image = undefined; this._imageSubscription = undefined; this._imageSubRegion = undefined; this._imageSubRegionSubscription = undefined; this._width = undefined; this._widthSubscription = undefined; this._height = undefined; this._heightSubscription = undefined; this._scale = undefined; this._scaleSubscription = undefined; this._rotation = undefined; this._rotationSubscription = undefined; this._alignedAxis = undefined; this._alignedAxisSubscription = undefined; this._horizontalOrigin = undefined; this._horizontalOriginSubscription = undefined; this._verticalOrigin = undefined; this._verticalOriginSubscription = undefined; this._color = undefined; this._colorSubscription = undefined; this._eyeOffset = undefined; this._eyeOffsetSubscription = undefined; this._heightReference = undefined; this._heightReferenceSubscription = undefined; this._pixelOffset = undefined; this._pixelOffsetSubscription = undefined; this._show = undefined; this._showSubscription = undefined; this._scaleByDistance = undefined; this._scaleByDistanceSubscription = undefined; this._translucencyByDistance = undefined; this._translucencyByDistanceSubscription = undefined; this._pixelOffsetScaleByDistance = undefined; this._pixelOffsetScaleByDistanceSubscription = undefined; this._sizeInMeters = undefined; this._sizeInMetersSubscription = undefined; this._distanceDisplayCondition = undefined; this._distanceDisplayConditionSubscription = undefined; this._definitionChanged = new Event(); this.merge(defaultValue(options, defaultValue.EMPTY_OBJECT)); } defineProperties(BillboardGraphics.prototype, { /** * Gets the event that is raised whenever a property or sub-property is changed or modified. * @memberof BillboardGraphics.prototype * * @type {Event} * @readonly */ definitionChanged : { get : function() { return this._definitionChanged; } }, /** * Gets or sets the Property specifying the Image, URI, or Canvas to use for the billboard. * @memberof BillboardGraphics.prototype * @type {Property} */ image : createPropertyDescriptor('image'), /** * Gets or sets the Property specifying a {@link BoundingRectangle} that defines a * sub-region of the <code>image</code> to use for the billboard, rather than the entire image, * measured in pixels from the bottom-left. * @memberof BillboardGraphics.prototype * @type {Property} */ imageSubRegion : createPropertyDescriptor('imageSubRegion'), /** * Gets or sets the numeric Property specifying the uniform scale to apply to the image. * A scale greater than <code>1.0</code> enlarges the billboard while a scale less than <code>1.0</code> shrinks it. * <p> * <div align='center'> * <img src='images/Billboard.setScale.png' width='400' height='300' /><br/> * From left to right in the above image, the scales are <code>0.5</code>, <code>1.0</code>, and <code>2.0</code>. * </div> * </p> * @memberof BillboardGraphics.prototype * @type {Property} * @default 1.0 */ scale : createPropertyDescriptor('scale'), /** * Gets or sets the numeric Property specifying the rotation of the image * counter clockwise from the <code>alignedAxis</code>. * @memberof BillboardGraphics.prototype * @type {Property} * @default 0 */ rotation : createPropertyDescriptor('rotation'), /** * Gets or sets the {@link Cartesian3} Property specifying the unit vector axis of rotation * in the fixed frame. When set to Cartesian3.ZERO the rotation is from the top of the screen. * @memberof BillboardGraphics.prototype * @type {Property} * @default Cartesian3.ZERO */ alignedAxis : createPropertyDescriptor('alignedAxis'), /** * Gets or sets the Property specifying the {@link HorizontalOrigin}. * @memberof BillboardGraphics.prototype * @type {Property} * @default HorizontalOrigin.CENTER */ horizontalOrigin : createPropertyDescriptor('horizontalOrigin'), /** * Gets or sets the Property specifying the {@link VerticalOrigin}. * @memberof BillboardGraphics.prototype * @type {Property} * @default VerticalOrigin.CENTER */ verticalOrigin : createPropertyDescriptor('verticalOrigin'), /** * Gets or sets the Property specifying the {@link Color} that is multiplied with the <code>image</code>. * This has two common use cases. First, the same white texture may be used by many different billboards, * each with a different color, to create colored billboards. Second, the color's alpha component can be * used to make the billboard translucent as shown below. An alpha of <code>0.0</code> makes the billboard * transparent, and <code>1.0</code> makes the billboard opaque. * <p> * <div align='center'> * <table border='0' cellpadding='5'><tr> * <td align='center'><code>default</code><br/><img src='images/Billboard.setColor.Alpha255.png' width='250' height='188' /></td> * <td align='center'><code>alpha : 0.5</code><br/><img src='images/Billboard.setColor.Alpha127.png' width='250' height='188' /></td> * </tr></table> * </div> * </p> * @memberof BillboardGraphics.prototype * @type {Property} * @default Color.WHITE */ color : createPropertyDescriptor('color'), /** * Gets or sets the {@link Cartesian3} Property specifying the billboard's offset in eye coordinates. * Eye coordinates is a left-handed coordinate system, where <code>x</code> points towards the viewer's * right, <code>y</code> points up, and <code>z</code> points into the screen. * <p> * An eye offset is commonly used to arrange multiple billboards or objects at the same position, e.g., to * arrange a billboard above its corresponding 3D model. * </p> * Below, the billboard is positioned at the center of the Earth but an eye offset makes it always * appear on top of the Earth regardless of the viewer's or Earth's orientation. * <p> * <div align='center'> * <table border='0' cellpadding='5'><tr> * <td align='center'><img src='images/Billboard.setEyeOffset.one.png' width='250' height='188' /></td> * <td align='center'><img src='images/Billboard.setEyeOffset.two.png' width='250' height='188' /></td> * </tr></table> * <code>b.eyeOffset = new Cartesian3(0.0, 8000000.0, 0.0);</code> * </div> * </p> * @memberof BillboardGraphics.prototype * @type {Property} * @default Cartesian3.ZERO */ eyeOffset : createPropertyDescriptor('eyeOffset'), /** * Gets or sets the Property specifying the {@link HeightReference}. * @memberof BillboardGraphics.prototype * @type {Property} * @default HeightReference.NONE */ heightReference : createPropertyDescriptor('heightReference'), /** * Gets or sets the {@link Cartesian2} Property specifying the billboard's pixel offset in screen space * from the origin of this billboard. This is commonly used to align multiple billboards and labels at * the same position, e.g., an image and text. The screen space origin is the top, left corner of the * canvas; <code>x</code> increases from left to right, and <code>y</code> increases from top to bottom. * <p> * <div align='center'> * <table border='0' cellpadding='5'><tr> * <td align='center'><code>default</code><br/><img src='images/Billboard.setPixelOffset.default.png' width='250' height='188' /></td> * <td align='center'><code>b.pixeloffset = new Cartesian2(50, 25);</code><br/><img src='images/Billboard.setPixelOffset.x50y-25.png' width='250' height='188' /></td> * </tr></table> * The billboard's origin is indicated by the yellow point. * </div> * </p> * @memberof BillboardGraphics.prototype * @type {Property} * @default Cartesian2.ZERO */ pixelOffset : createPropertyDescriptor('pixelOffset'), /** * Gets or sets the boolean Property specifying the visibility of the billboard. * @memberof BillboardGraphics.prototype * @type {Property} * @default true */ show : createPropertyDescriptor('show'), /** * Gets or sets the numeric Property specifying the billboard's width in pixels. * When undefined, the native width is used. * @memberof BillboardGraphics.prototype * @type {Property} */ width : createPropertyDescriptor('width'), /** * Gets or sets the numeric Property specifying the height of the billboard in pixels. * When undefined, the native height is used. * @memberof BillboardGraphics.prototype * @type {Property} */ height : createPropertyDescriptor('height'), /** * Gets or sets {@link NearFarScalar} Property specifying the scale of the billboard based on the distance from the camera. * A billboard's scale will interpolate between the {@link NearFarScalar#nearValue} and * {@link NearFarScalar#farValue} while the camera distance falls within the upper and lower bounds * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}. * Outside of these ranges the billboard's scale remains clamped to the nearest bound. * @memberof BillboardGraphics.prototype * @type {Property} */ scaleByDistance : createPropertyDescriptor('scaleByDistance'), /** * Gets or sets {@link NearFarScalar} Property specifying the translucency of the billboard based on the distance from the camera. * A billboard's translucency will interpolate between the {@link NearFarScalar#nearValue} and * {@link NearFarScalar#farValue} while the camera distance falls within the upper and lower bounds * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}. * Outside of these ranges the billboard's translucency remains clamped to the nearest bound. * @memberof BillboardGraphics.prototype * @type {Property} */ translucencyByDistance : createPropertyDescriptor('translucencyByDistance'), /** * Gets or sets {@link NearFarScalar} Property specifying the pixel offset of the billboard based on the distance from the camera. * A billboard's pixel offset will interpolate between the {@link NearFarScalar#nearValue} and * {@link NearFarScalar#farValue} while the camera distance falls within the upper and lower bounds * of the specified {@link NearFarScalar#near} and {@link NearFarScalar#far}. * Outside of these ranges the billboard's pixel offset remains clamped to the nearest bound. * @memberof BillboardGraphics.prototype * @type {Property} */ pixelOffsetScaleByDistance : createPropertyDescriptor('pixelOffsetScaleByDistance'), /** * Gets or sets the boolean Property specifying if this billboard's size will be measured in meters. * @memberof BillboardGraphics.prototype * @type {Property} * @default false */ sizeInMeters : createPropertyDescriptor('sizeInMeters'), /** * Gets or sets the {@link DistanceDisplayCondition} Property specifying at what distance from the camera that this billboard will be displayed. * @memberof BillboardGraphics.prototype * @type {Property} */ distanceDisplayCondition : createPropertyDescriptor('distanceDisplayCondition') }); /** * Duplicates this instance. * * @param {BillboardGraphics} [result] The object onto which to store the result. * @returns {BillboardGraphics} The modified result parameter or a new instance if one was not provided. */ BillboardGraphics.prototype.clone = function(result) { if (!defined(result)) { return new BillboardGraphics(this); } result.color = this._color; result.eyeOffset = this._eyeOffset; result.heightReference = this._heightReference; result.horizontalOrigin = this._horizontalOrigin; result.image = this._image; result.imageSubRegion = this._imageSubRegion; result.pixelOffset = this._pixelOffset; result.scale = this._scale; result.rotation = this._rotation; result.alignedAxis = this._alignedAxis; result.show = this._show; result.verticalOrigin = this._verticalOrigin; result.width = this._width; result.height = this._height; result.scaleByDistance = this._scaleByDistance; result.translucencyByDistance = this._translucencyByDistance; result.pixelOffsetScaleByDistance = this._pixelOffsetScaleByDistance; result.sizeInMeters = this._sizeInMeters; result.distanceDisplayCondition = this._distanceDisplayCondition; return result; }; /** * Assigns each unassigned property on this object to the value * of the same property on the provided source object. * * @param {BillboardGraphics} source The object to be merged into this object. */ BillboardGraphics.prototype.merge = function(source) { //>>includeStart('debug', pragmas.debug); if (!defined(source)) { throw new DeveloperError('source is required.'); } //>>includeEnd('debug'); this.color = defaultValue(this._color, source.color); this.eyeOffset = defaultValue(this._eyeOffset, source.eyeOffset); this.heightReference = defaultValue(this._heightReference, source.heightReference); this.horizontalOrigin = defaultValue(this._horizontalOrigin, source.horizontalOrigin); this.image = defaultValue(this._image, source.image); this.imageSubRegion = defaultValue(this._imageSubRegion, source.imageSubRegion); this.pixelOffset = defaultValue(this._pixelOffset, source.pixelOffset); this.scale = defaultValue(this._scale, source.scale); this.rotation = defaultValue(this._rotation, source.rotation); this.alignedAxis = defaultValue(this._alignedAxis, source.alignedAxis); this.show = defaultValue(this._show, source.show); this.verticalOrigin = defaultValue(this._verticalOrigin, source.verticalOrigin); this.width = defaultValue(this._width, source.width); this.height = defaultValue(this._height, source.height); this.scaleByDistance = defaultValue(this._scaleByDistance, source.scaleByDistance); this.translucencyByDistance = defaultValue(this._translucencyByDistance, source.translucencyByDistance); this.pixelOffsetScaleByDistance = defaultValue(this._pixelOffsetScaleByDistance, source.pixelOffsetScaleByDistance); this.sizeInMeters = defaultValue(this._sizeInMeters, source.sizeInMeters); this.distanceDisplayCondition = defaultValue(this._distanceDisplayCondition, source.distanceDisplayCondition); }; return BillboardGraphics; });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isStatelessComponent; // weak function isJSXElementOrReactCreateElement(path) { var visited = false; path.traverse({ CallExpression: function CallExpression(path2) { var callee = path2.get('callee'); if (callee.matchesPattern('React.createElement') || callee.matchesPattern('React.cloneElement')) { visited = true; } }, JSXElement: function JSXElement() { visited = true; } }); return visited; } function isReturningJSXElement(path) { // Early exit for ArrowFunctionExpressions, there is no ReturnStatement node. if (path.node.init && path.node.init.body && isJSXElementOrReactCreateElement(path)) { return true; } var visited = false; path.traverse({ ReturnStatement: function ReturnStatement(path2) { // We have already found what we are looking for. if (visited) { return; } var argument = path2.get('argument'); // Nothing is returned if (!argument.node) { return; } if (isJSXElementOrReactCreateElement(path2)) { visited = true; return; } if (argument.node.type === 'CallExpression') { var name = argument.get('callee').node.name; var binding = path.scope.getBinding(name); if (!binding) { return; } if (isReturningJSXElement(binding.path)) { visited = true; } } } }); return visited; } var VALID_POSSIBLE_STATELESS_COMPONENT_TYPES = ['VariableDeclarator', 'FunctionDeclaration']; // Returns `true` if the path represents a function which returns a JSXElement function isStatelessComponent(path) { if (VALID_POSSIBLE_STATELESS_COMPONENT_TYPES.indexOf(path.node.type) === -1) { return false; } if (isReturningJSXElement(path)) { return true; } return false; }
import { document } from 'ssr-window'; import $ from '../../../utils/dom'; import Utils from '../../../utils/utils'; export default function (event) { const swiper = this; const data = swiper.touchEventsData; const { params, touches, rtlTranslate: rtl } = swiper; let e = event; if (e.originalEvent) e = e.originalEvent; if (!data.isTouched) { if (data.startMoving && data.isScrolling) { swiper.emit('touchMoveOpposite', e); } return; } if (data.isTouchEvent && e.type === 'mousemove') return; const pageX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX; const pageY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY; if (e.preventedByNestedSwiper) { touches.startX = pageX; touches.startY = pageY; return; } if (!swiper.allowTouchMove) { // isMoved = true; swiper.allowClick = false; if (data.isTouched) { Utils.extend(touches, { startX: pageX, startY: pageY, currentX: pageX, currentY: pageY, }); data.touchStartTime = Utils.now(); } return; } if (data.isTouchEvent && params.touchReleaseOnEdges && !params.loop) { if (swiper.isVertical()) { // Vertical if ( (pageY < touches.startY && swiper.translate <= swiper.maxTranslate()) || (pageY > touches.startY && swiper.translate >= swiper.minTranslate()) ) { data.isTouched = false; data.isMoved = false; return; } } else if ( (pageX < touches.startX && swiper.translate <= swiper.maxTranslate()) || (pageX > touches.startX && swiper.translate >= swiper.minTranslate()) ) { return; } } if (data.isTouchEvent && document.activeElement) { if (e.target === document.activeElement && $(e.target).is(data.formElements)) { data.isMoved = true; swiper.allowClick = false; return; } } if (data.allowTouchCallbacks) { swiper.emit('touchMove', e); } if (e.targetTouches && e.targetTouches.length > 1) return; touches.currentX = pageX; touches.currentY = pageY; const diffX = touches.currentX - touches.startX; const diffY = touches.currentY - touches.startY; if (swiper.params.threshold && Math.sqrt((diffX ** 2) + (diffY ** 2)) < swiper.params.threshold) return; if (typeof data.isScrolling === 'undefined') { let touchAngle; if ((swiper.isHorizontal() && touches.currentY === touches.startY) || (swiper.isVertical() && touches.currentX === touches.startX)) { data.isScrolling = false; } else { // eslint-disable-next-line if ((diffX * diffX) + (diffY * diffY) >= 25) { touchAngle = (Math.atan2(Math.abs(diffY), Math.abs(diffX)) * 180) / Math.PI; data.isScrolling = swiper.isHorizontal() ? touchAngle > params.touchAngle : (90 - touchAngle > params.touchAngle); } } } if (data.isScrolling) { swiper.emit('touchMoveOpposite', e); } if (typeof data.startMoving === 'undefined') { if (touches.currentX !== touches.startX || touches.currentY !== touches.startY) { data.startMoving = true; } } if (data.isScrolling) { data.isTouched = false; return; } if (!data.startMoving) { return; } swiper.allowClick = false; e.preventDefault(); if (params.touchMoveStopPropagation && !params.nested) { e.stopPropagation(); } if (!data.isMoved) { if (params.loop) { swiper.loopFix(); } data.startTranslate = swiper.getTranslate(); swiper.setTransition(0); if (swiper.animating) { swiper.$wrapperEl.trigger('webkitTransitionEnd transitionend'); } data.allowMomentumBounce = false; // Grab Cursor if (params.grabCursor && (swiper.allowSlideNext === true || swiper.allowSlidePrev === true)) { swiper.setGrabCursor(true); } swiper.emit('sliderFirstMove', e); } swiper.emit('sliderMove', e); data.isMoved = true; let diff = swiper.isHorizontal() ? diffX : diffY; touches.diff = diff; diff *= params.touchRatio; if (rtl) diff = -diff; swiper.swipeDirection = diff > 0 ? 'prev' : 'next'; data.currentTranslate = diff + data.startTranslate; let disableParentSwiper = true; let resistanceRatio = params.resistanceRatio; if (params.touchReleaseOnEdges) { resistanceRatio = 0; } if ((diff > 0 && data.currentTranslate > swiper.minTranslate())) { disableParentSwiper = false; if (params.resistance) data.currentTranslate = (swiper.minTranslate() - 1) + ((-swiper.minTranslate() + data.startTranslate + diff) ** resistanceRatio); } else if (diff < 0 && data.currentTranslate < swiper.maxTranslate()) { disableParentSwiper = false; if (params.resistance) data.currentTranslate = (swiper.maxTranslate() + 1) - ((swiper.maxTranslate() - data.startTranslate - diff) ** resistanceRatio); } if (disableParentSwiper) { e.preventedByNestedSwiper = true; } // Directions locks if (!swiper.allowSlideNext && swiper.swipeDirection === 'next' && data.currentTranslate < data.startTranslate) { data.currentTranslate = data.startTranslate; } if (!swiper.allowSlidePrev && swiper.swipeDirection === 'prev' && data.currentTranslate > data.startTranslate) { data.currentTranslate = data.startTranslate; } // Threshold if (params.threshold > 0) { if (Math.abs(diff) > params.threshold || data.allowThresholdMove) { if (!data.allowThresholdMove) { data.allowThresholdMove = true; touches.startX = touches.currentX; touches.startY = touches.currentY; data.currentTranslate = data.startTranslate; touches.diff = swiper.isHorizontal() ? touches.currentX - touches.startX : touches.currentY - touches.startY; return; } } else { data.currentTranslate = data.startTranslate; return; } } if (!params.followFinger) return; // Update active index in free mode if (params.freeMode || params.watchSlidesProgress || params.watchSlidesVisibility) { swiper.updateActiveIndex(); swiper.updateSlidesClasses(); } if (params.freeMode) { // Velocity if (data.velocities.length === 0) { data.velocities.push({ position: touches[swiper.isHorizontal() ? 'startX' : 'startY'], time: data.touchStartTime, }); } data.velocities.push({ position: touches[swiper.isHorizontal() ? 'currentX' : 'currentY'], time: Utils.now(), }); } // Update progress swiper.updateProgress(data.currentTranslate); // Update translate swiper.setTranslate(data.currentTranslate); }
var searchData= [ ['readaxes',['readAxes',['../class_virtual_joystick.html#ac0ec476a1ace9195fffc0774bf332357',1,'VirtualJoystick']]], ['readbuttons',['readButtons',['../class_virtual_joystick.html#ac9d0aefa6e654d0a9e36bb913c83cac6',1,'VirtualJoystick']]], ['readpovs',['readPOVs',['../class_virtual_joystick.html#a70c1bbf238b3141525595d527247d3d6',1,'VirtualJoystick']]], ['resetjoysticks',['resetJoysticks',['../class_q_joysticks.html#a214d5d5f7cbb20f942d8d38c40aa80c4',1,'QJoysticks']]], ['rumble',['rumble',['../class_s_d_l___joysticks.html#a0817af463d8b74b6f8a128ab0b756617',1,'SDL_Joysticks']]] ];
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var reactIs = require('react-is'); var Stylis = _interopDefault(require('@emotion/stylis')); var _insertRulePlugin = _interopDefault(require('stylis-rule-sheet')); var unitless = _interopDefault(require('@emotion/unitless')); var validAttr = _interopDefault(require('@emotion/is-prop-valid')); var merge = _interopDefault(require('merge-anything')); var React = require('react'); var React__default = _interopDefault(React); var shallowequal = _interopDefault(require('shallowequal')); function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } // var interleave = (function (strings, interpolations) { var result = [strings[0]]; for (var i = 0, len = interpolations.length; i < len; i += 1) { result.push(interpolations[i], strings[i + 1]); } return result; }); // var isPlainObject = (function (x) { return typeof x === 'object' && x.constructor === Object; }); // var EMPTY_ARRAY = Object.freeze([]); var EMPTY_OBJECT = Object.freeze({}); // function isFunction(test) { return typeof test === 'function'; } // function getComponentName(target) { return (process.env.NODE_ENV !== 'production' ? typeof target === 'string' && target : false) || // $FlowFixMe target.displayName || // $FlowFixMe target.name || 'Component'; } // function isStatelessFunction(test) { return typeof test === 'function' && !(test.prototype && test.prototype.isReactComponent); } // function isStyledComponent(target) { return target && typeof target.styledComponentId === 'string'; } // var SC_ATTR = typeof process !== 'undefined' && (process.env.REACT_APP_SC_ATTR || process.env.SC_ATTR) || 'data-styled'; var SC_ATTR_ACTIVE = 'active'; var SC_ATTR_VERSION = 'data-styled-version'; var SC_VERSION = "5.0.0-beta.6-ej"; var IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window; var DISABLE_SPEEDY = typeof SC_DISABLE_SPEEDY === 'boolean' && SC_DISABLE_SPEEDY || typeof process !== 'undefined' && (process.env.REACT_APP_SC_DISABLE_SPEEDY || process.env.SC_DISABLE_SPEEDY) || process.env.NODE_ENV !== 'production'; // Shared empty execution context when generating static styles var STATIC_EXECUTION_CONTEXT = {}; var COMMENT_REGEX = /^\s*\/\/.*$/gm; function createStylisInstance(_temp) { var _ref = _temp === void 0 ? EMPTY_OBJECT : _temp, _ref$options = _ref.options, options = _ref$options === void 0 ? EMPTY_OBJECT : _ref$options, _ref$plugins = _ref.plugins, plugins = _ref$plugins === void 0 ? EMPTY_ARRAY : _ref$plugins; var stylis = new Stylis(options); // Wrap `insertRulePlugin to build a list of rules, // and then make our own plugin to return the rules. This // makes it easier to hook into the existing SSR architecture var parsingRules = []; // eslint-disable-next-line consistent-return var returnRulesPlugin = function returnRulesPlugin(context) { if (context === -2) { var parsedRules = parsingRules; parsingRules = []; return parsedRules; } }; var parseRulesPlugin = _insertRulePlugin(function (rule) { parsingRules.push(rule); }); var _componentId; var _selector; var _selectorRegexp; var selfReferenceReplacer = function selfReferenceReplacer(match, offset, string) { if ( // the first self-ref is always untouched offset > 0 && // there should be at least two self-refs to do a replacement (.b > .b) string.slice(0, offset).indexOf(_selector) !== -1 && // no consecutive self refs (.b.b); that is a precedence boost and treated differently string.slice(offset - _selector.length, offset) !== _selector) { return "." + _componentId; } return match; }; /** * When writing a style like * * & + & { * color: red; * } * * The second ampersand should be a reference to the static component class. stylis * has no knowledge of static class so we have to intelligently replace the base selector. * * https://github.com/thysultan/stylis.js#plugins <- more info about the context phase values * "2" means this plugin is taking effect at the very end after all other processing is complete */ var selfReferenceReplacementPlugin = function selfReferenceReplacementPlugin(context, _, selectors) { if (context === 2 && selectors.length && selectors[0].lastIndexOf(_selector) > 0) { // eslint-disable-next-line no-param-reassign selectors[0] = selectors[0].replace(_selectorRegexp, selfReferenceReplacer); } }; stylis.use([].concat(plugins, [selfReferenceReplacementPlugin, parseRulesPlugin, returnRulesPlugin])); return function stringifyRules(css, selector, prefix, componentId) { if (componentId === void 0) { componentId = '&'; } var flatCSS = css.replace(COMMENT_REGEX, ''); var cssStr = selector && prefix ? prefix + " " + selector + " { " + flatCSS + " }" : flatCSS; // stylis has no concept of state to be passed to plugins // but since JS is single=threaded, we can rely on that to ensure // these properties stay in sync with the current stylis run _componentId = componentId; _selector = selector; _selectorRegexp = new RegExp("\\" + _selector + "\\b", 'g'); return stylis(prefix || !selector ? '' : selector, cssStr); }; } // /* eslint-disable camelcase, no-undef */ var getNonce = function getNonce() { return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null; }; // var ELEMENT_TYPE = 1; /* Node.ELEMENT_TYPE */ /** Find last style element if any inside target */ var findLastStyleTag = function findLastStyleTag(target) { var childNodes = target.childNodes; for (var i = childNodes.length; i >= 0; i--) { var child = childNodes[i]; if (child && child.nodeType === ELEMENT_TYPE && child.hasAttribute(SC_ATTR)) { return child; } } return undefined; }; /** Create a style element inside `target` or <head> after the last */ var makeStyleTag = function makeStyleTag(target) { var head = document.head; var parent = target || head; var style = document.createElement('style'); var prevStyle = findLastStyleTag(parent); var nextSibling = prevStyle !== undefined ? prevStyle.nextSibling : null; style.setAttribute(SC_ATTR, SC_ATTR_ACTIVE); style.setAttribute(SC_ATTR_VERSION, SC_VERSION); var nonce = getNonce(); if (nonce) style.setAttribute('nonce', nonce); parent.insertBefore(style, nextSibling); return style; }; /** Get the CSSStyleSheet instance for a given style element */ var getSheet = function getSheet(tag) { if (tag.sheet) { return tag.sheet; } // Avoid Firefox quirk where the style element might not have a sheet property var _document = document, styleSheets = _document.styleSheets; for (var i = 0, l = styleSheets.length; i < l; i++) { var sheet = styleSheets[i]; if (sheet.ownerNode === tag) { return sheet; } } throw new TypeError("CSSStyleSheet could not be found on HTMLStyleElement"); }; // /** Create a CSSStyleSheet-like tag depending on the environment */ var makeTag = function makeTag(_ref) { var isServer = _ref.isServer, useCSSOMInjection = _ref.useCSSOMInjection, target = _ref.target; if (isServer) { return new VirtualTag(target); } else if (useCSSOMInjection) { return new CSSOMTag(target); } else { return new TextTag(target); } }; var CSSOMTag = /*#__PURE__*/ function () { function CSSOMTag(target) { var element = this.element = makeStyleTag(target); // Avoid Edge bug where empty style elements don't create sheets element.appendChild(document.createTextNode('')); this.sheet = getSheet(element); this.length = 0; } var _proto = CSSOMTag.prototype; _proto.insertRule = function insertRule(index, rule) { try { this.sheet.insertRule(rule, index); this.length++; return true; } catch (_error) { return false; } }; _proto.deleteRule = function deleteRule(index) { this.sheet.deleteRule(index); this.length--; }; _proto.getRule = function getRule(index) { var rule = this.sheet.cssRules[index]; // Avoid IE11 quirk where cssText is inaccessible on some invalid rules if (rule !== undefined && typeof rule.cssText === 'string') { return rule.cssText; } else { return ''; } }; return CSSOMTag; }(); /** A Tag that emulates the CSSStyleSheet API but uses text nodes */ var TextTag = /*#__PURE__*/ function () { function TextTag(target) { var element = this.element = makeStyleTag(target); this.nodes = element.childNodes; this.length = 0; } var _proto2 = TextTag.prototype; _proto2.insertRule = function insertRule(index, rule) { if (index <= this.length && index >= 0) { var node = document.createTextNode(rule); var refNode = this.nodes[index]; this.element.insertBefore(node, refNode || null); this.length++; return true; } else { return false; } }; _proto2.deleteRule = function deleteRule(index) { this.element.removeChild(this.nodes[index]); this.length--; }; _proto2.getRule = function getRule(index) { if (index < this.length) { return this.nodes[index].textContent; } else { return ''; } }; return TextTag; }(); /** A completely virtual (server-side) Tag that doesn't manipulate the DOM */ var VirtualTag = /*#__PURE__*/ function () { function VirtualTag(_target) { this.rules = []; this.length = 0; } var _proto3 = VirtualTag.prototype; _proto3.insertRule = function insertRule(index, rule) { if (index <= this.length) { this.rules.splice(index, 0, rule); this.length++; return true; } else { return false; } }; _proto3.deleteRule = function deleteRule(index) { this.rules.splice(index, 1); this.length--; }; _proto3.getRule = function getRule(index) { if (index < this.length) { return this.rules[index]; } else { return ''; } }; return VirtualTag; }(); // /* eslint-disable no-use-before-define */ /** Create a GroupedTag with an underlying Tag implementation */ var makeGroupedTag = function makeGroupedTag(tag) { return new DefaultGroupedTag(tag); }; var BASE_SIZE = 1 << 8; var DefaultGroupedTag = /*#__PURE__*/ function () { function DefaultGroupedTag(tag) { this.groupSizes = new Uint32Array(BASE_SIZE); this.length = BASE_SIZE; this.tag = tag; } var _proto = DefaultGroupedTag.prototype; _proto.indexOfGroup = function indexOfGroup(group) { var index = 0; for (var i = 0; i < group; i++) { index += this.groupSizes[i]; } return index; }; _proto.insertRules = function insertRules(group, rules) { if (group >= this.groupSizes.length) { var oldBuffer = this.groupSizes; var oldSize = oldBuffer.length; var newSize = BASE_SIZE << (group / BASE_SIZE | 0); this.groupSizes = new Uint32Array(newSize); this.groupSizes.set(oldBuffer); this.length = newSize; for (var i = oldSize; i < newSize; i++) { this.groupSizes[i] = 0; } } var startIndex = this.indexOfGroup(group + 1); for (var _i = 0, l = rules.length; _i < l; _i++) { if (this.tag.insertRule(startIndex + _i, rules[_i])) { this.groupSizes[group]++; } } }; _proto.clearGroup = function clearGroup(group) { if (group < this.length) { var length = this.groupSizes[group]; var startIndex = this.indexOfGroup(group); var endIndex = startIndex + length; this.groupSizes[group] = 0; for (var i = startIndex; i < endIndex; i++) { this.tag.deleteRule(startIndex); } } }; _proto.getGroup = function getGroup(group) { var css = ''; if (group >= this.length || this.groupSizes[group] === 0) { return css; } var length = this.groupSizes[group]; var startIndex = this.indexOfGroup(group); var endIndex = startIndex + length; for (var i = startIndex; i < endIndex; i++) { css += this.tag.getRule(i) + "\n"; } return css; }; return DefaultGroupedTag; }(); // var groupIDRegister = new Map(); var reverseRegister = new Map(); var nextFreeGroup = 1; var getGroupForId = function getGroupForId(id) { if (groupIDRegister.has(id)) { return groupIDRegister.get(id); } var group = nextFreeGroup++; groupIDRegister.set(id, group); reverseRegister.set(group, id); return group; }; var getIdForGroup = function getIdForGroup(group) { return reverseRegister.get(group); }; var setGroupForId = function setGroupForId(id, group) { if (group >= nextFreeGroup) { nextFreeGroup = group + 1; } groupIDRegister.set(id, group); reverseRegister.set(group, id); }; // var PLAIN_RULE_TYPE = 1; var SELECTOR = "style[" + SC_ATTR + "][" + SC_ATTR_VERSION + "=\"" + SC_VERSION + "\"]"; var MARKER_RE = new RegExp("^" + SC_ATTR + "\\.g(\\d+)\\[id=\"([\\w\\d-]+)\"\\]"); var outputSheet = function outputSheet(sheet) { var tag = sheet.getTag(); var length = tag.length; var css = ''; for (var group = 0; group < length; group++) { var id = getIdForGroup(group); if (id === undefined) continue; var names = sheet.names.get(id); var rules = tag.getGroup(group); if (names === undefined || rules.length === 0) continue; var selector = SC_ATTR + ".g" + group + "[id=\"" + id + "\"]"; var content = ''; if (names !== undefined) { names.forEach(function (name) { if (name.length > 0) { content += name + ","; } }); } // NOTE: It's easier to collect rules and have the marker // after the actual rules to simplify the rehydration css += "" + rules + selector + "{content:\"" + content + "\"}\n"; } return css; }; var rehydrateNamesFromContent = function rehydrateNamesFromContent(sheet, id, content) { var names = content.slice(1, -1).split(','); for (var i = 0, l = names.length; i < l; i++) { var name = names[i]; if (name.length > 0) { sheet.registerName(id, name); } } }; var rehydrateSheetFromTag = function rehydrateSheetFromTag(sheet, style) { var _getSheet = getSheet(style), cssRules = _getSheet.cssRules; var rules = []; for (var i = 0, l = cssRules.length; i < l; i++) { var cssRule = cssRules[i]; if (typeof cssRule.cssText !== 'string') { // Avoid IE11 quirk where cssText is inaccessible on some invalid rules continue; } else if (cssRule.type !== PLAIN_RULE_TYPE) { rules.push(cssRule.cssText); } else { var marker = cssRule.selectorText.match(MARKER_RE); if (marker !== null) { var group = parseInt(marker[1], 10) | 0; var id = marker[2]; var content = cssRule.style.content; if (group !== 0) { // Rehydrate componentId to group index mapping setGroupForId(id, group); // Rehydrate names and rules rehydrateNamesFromContent(sheet, id, content); sheet.getTag().insertRules(group, rules); } rules.length = 0; } else { rules.push(cssRule.cssText); } } } }; var rehydrateSheet = function rehydrateSheet(sheet) { var nodes = document.querySelectorAll(SELECTOR); for (var i = 0, l = nodes.length; i < l; i++) { var node = nodes[i]; if (node && node.getAttribute(SC_ATTR) !== SC_ATTR_ACTIVE) { rehydrateSheetFromTag(sheet, node); if (node.parentNode) { node.parentNode.removeChild(node); } } } }; var SHOULD_REHYDRATE = IS_BROWSER; var defaultOptions = { isServer: !IS_BROWSER, stringifier: createStylisInstance(), useCSSOMInjection: !DISABLE_SPEEDY }; /** Contains the main stylesheet logic for stringification and caching */ var StyleSheet = /*#__PURE__*/ function () { /** Register a group ID to give it an index */ StyleSheet.registerId = function registerId(id) { return getGroupForId(id); }; function StyleSheet(options) { if (options === void 0) { options = defaultOptions; } this.options = _extends({}, defaultOptions, options); this.names = new Map(); // We rehydrate only once and use the sheet that is // created first if (!this.options.isServer && IS_BROWSER && SHOULD_REHYDRATE) { SHOULD_REHYDRATE = false; rehydrateSheet(this); } } var _proto = StyleSheet.prototype; _proto.reconstructWithOptions = function reconstructWithOptions(options) { return new StyleSheet(_extends({}, this.options, options)); } /** Lazily initialises a GroupedTag for when it's actually needed */ ; _proto.getTag = function getTag() { return this.tag || (this.tag = makeGroupedTag(makeTag(this.options))); } /** Check whether a name is known for caching */ ; _proto.hasNameForId = function hasNameForId(id, name) { return this.names.has(id) && this.names.get(id).has(name); } /** Mark a group's name as known for caching */ ; _proto.registerName = function registerName(id, name) { getGroupForId(id); if (!this.names.has(id)) { var groupNames = new Set(); groupNames.add(name); this.names.set(id, groupNames); } else { this.names.get(id).add(name); } } /** Insert new rules which also marks the name as known */ ; _proto.insertRules = function insertRules(id, name, rules) { this.registerName(id, name); this.getTag().insertRules(getGroupForId(id), rules); } /** Clears all cached names for a given group ID */ ; _proto.clearNames = function clearNames(id) { if (this.names.has(id)) { this.names.get(id).clear(); } } /** Clears all rules for a given group ID */ ; _proto.clearRules = function clearRules(id) { this.getTag().clearGroup(getGroupForId(id)); this.clearNames(id); } /** Clears the entire tag which deletes all rules but not its names */ ; _proto.clearTag = function clearTag() { // NOTE: This does not clear the names, since it's only used during SSR // so that we can continuously output only new rules this.tag = undefined; } /** Outputs the current sheet as a CSS string with markers for SSR */ ; _proto.toString = function toString() { return outputSheet(this); }; return StyleSheet; }(); // var errorMap = { "1": "Cannot create styled-component for component: %s.\n\n", "2": "Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n", "3": "Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n", "4": "The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n", "5": "The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n", "6": "Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n", "7": "ThemeProvider: Please return an object from your \"theme\" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n", "8": "ThemeProvider: Please make your \"theme\" prop an object.\n\n", "9": "Missing document `<head>`\n\n", "10": "Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n", "11": "_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n\n", "12": "It seems you are interpolating a keyframe declaration (%s) into an untagged string. This was supported in styled-components v3, but is not longer supported in v4 as keyframes are now injected on-demand. Please wrap your string in the css\\`\\` helper (see https://www.styled-components.com/docs/api#css), which ensures the styles are injected correctly.\n\n", "13": "%s is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.\n" }; // var ERRORS = process.env.NODE_ENV !== 'production' ? errorMap : {}; /** * super basic version of sprintf */ function format() { var a = arguments.length <= 0 ? undefined : arguments[0]; var b = []; for (var c = 1, len = arguments.length; c < len; c += 1) { b.push(c < 0 || arguments.length <= c ? undefined : arguments[c]); } b.forEach(function (d) { a = a.replace(/%[a-z]/, d); }); return a; } /** * Create an error file out of errors.md for development and a simple web link to the full errors * in production mode. */ function throwStyledComponentsError(code) { for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } if (process.env.NODE_ENV === 'production') { throw new Error("An error occurred. See https://github.com/styled-components/styled-components/blob/master/packages/styled-components/src/utils/errors.md#" + code + " for more information." + (interpolations.length > 0 ? " Additional arguments: " + interpolations.join(', ') : '')); } else { throw new Error(format.apply(void 0, [ERRORS[code]].concat(interpolations)).trim()); } } // var Keyframes = /*#__PURE__*/ function () { function Keyframes(name, stringifyArgs) { var _this = this; this.inject = function (styleSheet) { if (!styleSheet.hasNameForId(_this.id, _this.name)) { var _styleSheet$options; styleSheet.insertRules(_this.id, _this.name, (_styleSheet$options = styleSheet.options).stringifier.apply(_styleSheet$options, _this.stringifyArgs)); } }; this.toString = function () { return throwStyledComponentsError(12, String(_this.name)); }; this.name = name; this.id = "sc-keyframes-" + name; this.stringifyArgs = stringifyArgs; } var _proto = Keyframes.prototype; _proto.getName = function getName() { return this.name; }; return Keyframes; }(); // /** * inlined version of * https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js */ var uppercasePattern = /([A-Z])/g; var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return string.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-'); } // function addUnitIfNeeded(name, value) { // https://github.com/amilajack/eslint-plugin-flowtype-errors/issues/133 // $FlowFixMe if (value == null || typeof value === 'boolean' || value === '') { return ''; } if (typeof value === 'number' && value !== 0 && !(name in unitless)) { return value + "px"; // Presumes implicit 'px' suffix for unitless numbers } return String(value).trim(); } // /** * It's falsish not falsy because 0 is allowed. */ var isFalsish = function isFalsish(chunk) { return chunk === undefined || chunk === null || chunk === false || chunk === ''; }; var objToCssArray = function objToCssArray(obj, prevKey) { var rules = []; var keys = Object.keys(obj); keys.forEach(function (key) { if (!isFalsish(obj[key])) { if (isPlainObject(obj[key])) { rules.push.apply(rules, objToCssArray(obj[key], key)); return rules; } else if (isFunction(obj[key])) { rules.push(hyphenateStyleName(key) + ":", obj[key], ';'); return rules; } rules.push(hyphenateStyleName(key) + ": " + addUnitIfNeeded(key, obj[key]) + ";"); } return rules; }); return prevKey ? [prevKey + " {"].concat(rules, ['}']) : rules; }; function flatten(chunk, executionContext, styleSheet) { if (Array.isArray(chunk)) { var ruleSet = []; for (var i = 0, len = chunk.length, result; i < len; i += 1) { result = flatten(chunk[i], executionContext, styleSheet); if (result === '') continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result); } return ruleSet; } if (isFalsish(chunk)) { return ''; } /* Handle other components */ if (isStyledComponent(chunk)) { return "." + chunk.styledComponentId; } /* Either execute or defer the function */ if (isFunction(chunk)) { if (isStatelessFunction(chunk) && executionContext) { var _result = chunk(executionContext); if (process.env.NODE_ENV !== 'production' && reactIs.isElement(_result)) { // eslint-disable-next-line no-console console.warn(getComponentName(chunk) + " is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details."); } return flatten(_result, executionContext, styleSheet); } else return chunk; } if (chunk instanceof Keyframes) { if (styleSheet) { chunk.inject(styleSheet); return chunk.getName(); } else return chunk; } /* Handle objects */ return isPlainObject(chunk) ? objToCssArray(chunk) : chunk.toString(); } // function css(styles) { for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } if (isFunction(styles) || isPlainObject(styles)) { // $FlowFixMe return flatten(interleave(EMPTY_ARRAY, [styles].concat(interpolations))); } // $FlowFixMe return flatten(interleave(styles, interpolations)); } function constructWithOptions(componentConstructor, tag, options) { if (options === void 0) { options = EMPTY_OBJECT; } if (!reactIs.isValidElementType(tag)) { return throwStyledComponentsError(1, String(tag)); } /* This is callable directly as a template function */ // $FlowFixMe: Not typed to avoid destructuring arguments var templateFunction = function templateFunction() { return componentConstructor(tag, options, css.apply(void 0, arguments)); }; /* If config methods are called, wrap up a new template function and merge options */ templateFunction.withConfig = function (config) { return constructWithOptions(componentConstructor, tag, _extends({}, options, config)); }; /* Modify/inject new props at runtime */ templateFunction.attrs = function (attrs) { return constructWithOptions(componentConstructor, tag, _extends({}, options, { attrs: Array.prototype.concat(options.attrs, attrs).filter(Boolean) })); }; return templateFunction; } // /* eslint-disable no-bitwise */ /* This is the "capacity" of our alphabet i.e. 2x26 for all letters plus their capitalised * counterparts */ var charsLength = 52; /* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */ var getAlphabeticChar = function getAlphabeticChar(code) { return String.fromCharCode(code + (code > 25 ? 39 : 97)); }; /* input a number, usually a hash and convert it to base-52 */ function generateAlphabeticName(code) { var name = ''; var x; /* get a char and divide by alphabet-length */ for (x = Math.abs(code); x > charsLength; x = x / charsLength | 0) { name = getAlphabeticChar(x % charsLength) + name; } return getAlphabeticChar(x % charsLength) + name; } // // version of djb2 where we pretend that we're still looping over // the same string var phash = function phash(h, x) { h = h | 0; for (var i = 0, l = x.length | 0; i < l; i++) { h = (h << 5) + h + x.charCodeAt(i); } return h; }; // This is a djb2 hashing function var hash = function hash(x) { return phash(5381 | 0, x) >>> 0; }; var hasher = function hasher(str) { return generateAlphabeticName(hash(str)); }; // function isStaticRules(rules) { for (var i = 0; i < rules.length; i += 1) { var rule = rules[i]; if (isFunction(rule) && !isStyledComponent(rule)) { // functions are allowed to be static if they're just being // used to get the classname of a nested styled component return false; } } return true; } // /* ComponentStyle is all the CSS-specific stuff, not the React-specific stuff. */ var ComponentStyle = /*#__PURE__*/ function () { function ComponentStyle(rules, componentId) { this.rules = rules; this.hasInjected = false; this.isStatic = process.env.NODE_ENV === 'production' && isStaticRules(rules); this.componentId = componentId; this.baseHash = hash(componentId); // NOTE: This registers the componentId, which ensures a consistent order // for this component's styles compared to others StyleSheet.registerId(componentId); } /* * Flattens a rule set into valid CSS * Hashes it, wraps the whole chunk in a .hash1234 {} * Returns the hash to be injected on render() * */ var _proto = ComponentStyle.prototype; _proto.generateAndInjectStyles = function generateAndInjectStyles(executionContext, styleSheet) { var componentId = this.componentId; if (this.isStatic && !this.hasInjected) { var cssStatic = flatten(this.rules, executionContext, styleSheet).join(''); var name = generateAlphabeticName(phash(this.baseHash, cssStatic + 1) >>> 0); if (!styleSheet.hasNameForId(componentId, name)) { var cssStaticFormatted = styleSheet.options.stringifier(cssStatic, "." + name, undefined, componentId); styleSheet.insertRules(componentId, componentId, cssStaticFormatted); this.hasInjected = true; } return name; } else { var length = this.rules.length; var dynamicHash = this.baseHash; var i = 0; var css = ''; for (i = 0; i < length; i++) { var partRule = this.rules[i]; if (typeof partRule === 'string') { css += partRule; if (process.env.NODE_ENV !== 'production') dynamicHash = phash(dynamicHash, partRule + i); } else { var partChunk = flatten(partRule, executionContext, styleSheet); var partString = Array.isArray(partChunk) ? partChunk.join('') : partChunk; dynamicHash = phash(dynamicHash, partString + i); css += partString; } } var _name = generateAlphabeticName(dynamicHash >>> 0); if (!styleSheet.hasNameForId(componentId, _name)) { var cssFormatted = styleSheet.options.stringifier(css, "." + _name, undefined, componentId); styleSheet.insertRules(componentId, _name, cssFormatted); } return _name; } }; return ComponentStyle; }(); // var LIMIT = 200; var createWarnTooManyClasses = (function (displayName) { var generatedClasses = {}; var warningSeen = false; return function (className) { if (!warningSeen) { generatedClasses[className] = true; if (Object.keys(generatedClasses).length >= LIMIT) { // Unable to find latestRule in test environment. /* eslint-disable no-console, prefer-template */ console.warn("Over " + LIMIT + " classes were generated for component " + displayName + ". This happens when some of the props you use for styling have many potential values and we need to make a new CSS class for each variant. Over time the stylesheet will grow and slow down your app.\n" + 'For these particular CSS rules with high dynamicity, consider using the attrs() method together with a style object.\n' + 'Example:\n' + ' const Component = styled.div.attrs(props => ({\n' + ' style: {\n' + ' background: props.background,\n' + ' },\n' + ' }))`width: 100%;`\n\n' + ' <Component />'); warningSeen = true; generatedClasses = {}; } } }; }); // var determineTheme = (function (props, providedTheme, defaultProps) { if (defaultProps === void 0) { defaultProps = EMPTY_OBJECT; } return props.theme !== defaultProps.theme && props.theme || providedTheme || defaultProps.theme; }); // var escapeRegex = /[[\].#*$><+~=|^:(),"'`-]+/g; var dashesAtEnds = /(^-|-$)/g; /** * TODO: Explore using CSS.escape when it becomes more available * in evergreen browsers. */ function escape(str) { return str // Replace all possible CSS selectors .replace(escapeRegex, '-') // Remove extraneous hyphens at the start and end .replace(dashesAtEnds, ''); } // function isTag(target) { return typeof target === 'string' && (process.env.NODE_ENV !== 'production' ? target.charAt(0) === target.charAt(0).toLowerCase() : true); } // function generateDisplayName(target) { // $FlowFixMe return isTag(target) ? "styled." + target : "Styled(" + getComponentName(target) + ")"; } var _TYPE_STATICS; var REACT_STATICS = { childContextTypes: true, contextTypes: true, defaultProps: true, displayName: true, getDerivedStateFromProps: true, propTypes: true, type: true }; var KNOWN_STATICS = { name: true, length: true, prototype: true, caller: true, callee: true, arguments: true, arity: true }; var TYPE_STATICS = (_TYPE_STATICS = {}, _TYPE_STATICS[reactIs.ForwardRef] = { $$typeof: true, render: true }, _TYPE_STATICS); var defineProperty = Object.defineProperty, getOwnPropertyNames = Object.getOwnPropertyNames, _Object$getOwnPropert = Object.getOwnPropertySymbols, getOwnPropertySymbols = _Object$getOwnPropert === void 0 ? function () { return []; } : _Object$getOwnPropert, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor, getPrototypeOf = Object.getPrototypeOf, objectPrototype = Object.prototype; var arrayPrototype = Array.prototype; function hoistNonReactStatics(targetComponent, sourceComponent, blacklist) { if (typeof sourceComponent !== 'string') { // don't hoist over string (html) components var inheritedComponent = getPrototypeOf(sourceComponent); if (inheritedComponent && inheritedComponent !== objectPrototype) { hoistNonReactStatics(targetComponent, inheritedComponent, blacklist); } var keys = arrayPrototype.concat(getOwnPropertyNames(sourceComponent), // $FlowFixMe getOwnPropertySymbols(sourceComponent)); var targetStatics = TYPE_STATICS[targetComponent.$$typeof] || REACT_STATICS; var sourceStatics = TYPE_STATICS[sourceComponent.$$typeof] || REACT_STATICS; var i = keys.length; var descriptor; var key; // eslint-disable-next-line no-plusplus while (i--) { key = keys[i]; if ( // $FlowFixMe !KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && // $FlowFixMe !(targetStatics && targetStatics[key])) { descriptor = getOwnPropertyDescriptor(sourceComponent, key); if (descriptor) { try { // Avoid failures from read-only properties defineProperty(targetComponent, key, descriptor); } catch (e) { /* fail silently */ } } } } return targetComponent; } return targetComponent; } var ThemeContext = React__default.createContext(); var ThemeConsumer = ThemeContext.Consumer; function useMergedTheme(theme, outerTheme) { if (isFunction(theme)) { var mergedTheme = theme(outerTheme); if (process.env.NODE_ENV !== 'production' && (mergedTheme === null || Array.isArray(mergedTheme) || typeof mergedTheme !== 'object')) { return throwStyledComponentsError(7); } return mergedTheme; } if (theme === null || Array.isArray(theme) || typeof theme !== 'object') { return throwStyledComponentsError(8); } return outerTheme ? _extends({}, outerTheme, theme) : theme; } /** * Provide a theme to an entire react component tree via context */ function ThemeProvider(props) { var outerTheme = React.useContext(ThemeContext); // NOTE: can't really memoize with props.theme as that'd cause incorrect memoization when it's a function var themeContext = useMergedTheme(props.theme, outerTheme); if (!props.children) { return null; } return React__default.createElement(ThemeContext.Provider, { value: themeContext }, React__default.Children.only(props.children)); } // var StyleSheetContext = React__default.createContext(); var StyleSheetConsumer = StyleSheetContext.Consumer; var masterSheet = new StyleSheet(); function useStyleSheet() { return React.useContext(StyleSheetContext) || masterSheet; } function StyleSheetManager(props) { /** * freeze the stylis modification props on initial mount since they rely on * reference equality for the useMemo dependencies array and devs will * likely not store the reference themselves to avoid this issue */ var _useState = React.useState({ disableVendorPrefixes: props.disableVendorPrefixes, stylisPlugins: props.stylisPlugins }), _useState$ = _useState[0], disableVendorPrefixes = _useState$.disableVendorPrefixes, stylisPlugins = _useState$.stylisPlugins; if (process.env.NODE_ENV !== 'production') { if (!shallowequal(disableVendorPrefixes, props.disableVendorPrefixes)) { // eslint-disable-next-line no-console console.warn('disableVendorPrefixes is frozen on initial mount of StyleSheetManager. Changing this prop dynamically will have no effect.'); } if (!shallowequal(stylisPlugins, props.stylisPlugins)) { // eslint-disable-next-line no-console console.warn('stylisPlugins are frozen on initial mount of StyleSheetManager. Changing this prop dynamically will have no effect.'); } } var styleSheet = React.useMemo(function () { var sheet = masterSheet; if (props.sheet) { // eslint-disable-next-line prefer-destructuring sheet = props.sheet; } else if (props.target) { sheet = sheet.reconstructWithOptions({ target: props.target }); } if (props.disableCSSOMInjection) { sheet = sheet.reconstructWithOptions({ useCSSOMInjection: false }); } if (disableVendorPrefixes || stylisPlugins) { sheet = sheet.reconstructWithOptions({ stringifier: createStylisInstance({ options: { prefix: !disableVendorPrefixes }, plugins: stylisPlugins }) }); } return sheet; }, [props.disableCSSOMInjection, props.sheet, disableVendorPrefixes, stylisPlugins, props.target]); return React__default.createElement(StyleSheetContext.Provider, { value: styleSheet }, process.env.NODE_ENV !== 'production' ? React__default.Children.only(props.children) : props.children); } /* global $Call */ var identifiers = {}; /* We depend on components having unique IDs */ function generateId(displayName, parentComponentId) { var name = typeof displayName !== 'string' ? 'sc' : escape(displayName); // Ensure that no displayName can lead to duplicate componentIds identifiers[name] = (identifiers[name] || 0) + 1; var componentId = name + "-" + hasher(name + identifiers[name]); return parentComponentId ? parentComponentId + "-" + componentId : componentId; } function useResolvedAttrs(theme, props, attrs) { if (theme === void 0) { theme = EMPTY_OBJECT; } // NOTE: can't memoize this // returns [context, resolvedAttrs] // where resolvedAttrs is only the things injected by the attrs themselves var context = _extends({}, props, { theme: theme }); var resolvedAttrs = {}; attrs.forEach(function (attrDef) { var resolvedAttrDef = attrDef; var key; if (isFunction(resolvedAttrDef)) { resolvedAttrDef = resolvedAttrDef(context); } /* eslint-disable guard-for-in */ for (key in resolvedAttrDef) { context[key] = resolvedAttrs[key] = resolvedAttrDef[key]; } /* eslint-enable guard-for-in */ }); return [context, resolvedAttrs]; } function useInjectedStyle(componentStyle, hasAttrs, resolvedAttrs, warnTooManyClasses) { var styleSheet = useStyleSheet(); // statically styled-components don't need to build an execution context object, // and shouldn't be increasing the number of class names var isStatic = componentStyle.isStatic && !hasAttrs; var className = isStatic ? componentStyle.generateAndInjectStyles(EMPTY_OBJECT, styleSheet) : componentStyle.generateAndInjectStyles(resolvedAttrs, styleSheet); React.useDebugValue(className); if (process.env.NODE_ENV !== 'production' && !isStatic && warnTooManyClasses) { warnTooManyClasses(className); } return className; } function useStyledComponentImpl(forwardedComponent, props, forwardedRef) { var componentAttrs = forwardedComponent.attrs, componentStyle = forwardedComponent.componentStyle, defaultProps = forwardedComponent.defaultProps, foldedComponentIds = forwardedComponent.foldedComponentIds, styledComponentId = forwardedComponent.styledComponentId, target = forwardedComponent.target; React.useDebugValue(styledComponentId); // NOTE: the non-hooks version only subscribes to this when !componentStyle.isStatic, // but that'd be against the rules-of-hooks. We could be naughty and do it anyway as it // should be an immutable value, but behave for now. var theme = determineTheme(props, React.useContext(ThemeContext), defaultProps) || EMPTY_OBJECT; var _useResolvedAttrs = useResolvedAttrs(theme, props, componentAttrs), context = _useResolvedAttrs[0], attrs = _useResolvedAttrs[1]; var generatedClassName = useInjectedStyle(componentStyle, componentAttrs.length > 0, context, process.env.NODE_ENV !== 'production' ? forwardedComponent.warnTooManyClasses : undefined); var refToForward = forwardedRef; var elementToBeCreated = props.as || attrs.as || target; var isTargetTag = isTag(elementToBeCreated); var computedProps = attrs !== props ? _extends({}, attrs, props) : props; var shouldFilterProps = isTargetTag || 'as' in computedProps || 'forwardedAs' in computedProps; var propsForElement = shouldFilterProps ? {} : _extends({}, computedProps); if (shouldFilterProps) { // eslint-disable-next-line guard-for-in for (var key in computedProps) { if (key === 'forwardedAs') { propsForElement.as = computedProps[key]; } else if (key !== 'as' && key !== 'forwardedAs' && (!isTargetTag || validAttr(key))) { // Don't pass through non HTML tags through to HTML elements propsForElement[key] = computedProps[key]; } } } if (props.style && attrs.style !== props.style) { propsForElement.style = _extends({}, attrs.style, props.style); } propsForElement.className = Array.prototype.concat(foldedComponentIds, styledComponentId, generatedClassName !== styledComponentId ? generatedClassName : null, props.className, attrs.className).filter(Boolean).join(' '); propsForElement.ref = refToForward; return React.createElement(elementToBeCreated, propsForElement); } function createStyledComponent(target, options, rules) { var isTargetStyledComp = isStyledComponent(target); var isCompositeComponent = !isTag(target); var _options$displayName = options.displayName, displayName = _options$displayName === void 0 ? generateDisplayName(target) : _options$displayName, _options$componentId = options.componentId, componentId = _options$componentId === void 0 ? generateId(options.displayName, options.parentComponentId) : _options$componentId, _options$attrs = options.attrs, attrs = _options$attrs === void 0 ? EMPTY_ARRAY : _options$attrs; var styledComponentId = options.displayName && options.componentId ? escape(options.displayName) + "-" + options.componentId : options.componentId || componentId; // fold the underlying StyledComponent attrs up (implicit extend) var finalAttrs = // $FlowFixMe isTargetStyledComp && target.attrs ? Array.prototype.concat(target.attrs, attrs).filter(Boolean) : attrs; var componentStyle = new ComponentStyle(isTargetStyledComp ? // fold the underlying StyledComponent rules up (implicit extend) // $FlowFixMe target.componentStyle.rules.concat(rules) : rules, styledComponentId); /** * forwardRef creates a new interim component, which we'll take advantage of * instead of extending ParentComponent to create _another_ interim class */ var WrappedStyledComponent; // eslint-disable-next-line react-hooks/rules-of-hooks var forwardRef = function forwardRef(props, ref) { return useStyledComponentImpl(WrappedStyledComponent, props, ref); }; forwardRef.displayName = displayName; // $FlowFixMe this is a forced cast to merge it StyledComponentWrapperProperties WrappedStyledComponent = React__default.forwardRef(forwardRef); WrappedStyledComponent.attrs = finalAttrs; WrappedStyledComponent.componentStyle = componentStyle; WrappedStyledComponent.displayName = displayName; // this static is used to preserve the cascade of static classes for component selector // purposes; this is especially important with usage of the css prop WrappedStyledComponent.foldedComponentIds = isTargetStyledComp ? // $FlowFixMe Array.prototype.concat(target.foldedComponentIds, target.styledComponentId) : EMPTY_ARRAY; WrappedStyledComponent.styledComponentId = styledComponentId; // fold the underlying StyledComponent target up since we folded the styles WrappedStyledComponent.target = isTargetStyledComp ? // $FlowFixMe target.target : target; // $FlowFixMe WrappedStyledComponent.withComponent = function withComponent(tag) { var previousComponentId = options.componentId, optionsToCopy = _objectWithoutPropertiesLoose(options, ["componentId"]); var newComponentId = previousComponentId && previousComponentId + "-" + (isTag(tag) ? tag : escape(getComponentName(tag))); var newOptions = _extends({}, optionsToCopy, { attrs: finalAttrs, componentId: newComponentId }); return createStyledComponent(tag, newOptions, rules); }; // $FlowFixMe Object.defineProperty(WrappedStyledComponent, 'defaultProps', { get: function get() { return this._foldedDefaultProps; }, set: function set(obj) { // $FlowFixMe this._foldedDefaultProps = isTargetStyledComp ? merge(target.defaultProps, obj) : obj; } }); if (process.env.NODE_ENV !== 'production') { WrappedStyledComponent.warnTooManyClasses = createWarnTooManyClasses(displayName); } // $FlowFixMe WrappedStyledComponent.toString = function () { return "." + WrappedStyledComponent.styledComponentId; }; if (isCompositeComponent) { hoistNonReactStatics(WrappedStyledComponent, target, { // all SC-specific things should not be hoisted attrs: true, componentStyle: true, displayName: true, foldedComponentIds: true, self: true, styledComponentId: true, target: true, withComponent: true }); } return WrappedStyledComponent; } // // Thanks to ReactDOMFactories for this handy list! var domElements = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG 'circle', 'clipPath', 'defs', 'ellipse', 'foreignObject', 'g', 'image', 'line', 'linearGradient', 'marker', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan']; // var styled = function styled(tag) { return constructWithOptions(createStyledComponent, tag); }; // Shorthands for all valid HTML Elements domElements.forEach(function (domElement) { styled[domElement] = styled(domElement); }); // var GlobalStyle = /*#__PURE__*/ function () { function GlobalStyle(rules, componentId) { this.rules = rules; this.componentId = componentId; this.isStatic = isStaticRules(rules); StyleSheet.registerId(componentId); } var _proto = GlobalStyle.prototype; _proto.createStyles = function createStyles(executionContext, styleSheet) { var flatCSS = flatten(this.rules, executionContext, styleSheet); var css = styleSheet.options.stringifier(flatCSS.join(''), ''); var id = this.componentId; // NOTE: We use the id as a name as well, since these rules never change styleSheet.insertRules(id, id, css); }; _proto.removeStyles = function removeStyles(styleSheet) { styleSheet.clearRules(this.componentId); }; _proto.renderStyles = function renderStyles(executionContext, styleSheet) { // NOTE: Remove old styles, then inject the new ones this.removeStyles(styleSheet); this.createStyles(executionContext, styleSheet); }; return GlobalStyle; }(); if (IS_BROWSER) { window.scCGSHMRCache = {}; } function createGlobalStyle(strings) { for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(void 0, [strings].concat(interpolations)); var styledComponentId = "sc-global-" + hasher(JSON.stringify(rules)); var globalStyle = new GlobalStyle(rules, styledComponentId); function GlobalStyleComponent(props) { var styleSheet = useStyleSheet(); var theme = React.useContext(ThemeContext); if (process.env.NODE_ENV !== 'production' && React__default.Children.count(props.children)) { // eslint-disable-next-line no-console console.warn("The global style component " + styledComponentId + " was given child JSX. createGlobalStyle does not render children."); } if (globalStyle.isStatic) { globalStyle.renderStyles(STATIC_EXECUTION_CONTEXT, styleSheet); } else { var context = _extends({}, props, { theme: determineTheme(props, theme, GlobalStyleComponent.defaultProps) }); globalStyle.renderStyles(context, styleSheet); } React.useEffect(function () { if (IS_BROWSER) { window.scCGSHMRCache[styledComponentId] = (window.scCGSHMRCache[styledComponentId] || 0) + 1; return function () { if (window.scCGSHMRCache[styledComponentId]) { window.scCGSHMRCache[styledComponentId] -= 1; } /** * Depending on the order "render" is called this can cause the styles to be lost * until the next render pass of the remaining instance, which may * not be immediate. */ if (window.scCGSHMRCache[styledComponentId] === 0) { globalStyle.removeStyles(styleSheet); } }; } return undefined; }, []); return null; } return GlobalStyleComponent; } // function keyframes(strings) { /* Warning if you've used keyframes on React Native */ if (process.env.NODE_ENV !== 'production' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { // eslint-disable-next-line no-console console.warn('`keyframes` cannot be used on ReactNative, only on the web. To do animation in ReactNative please use Animated.'); } for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(void 0, [strings].concat(interpolations)).join(''); var name = hasher(rules); return new Keyframes(name, [rules, name, '@keyframes']); } var CLOSING_TAG_R = /^\s*<\/[a-z]/i; var ServerStyleSheet = /*#__PURE__*/ function () { function ServerStyleSheet() { var _this = this; this._emitSheetCSS = function () { var css = _this.instance.toString(); var nonce = getNonce(); var attrs = [nonce && "nonce=\"" + nonce + "\"", SC_ATTR, SC_ATTR_VERSION + "=\"" + SC_VERSION + "\""]; var htmlAttr = attrs.filter(Boolean).join(' '); return "<style " + htmlAttr + ">" + css + "</style>"; }; this.getStyleTags = function () { if (_this.sealed) { return throwStyledComponentsError(2); } return _this._emitSheetCSS(); }; this.getStyleElement = function () { var _props; if (_this.sealed) { return throwStyledComponentsError(2); } var props = (_props = {}, _props[SC_ATTR] = '', _props[SC_ATTR_VERSION] = SC_VERSION, _props.dangerouslySetInnerHTML = { __html: _this.instance.toString() }, _props); var nonce = getNonce(); if (nonce) { props.nonce = nonce; } // v4 returned an array for this fn, so we'll do the same for v5 for backward compat return [React__default.createElement("style", _extends({}, props, { key: "sc-0-0" }))]; }; this.seal = function () { _this.sealed = true; }; this.instance = new StyleSheet({ isServer: true }); this.sealed = false; } var _proto = ServerStyleSheet.prototype; _proto.collectStyles = function collectStyles(children) { if (this.sealed) { return throwStyledComponentsError(2); } return React__default.createElement(StyleSheetManager, { sheet: this.instance }, children); }; // eslint-disable-next-line consistent-return _proto.interleaveWithNodeStream = function interleaveWithNodeStream(input) { if (IS_BROWSER) { return throwStyledComponentsError(3); } else if (this.sealed) { return throwStyledComponentsError(2); } { this.seal(); // eslint-disable-next-line global-require var _require = require('stream'), Readable = _require.Readable, Transform = _require.Transform; var readableStream = input; var sheet = this.instance, _emitSheetCSS = this._emitSheetCSS; var transformer = new Transform({ transform: function appendStyleChunks(chunk, /* encoding */ _, callback) { // Get the chunk and retrieve the sheet's CSS as an HTML chunk, // then reset its rules so we get only new ones for the next chunk var renderedHtml = chunk.toString(); var html = _emitSheetCSS(); sheet.clearTag(); // prepend style html to chunk, unless the start of the chunk is a // closing tag in which case append right after that if (CLOSING_TAG_R.test(renderedHtml)) { var endOfClosingTag = renderedHtml.indexOf('>') + 1; var before = renderedHtml.slice(0, endOfClosingTag); var after = renderedHtml.slice(endOfClosingTag); this.push(before + html + after); } else { this.push(html + renderedHtml); } callback(); } }); readableStream.on('error', function (err) { // forward the error to the transform stream transformer.emit('error', err); }); return readableStream.pipe(transformer); } }; return ServerStyleSheet; }(); // export default <Config: { theme?: any }, Instance>( // Component: AbstractComponent<Config, Instance> // ): AbstractComponent<$Diff<Config, { theme?: any }> & { theme?: any }, Instance> // // but the old build system tooling doesn't support the syntax var withTheme = (function (Component) { // $FlowFixMe This should be React.forwardRef<Config, Instance> var WithTheme = React__default.forwardRef(function (props, ref) { var theme = React.useContext(ThemeContext); // $FlowFixMe defaultProps isn't declared so it can be inferrable var defaultProps = Component.defaultProps; var themeProp = determineTheme(props, theme, defaultProps); if (process.env.NODE_ENV !== 'production' && themeProp === undefined) { // eslint-disable-next-line no-console console.warn("[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class \"" + getComponentName(Component) + "\""); } return React__default.createElement(Component, _extends({}, props, { theme: themeProp, ref: ref })); }); hoistNonReactStatics(WithTheme, Component); WithTheme.displayName = "WithTheme(" + getComponentName(Component) + ")"; return WithTheme; }); // var __PRIVATE__ = { StyleSheet: StyleSheet, masterSheet: masterSheet }; // // exports.ServerStyleSheet = ServerStyleSheet; exports.StyleSheetConsumer = StyleSheetConsumer; exports.StyleSheetContext = StyleSheetContext; exports.StyleSheetManager = StyleSheetManager; exports.ThemeConsumer = ThemeConsumer; exports.ThemeContext = ThemeContext; exports.ThemeProvider = ThemeProvider; exports.__PRIVATE__ = __PRIVATE__; exports.createGlobalStyle = createGlobalStyle; exports.css = css; exports.default = styled; exports.isStyledComponent = isStyledComponent; exports.keyframes = keyframes; exports.withTheme = withTheme; //# sourceMappingURL=styled-components.cjs.js.map
// Copyright IBM Corp. 2013,2016. All Rights Reserved. // Node module: strong-remoting // This file is licensed under the Artistic License 2.0. // License text available at https://opensource.org/licenses/Artistic-2.0 // create a set of shared classes var remoting = require('../'); var SharedClass = remoting.SharedClass var remotes = remoting.create(); var express = require('express'); var app = express(); // define a class-like object (or constructor) var user = { greet: function (fn) { fn(null, 'hello, world!'); } }; // create a shared class to allow strong-remoting to map // http requests to method invocations on your class var userSharedClass = new SharedClass('user', user); // tell strong-remoting about your greet method userSharedClass.defineMethod('greet', { isStatic: true, // not an instance method returns: [{ arg: 'msg', type: 'string' // define the type of the callback arguments }] }); // tell strong-remoting about the class remotes.addClass(userSharedClass); // mount the middleware on an express app app.use(remotes.handler('rest')); // create the http server require('http') .createServer(app) .listen(3000); /* Test the above with curl or a rest client: $ node simple.js $ curl http://localhost:3000/user/greet # responds as an object, with the msg attribute # set to the result of the function { "msg": "hello, world!" } */
/*! * # Semantic UI 2.7.2 - Transition * http://github.com/semantic-org/semantic-ui/ * * * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { 'use strict'; $.isFunction = $.isFunction || function(obj) { return typeof obj === "function" && typeof obj.nodeType !== "number"; }; window = (typeof window != 'undefined' && window.Math == Math) ? window : (typeof self != 'undefined' && self.Math == Math) ? self : Function('return this')() ; $.fn.transition = function() { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], moduleArguments = arguments, query = moduleArguments[0], queryArguments = [].slice.call(arguments, 1), methodInvoked = (typeof query === 'string'), requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { setTimeout(callback, 0); }, returnedValue ; $allModules .each(function(index) { var $module = $(this), element = this, // set at run time settings, instance, error, className, metadata, animationEnd, animationName, namespace, moduleNamespace, eventNamespace, module ; module = { initialize: function() { // get full settings settings = module.get.settings.apply(element, moduleArguments); // shorthand className = settings.className; error = settings.error; metadata = settings.metadata; // define namespace eventNamespace = '.' + settings.namespace; moduleNamespace = 'module-' + settings.namespace; instance = $module.data(moduleNamespace) || module; // get vendor specific events animationEnd = module.get.animationEndEvent(); if(methodInvoked) { methodInvoked = module.invoke(query); } // method not invoked, lets run an animation if(methodInvoked === false) { module.verbose('Converted arguments into settings object', settings); if(settings.interval) { module.delay(settings.animate); } else { module.animate(); } module.instantiate(); } }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, instance) ; }, destroy: function() { module.verbose('Destroying previous module for', element); $module .removeData(moduleNamespace) ; }, refresh: function() { module.verbose('Refreshing display type on next animation'); delete module.displayType; }, forceRepaint: function() { module.verbose('Forcing element repaint'); var $parentElement = $module.parent(), $nextElement = $module.next() ; if($nextElement.length === 0) { $module.detach().appendTo($parentElement); } else { $module.detach().insertBefore($nextElement); } }, repaint: function() { module.verbose('Repainting element'); var fakeAssignment = element.offsetWidth ; }, delay: function(interval) { var direction = module.get.animationDirection(), shouldReverse, delay ; if(!direction) { direction = module.can.transition() ? module.get.direction() : 'static' ; } interval = (interval !== undefined) ? interval : settings.interval ; shouldReverse = (settings.reverse == 'auto' && direction == className.outward); delay = (shouldReverse || settings.reverse == true) ? ($allModules.length - index) * settings.interval : index * settings.interval ; module.debug('Delaying animation by', delay); setTimeout(module.animate, delay); }, animate: function(overrideSettings) { settings = overrideSettings || settings; if(!module.is.supported()) { module.error(error.support); return false; } module.debug('Preparing animation', settings.animation); if(module.is.animating()) { if(settings.queue) { if(!settings.allowRepeats && module.has.direction() && module.is.occurring() && module.queuing !== true) { module.debug('Animation is currently occurring, preventing queueing same animation', settings.animation); } else { module.queue(settings.animation); } return false; } else if(!settings.allowRepeats && module.is.occurring()) { module.debug('Animation is already occurring, will not execute repeated animation', settings.animation); return false; } else { module.debug('New animation started, completing previous early', settings.animation); instance.complete(); } } if( module.can.animate() ) { module.set.animating(settings.animation); } else { module.error(error.noAnimation, settings.animation, element); } }, reset: function() { module.debug('Resetting animation to beginning conditions'); module.remove.animationCallbacks(); module.restore.conditions(); module.remove.animating(); }, queue: function(animation) { module.debug('Queueing animation of', animation); module.queuing = true; $module .one(animationEnd + '.queue' + eventNamespace, function() { module.queuing = false; module.repaint(); module.animate.apply(this, settings); }) ; }, complete: function (event) { module.debug('Animation complete', settings.animation); module.remove.completeCallback(); module.remove.failSafe(); if(!module.is.looping()) { if( module.is.outward() ) { module.verbose('Animation is outward, hiding element'); module.restore.conditions(); module.hide(); } else if( module.is.inward() ) { module.verbose('Animation is outward, showing element'); module.restore.conditions(); module.show(); } else { module.verbose('Static animation completed'); module.restore.conditions(); settings.onComplete.call(element); } } }, force: { visible: function() { var style = $module.attr('style'), userStyle = module.get.userStyle(style), displayType = module.get.displayType(), overrideStyle = userStyle + 'display: ' + displayType + ' !important;', inlineDisplay = $module[0].style.display, mustStayHidden = !displayType || (inlineDisplay === 'none' && settings.skipInlineHidden) || $module[0].tagName.match(/(script|link|style)/i) ; if (mustStayHidden){ module.remove.transition(); return false; } module.verbose('Overriding default display to show element', displayType); $module .attr('style', overrideStyle) ; if(style === '') { $module.removeAttr('style'); } return true; }, hidden: function() { var style = $module.attr('style'), currentDisplay = $module.css('display'), emptyStyle = (style === undefined || style === '') ; if(currentDisplay !== 'none' && !module.is.hidden()) { module.verbose('Overriding default display to hide element'); $module .css('display', 'none') ; } else if(emptyStyle) { $module .removeAttr('style') ; } } }, has: { direction: function(animation) { var hasDirection = false ; animation = animation || settings.animation; if(typeof animation === 'string') { animation = animation.split(' '); $.each(animation, function(index, word){ if(word === className.inward || word === className.outward) { hasDirection = true; } }); } return hasDirection; }, inlineDisplay: function() { var style = $module.attr('style') || '' ; return Array.isArray(style.match(/display.*?;/, '')); } }, set: { animating: function(animation) { // override display if necessary so animation appears visibly if(module.force.visible()) { var animationClass, direction ; // remove previous callbacks module.remove.completeCallback(); // determine exact animation animation = animation || settings.animation; animationClass = module.get.animationClass(animation); // save animation class in cache to restore class names module.save.animation(animationClass); module.remove.hidden(); module.remove.direction(); module.start.animation(animationClass); } }, duration: function(animationName, duration) { duration = duration || settings.duration; duration = (typeof duration == 'number') ? duration + 'ms' : duration ; if(duration || duration === 0) { module.verbose('Setting animation duration', duration); $module .css({ 'animation-duration': duration }) ; } }, direction: function(direction) { direction = direction || module.get.direction(); if(direction == className.inward) { module.set.inward(); } else { module.set.outward(); } }, looping: function() { module.debug('Transition set to loop'); $module .addClass(className.looping) ; }, hidden: function() { $module .addClass(className.transition) .addClass(className.hidden) ; }, inward: function() { module.debug('Setting direction to inward'); $module .removeClass(className.outward) .addClass(className.inward) ; }, outward: function() { module.debug('Setting direction to outward'); $module .removeClass(className.inward) .addClass(className.outward) ; }, visible: function() { $module .addClass(className.transition) .addClass(className.visible) ; } }, start: { animation: function(animationClass) { animationClass = animationClass || module.get.animationClass(); module.debug('Starting tween', animationClass); $module .addClass(animationClass) .one(animationEnd + '.complete' + eventNamespace, module.complete) ; if(settings.useFailSafe) { module.add.failSafe(); } module.set.duration(settings.duration); settings.onStart.call(element); } }, save: { animation: function(animation) { if(!module.cache) { module.cache = {}; } module.cache.animation = animation; }, displayType: function(displayType) { if(displayType !== 'none') { $module.data(metadata.displayType, displayType); } }, transitionExists: function(animation, exists) { $.fn.transition.exists[animation] = exists; module.verbose('Saving existence of transition', animation, exists); } }, restore: { conditions: function() { var animation = module.get.currentAnimation() ; if(animation) { $module .removeClass(animation) ; module.verbose('Removing animation class', module.cache); } module.remove.duration(); } }, add: { failSafe: function() { var duration = module.get.duration() ; module.timer = setTimeout(function() { $module.triggerHandler(animationEnd); }, duration + settings.failSafeDelay); module.verbose('Adding fail safe timer', module.timer); } }, remove: { animating: function() { $module.removeClass(className.animating); }, animationCallbacks: function() { module.remove.queueCallback(); module.remove.completeCallback(); }, queueCallback: function() { $module.off('.queue' + eventNamespace); }, completeCallback: function() { $module.off('.complete' + eventNamespace); }, display: function() { $module.css('display', ''); }, direction: function() { $module .removeClass(className.inward) .removeClass(className.outward) ; }, duration: function() { $module .css('animation-duration', '') ; }, failSafe: function() { module.verbose('Removing fail safe timer', module.timer); if(module.timer) { clearTimeout(module.timer); } }, hidden: function() { $module.removeClass(className.hidden); }, visible: function() { $module.removeClass(className.visible); }, looping: function() { module.debug('Transitions are no longer looping'); if( module.is.looping() ) { module.reset(); $module .removeClass(className.looping) ; } }, transition: function() { $module .removeClass(className.transition) .removeClass(className.visible) .removeClass(className.hidden) ; } }, get: { settings: function(animation, duration, onComplete) { // single settings object if(typeof animation == 'object') { return $.extend(true, {}, $.fn.transition.settings, animation); } // all arguments provided else if(typeof onComplete == 'function') { return $.extend({}, $.fn.transition.settings, { animation : animation, onComplete : onComplete, duration : duration }); } // only duration provided else if(typeof duration == 'string' || typeof duration == 'number') { return $.extend({}, $.fn.transition.settings, { animation : animation, duration : duration }); } // duration is actually settings object else if(typeof duration == 'object') { return $.extend({}, $.fn.transition.settings, duration, { animation : animation }); } // duration is actually callback else if(typeof duration == 'function') { return $.extend({}, $.fn.transition.settings, { animation : animation, onComplete : duration }); } // only animation provided else { return $.extend({}, $.fn.transition.settings, { animation : animation }); } }, animationClass: function(animation) { var animationClass = animation || settings.animation, directionClass = (module.can.transition() && !module.has.direction()) ? module.get.direction() + ' ' : '' ; return className.animating + ' ' + className.transition + ' ' + directionClass + animationClass ; }, currentAnimation: function() { return (module.cache && module.cache.animation !== undefined) ? module.cache.animation : false ; }, currentDirection: function() { return module.is.inward() ? className.inward : className.outward ; }, direction: function() { return module.is.hidden() || !module.is.visible() ? className.inward : className.outward ; }, animationDirection: function(animation) { var direction ; animation = animation || settings.animation; if(typeof animation === 'string') { animation = animation.split(' '); // search animation name for out/in class $.each(animation, function(index, word){ if(word === className.inward) { direction = className.inward; } else if(word === className.outward) { direction = className.outward; } }); } // return found direction if(direction) { return direction; } return false; }, duration: function(duration) { duration = duration || settings.duration; if(duration === false) { duration = $module.css('animation-duration') || 0; } return (typeof duration === 'string') ? (duration.indexOf('ms') > -1) ? parseFloat(duration) : parseFloat(duration) * 1000 : duration ; }, displayType: function(shouldDetermine) { shouldDetermine = (shouldDetermine !== undefined) ? shouldDetermine : true ; if(settings.displayType) { return settings.displayType; } if(shouldDetermine && $module.data(metadata.displayType) === undefined) { var currentDisplay = $module.css('display'); if(currentDisplay === '' || currentDisplay === 'none'){ // create fake element to determine display state module.can.transition(true); } else { module.save.displayType(currentDisplay); } } return $module.data(metadata.displayType); }, userStyle: function(style) { style = style || $module.attr('style') || ''; return style.replace(/display.*?;/, ''); }, transitionExists: function(animation) { return $.fn.transition.exists[animation]; }, animationStartEvent: function() { var element = document.createElement('div'), animations = { 'animation' :'animationstart', 'OAnimation' :'oAnimationStart', 'MozAnimation' :'mozAnimationStart', 'WebkitAnimation' :'webkitAnimationStart' }, animation ; for(animation in animations){ if( element.style[animation] !== undefined ){ return animations[animation]; } } return false; }, animationEndEvent: function() { var element = document.createElement('div'), animations = { 'animation' :'animationend', 'OAnimation' :'oAnimationEnd', 'MozAnimation' :'mozAnimationEnd', 'WebkitAnimation' :'webkitAnimationEnd' }, animation ; for(animation in animations){ if( element.style[animation] !== undefined ){ return animations[animation]; } } return false; } }, can: { transition: function(forced) { var animation = settings.animation, transitionExists = module.get.transitionExists(animation), displayType = module.get.displayType(false), elementClass, tagName, $clone, currentAnimation, inAnimation, directionExists ; if( transitionExists === undefined || forced) { module.verbose('Determining whether animation exists'); elementClass = $module.attr('class'); tagName = $module.prop('tagName'); $clone = $('<' + tagName + ' />').addClass( elementClass ).insertAfter($module); currentAnimation = $clone .addClass(animation) .removeClass(className.inward) .removeClass(className.outward) .addClass(className.animating) .addClass(className.transition) .css('animationName') ; inAnimation = $clone .addClass(className.inward) .css('animationName') ; if(!displayType) { displayType = $clone .attr('class', elementClass) .removeAttr('style') .removeClass(className.hidden) .removeClass(className.visible) .show() .css('display') ; module.verbose('Determining final display state', displayType); module.save.displayType(displayType); } $clone.remove(); if(currentAnimation != inAnimation) { module.debug('Direction exists for animation', animation); directionExists = true; } else if(currentAnimation == 'none' || !currentAnimation) { module.debug('No animation defined in css', animation); return; } else { module.debug('Static animation found', animation, displayType); directionExists = false; } module.save.transitionExists(animation, directionExists); } return (transitionExists !== undefined) ? transitionExists : directionExists ; }, animate: function() { // can transition does not return a value if animation does not exist return (module.can.transition() !== undefined); } }, is: { animating: function() { return $module.hasClass(className.animating); }, inward: function() { return $module.hasClass(className.inward); }, outward: function() { return $module.hasClass(className.outward); }, looping: function() { return $module.hasClass(className.looping); }, occurring: function(animation) { animation = animation || settings.animation; animation = '.' + animation.replace(' ', '.'); return ( $module.filter(animation).length > 0 ); }, visible: function() { return $module.is(':visible'); }, hidden: function() { return $module.css('visibility') === 'hidden'; }, supported: function() { return(animationEnd !== false); } }, hide: function() { module.verbose('Hiding element'); if( module.is.animating() ) { module.reset(); } element.blur(); // IE will trigger focus change if element is not blurred before hiding module.remove.display(); module.remove.visible(); if($.isFunction(settings.onBeforeHide)){ settings.onBeforeHide.call(element,function(){ module.hideNow(); }); } else { module.hideNow(); } }, hideNow: function() { module.set.hidden(); module.force.hidden(); settings.onHide.call(element); settings.onComplete.call(element); // module.repaint(); }, show: function(display) { module.verbose('Showing element', display); if(module.force.visible()) { module.remove.hidden(); module.set.visible(); settings.onShow.call(element); settings.onComplete.call(element); // module.repaint(); } }, toggle: function() { if( module.is.visible() ) { module.hide(); } else { module.show(); } }, stop: function() { module.debug('Stopping current animation'); $module.triggerHandler(animationEnd); }, stopAll: function() { module.debug('Stopping all animation'); module.remove.queueCallback(); $module.triggerHandler(animationEnd); }, clear: { queue: function() { module.debug('Clearing animation queue'); module.remove.queueCallback(); } }, enable: function() { module.verbose('Starting animation'); $module.removeClass(className.disabled); }, disable: function() { module.debug('Stopping animation'); $module.addClass(className.disabled); }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { if($.isPlainObject(settings[name])) { $.extend(true, settings[name], value); } else { settings[name] = value; } } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(!settings.silent && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(!settings.silent && settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { if(!settings.silent) { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); } }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if($allModules.length > 1) { title += ' ' + '(' + $allModules.length + ')'; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, // modified for transition to return invoke success invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if(Array.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return (found !== undefined) ? found : false ; } }; module.initialize(); }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; // Records if CSS transition is available $.fn.transition.exists = {}; $.fn.transition.settings = { // module info name : 'Transition', // hide all output from this component regardless of other settings silent : false, // debug content outputted to console debug : false, // verbose debug output verbose : false, // performance data output performance : true, // event namespace namespace : 'transition', // delay between animations in group interval : 0, // whether group animations should be reversed reverse : 'auto', // animation callback event onStart : function() {}, onComplete : function() {}, onShow : function() {}, onHide : function() {}, // whether timeout should be used to ensure callback fires in cases animationend does not useFailSafe : true, // delay in ms for fail safe failSafeDelay : 100, // whether EXACT animation can occur twice in a row allowRepeats : false, // Override final display type on visible displayType : false, // animation duration animation : 'fade', duration : false, // new animations will occur after previous ones queue : true, // whether initially inline hidden objects should be skipped for transition skipInlineHidden: false, metadata : { displayType: 'display' }, className : { animating : 'animating', disabled : 'disabled', hidden : 'hidden', inward : 'in', loading : 'loading', looping : 'looping', outward : 'out', transition : 'transition', visible : 'visible' }, // possible errors error: { noAnimation : 'Element is no longer attached to DOM. Unable to animate. Use silent setting to surpress this warning in production.', repeated : 'That animation is already occurring, cancelling repeated animation', method : 'The method you called is not defined', support : 'This browser does not support CSS animations' } }; })( jQuery, window, document );
'use strict' const common = require('./common') const debug = require('debug')('electron-packager') const download = require('electron-download') const pify = require('pify') const semver = require('semver') const targets = require('./targets') function createDownloadOpts (opts, platform, arch) { let downloadOpts = Object.assign({}, opts.download) common.subOptionWarning(downloadOpts, 'download', 'platform', platform, opts.quiet) common.subOptionWarning(downloadOpts, 'download', 'arch', arch, opts.quiet) common.subOptionWarning(downloadOpts, 'download', 'version', opts.electronVersion, opts.quiet) return downloadOpts } module.exports = { createDownloadCombos: function createDownloadCombos (opts, selectedPlatforms, selectedArchs, ignoreFunc) { return targets.createPlatformArchPairs(opts, selectedPlatforms, selectedArchs, ignoreFunc).map(combo => { const platform = combo[0] const arch = combo[1] return createDownloadOpts(opts, platform, arch) }) }, createDownloadOpts: createDownloadOpts, downloadElectronZip: function downloadElectronZip (downloadOpts) { // armv7l builds have only been backfilled for Electron >= 1.0.0. // See: https://github.com/electron/electron/pull/6986 /* istanbul ignore if */ if (downloadOpts.arch === 'armv7l' && semver.lt(downloadOpts.version, '1.0.0')) { downloadOpts.arch = 'arm' } debug(`Downloading Electron with options ${JSON.stringify(downloadOpts)}`) return pify(download)(downloadOpts) } }
/** * @fileOverview * widget.enchant.js * @version 0.2.0 * @require enchant.js v0.6.0+ * @author UEI Corporation * * @description * enchant.jsでモバイル向けウェブページのようなUIを作成するためのライブラリ. */ (function() { /** * @type {Object} */ enchant.widget = { assets: [ 'listItemBg.png', 'iconMenuBg.png', 'button.png', 'buttonPushed.png', 'dialog.png', 'navigationBar.png' ], _env: { // default font font: '12px helvetica', buttonFont: '23px helvetica', navigationBarFont: '16px helvetica', textareaFont: '8px monospace', listItemMargin: 4, dialogMargin: 24, itemHeight: 48, buttonWidth: 64, buttonHeight: 36, dialogWidth: 300, dialogHeight: 225, inputMinHeight: 160, inputMaxHeight: 240, acceptName: 'OK', cancelName: 'NO', HOLDTIME: 300, DBLLIMIT: 300, FLINGVEL: 3 }, /** * 文字列やenchant.Surfaceなど単体で表示できないオブジェクトを表示できる形にして返す. * @param {*} content 表示させたいデータ. * @return {*} enchantのEntity系オブジェクト. */ parseContent: function(content, font, color) { var en, metrics; if (typeof content === 'undefined') { content = ''; } if (typeof content === 'number') { content = '' + content; } if (content instanceof enchant.Entity) { } else if (content instanceof enchant.Surface) { en = new enchant.Sprite(content.width, content.height); en.image = content; content = en; } else if (typeof content == 'string') { en = new enchant.Label(content); if (font) { en.font = font; } else { en.font = enchant.widget._env.font; } if (color) { en.color = color; } metrics = en.getMetrics(); en.width = metrics.width; en.height = metrics.height; content = en; } return content; } }; /** * Sceneが開始したとき発生するイベント. * {@link enchant.Core#transitionPush}のアニメーションが終了した際に発生する. * @type {String} */ enchant.Event.TRANSITIONENTER = 'transitionenter'; /** * Sceneが終了したとき発生するイベント. * {@link enchant.Core#transitionPop}のアニメーションが終了した際に発生する. * @type {String} */ enchant.Event.TRANSITIONEXIT = 'transitionexit'; /** * enchant.widget.Confirmで肯定側のボタンが押されたときに発生されるイベント. * @type {String} */ enchant.Event.ACCEPT = 'accept'; /** * enchant.widget.Confirmで否定側のボタンが押されたときに発生されるイベント. * @type {String} */ enchant.Event.CANCEL = 'cancel'; /** * form系のオブジェクトで内容が変更されたときに発生されるイベント. * @type {String} */ enchant.Event.CHANGE = 'change'; /** * タップが検出されたときに発生されるイベント. * 移動なしでタッチが終了し, ダブルタップの判定時間が終了した場合検出される. * @type {String} */ enchant.Event.TAP = 'tap'; /** * ダブルタップが検出されたときに発生されるイベント. * 一定時間, 一定距離以内に2回タップが検出された場合検出される. * @type {String} */ enchant.Event.DOUBLETAP = 'doubletap'; /** * ホールドが検出されたときに発生されるイベント. * 移動なしで一定時間タッチが続いた場合検出される. * @type {String} */ enchant.Event.HOLD = 'hold'; /** * ドラッグが検出されたときに発生されるイベント. * ホールド中にタッチ位置が移動した際に検出される. * @type {String} */ enchant.Event.DRAG = 'drag'; /** * リリースが検出されたときに発生されるイベント. * ホールド中にタッチが終了した際に検出される. * @type {String} */ enchant.Event.RELEASE = 'release'; /** * スリップが検出されたときに発生されるイベント. * ホールドされずタッチ位置が移動した場合検出される. * @type {String} */ enchant.Event.SLIP = 'slip'; /** * フリックが検出されたときに発生されるイベント. * タッチが終了した際に, 一定速度以上で位置が移動していた場合検出される. * @type {String} */ enchant.Event.FLING = 'fling'; /** * Event which will be dispatched when additional content should be loaded for a view. */ enchant.Event.CONTENT_REQUESTED = 'contentRequested'; var NOTOUCH = 0; var WAITDBL = 1; var NOMOVE = 2; var NOMOVEDBL = 3; var MOVED = 4; var HOLD = 5; var getElementMetrics = function(string, font) { var e = document.createElement('div'); var cvs = document.createElement('canvas'); var ctx = cvs.getContext('2d'); var arr, str, w; var width = 0; var height = 0; if (!font) { font = enchant.widget._env.font; } ctx.font = font; e.style.font = font; string = string || ''; string = string.replace(/<(br|BR) ?\/?>/g, '<br>'); arr = string.split('<br>'); for (var i = 0, l = arr.length; i < l; i++) { str = arr[i]; w = ctx.measureText(str).width; if (width < w) { width = w; } } e.innerHTML = string; if (document.body) { document.body.appendChild(e); height = parseInt(getComputedStyle(e).height, 10); e.style.position = 'absolute'; width = parseInt(getComputedStyle(e).width, 10); document.body.removeChild(e); } else { height = 14 * arr.length; } return { width: width + 1, height: height + 1 }; }; var calcLeastPosition = function(margin) { margin |= 0; return margin; }; var calcMostPosition = function(child, parent, margin) { margin |= 0; return parent - margin - child; }; var calcCenteredPosition = function(child, parent) { return ~~(parent / 2) - ~~(child / 2); }; var getScaleOffest = function(length, scale) { var half = ~~(length / 2); scale = scale || 1; return half - ~~(half * scale); }; var distribute = function(value, div) { if (typeof div == 'array') { var ratio = div; var ret = new Array(ratio.length); var retSum = 0; var maxi = 0; var max = 0; var sum = 0; var quo; ratio.forEach(function(n) { sum += n; }); quo = value / sum; for (var i = 0, l = ret.length; i < l; i++) { ret[i] = Math.round(quo * ratio[i]); if (ratio[i] < max) { maxi = i; max = ratio[i]; } } ret.forEach(function(n) { retSum += n; }); ret[maxi] += value - retSum; } else if (typeof div == 'number') { var ret = new Array(div); var quo = ~~(value / div); var rem = ~~(value % div); for (var i = 0, l = div; i < l; i++) { ret[i] = quo; } for (var i = 0, l = rem; i < l; i++) { ret[i % div] += 1; } } return ret; }; var Adjust = { fitToX: function(parent, margin) { var l = parent.width; var s = Math.min( (l - margin * 2) / this.width, (l - margin * 2) / this.height ); if (this instanceof enchant.Sprite) { this.scaleX = s; this.scaleY = s; } else { this.width = ~~(this.width * s); this.height = ~~(this.height * s); } }, fitToY: function(parent, margin) { var l = parent.height; var s = Math.min( (l - margin * 2) / this.width, (l - margin * 2) / this.height ); if (this instanceof enchant.Sprite) { this.scaleX = s; this.scaleY = s; } else { this.width = ~~(this.width * s); this.height = ~~(this.height * s); } }, fillX: function(parent, margin) { var s = (parent.width - margin * 2) / this.width; if (this instanceof enchant.Sprite) { this.scaleX = s; this.scaleY = s; } else { this.width = ~~(this.width * s); this.height = ~~(this.height * s); } }, fillY: function(parent, margin) { var s = (parent.height - margin * 2) / this.height; if (this instanceof enchant.Sprite) { this.scaleX = s; this.scaleY = s; } else { this.width = ~~(this.width * s); this.height = ~~(this.height * s); } } }; var Effect = { transitForwardIn: function(time) { var core = enchant.Core.instance; var child; this.x = core.width; var e = new enchant.Event(enchant.Event.RENDER); for (var i = 0, l = this.childNodes.length; i < l; i++) { child = this.childNodes[i]; child.dispatchEvent(e); } this.tl .moveTo(0, 0, time, enchant.Easing.QUAD_EASEINOUT); }, transitForwardOut: function(time) { var core = enchant.Core.instance; this.x = 0; this.tl .moveTo(-core.width, 0, time, enchant.Easing.QUAD_EASEINOUT); }, transitBackIn: function(time) { var core = enchant.Core.instance; this.x = -core.width; this.tl .moveTo(0, 0, time, enchant.Easing.QUAD_EASEINOUT); }, transitBackOut: function(time) { var core = enchant.Core.instance; this.x = 0; this.tl .moveTo(core.width, 0, time, enchant.Easing.QUAD_EASEINOUT); }, popup: function() { this.scaleX = 0.1; this.scaleY = 0.1; this.opacity = 0.1; this.tl .fadeTo(0.8, 3, enchant.Easing.QUAD_EASEOUT) .and() .scaleTo(1, 3, enchant.Easing.BOUNCE_EASEOUT); }, popdown: function() { this.tl .fadeTo(0.1, 3, enchant.Easing.QUAD_EASEOUT) .and() .scaleTo(0.1, 3, enchant.Easing.BOUNCE_EASEOUT); }, resizeTo: function(width, height, time, easing) { return this.tl.tween({ width: width, height: height, time: time, easing: easing }); } }; var Align = { /** * @scope enchant.Entity */ /** * 指定オブジェクトの左側に寄せる. * @param {*} another 基準となるオブジェクト. * @param {Number} margin ずらすピクセル数. * @requires widget.enchant.js */ alignLeftOf: function(another, margin) { margin |= 0; var anotherScaleOffset = getScaleOffest(another.width, another.scaleX); var scaleOffset = getScaleOffest(this.width, this.scaleX); this.x = another.x + anotherScaleOffset - scaleOffset - this.width - margin; return this; }, /** * 指定オブジェクトの右側に寄せる. * @param {*} another 基準となるオブジェクト. * @param {Number} margin ずらすピクセル数. * @requires widget.enchant.js */ alignRightOf: function(another, margin) { margin |= 0; var anotherScaleOffset = getScaleOffest(another.width, another.scaleX); var scaleOffset = getScaleOffest(this.width, this.scaleX); this.x = another.x + another.width - anotherScaleOffset - scaleOffset + margin; return this; }, /** * 指定オブジェクトの上側に寄せる. * @param {*} another 基準となるオブジェクト. * @param {Number} margin ずらすピクセル数. * @requires widget.enchant.js */ alignTopOf: function(another, margin) { margin |= 0; var anotherScaleOffset = getScaleOffest(another.height, another.scaleY); var scaleOffset = getScaleOffest(this.height, this.scaleY); this.y = another.y + anotherScaleOffset - scaleOffset - this.height - margin; return this; }, /** * 指定オブジェクトの下側に寄せる. * @param {*} another 基準となるオブジェクト. * @param {Number} margin ずらすピクセル数. * @requires widget.enchant.js */ alignBottomOf: function(another, margin) { margin |= 0; var anotherScaleOffset = getScaleOffest(another.height, another.scaleY); var scaleOffset = getScaleOffest(this.height, this.scaleY); this.y = another.y + another.height - anotherScaleOffset - scaleOffset + margin; return this; }, /** * 指定オブジェクト内で左寄せを行う. * @param {*} another 基準となるオブジェクト. * @param {Number} margin ずらすピクセル数. * @requires widget.enchant.js */ alignLeftIn: function(another, margin) { var scaleOffset = getScaleOffest(this.width, this.scaleX); this.x = calcLeastPosition(margin) - scaleOffset; return this; }, /** * 指定オブジェクト内で右寄せを行う. * @param {*} another 基準となるオブジェクト. * @param {Number} margin ずらすピクセル数. * @requires widget.enchant.js */ alignRightIn: function(another, margin) { var scaleOffset = getScaleOffest(this.width, this.scaleX); this.x = calcMostPosition(this.width, another.width, margin) + scaleOffset; return this; }, /** * 指定オブジェクト内で上寄せを行う. * @param {*} another 基準となるオブジェクト. * @param {Number} margin ずらすピクセル数. * @requires widget.enchant.js */ alignTopIn: function(another, margin) { var scaleOffset = getScaleOffest(this.height, this.scaleY); this.y = calcLeastPosition(margin) - scaleOffset; return this; }, /** * 指定オブジェクト内で下寄せを行う. * @param {*} another 基準となるオブジェクト. * @param {Number} margin ずらすピクセル数. * @requires widget.enchant.js */ alignBottomIn: function(another, margin) { var scaleOffset = getScaleOffest(this.height, this.scaleY); this.y = calcMostPosition(this.height, another.height, margin) + scaleOffset; return this; }, /** * 指定オブジェクト内でx方向の中央寄せを行う. * @param {*} another 基準となるオブジェクト. * @param {Number} margin ずらすピクセル数. * @requires widget.enchant.js */ alignHorizontalCenterIn: function(another) { this.x = calcCenteredPosition(this.width, another.width); return this; }, /** * 指定オブジェクト内でy方向の中央寄せを行う. * @param {*} another 基準となるオブジェクト. * @param {Number} margin ずらすピクセル数. * @requires widget.enchant.js */ alignVerticalCenterIn: function(another) { this.y = calcCenteredPosition(this.height, another.height); return this; } }; for (var prop in Align) { enchant.Entity.prototype[prop] = Align[prop]; } var _transitionLock = false; /** * @scope enchant.Core */ /** * トランジションアニメーションのついたpushSceneを行う. * @param {enchant.Scene} scene 移行する新しいシーン. * @return {enchant.Scene} 新しいシーン. * @requires widget.enchant.js */ enchant.Core.prototype.transitionPush = function(inScene) { if (_transitionLock) return null; _transitionLock = true; var time = 15; var c = 0; var outScene = this.currentScene; Effect.transitForwardIn.call(inScene, time); Effect.transitForwardOut.call(outScene, time); this.addEventListener(enchant.Event.ENTER_FRAME, function(e) { outScene.dispatchEvent(e); if (c > time) { _transitionLock = false; this.removeEventListener(enchant.Event.ENTER_FRAME, arguments.callee); inScene.dispatchEvent(new enchant.Event(enchant.Event.TRANSITIONENTER)); outScene.dispatchEvent(new enchant.Event(enchant.Event.TRANSITIONEXIT)); } c++; }); return this.pushScene(inScene); }; /** * トランジションアニメーションのついたpopSceneを行う. * @return {enchant.Scene} 終了させたシーン. * @requires widget.enchant.js */ enchant.Core.prototype.transitionPop = function() { if (_transitionLock) return null; if (this.currentScene == this.rootScene) return null; _transitionLock = true; var time = 15; var c = 0; var outScene = this.currentScene; var inScene = this._scenes[this._scenes.length - 2]; this.addEventListener(enchant.Event.ENTER_FRAME, function(e) { inScene.dispatchEvent(e); if (c > time) { _transitionLock = false; this.removeEventListener(enchant.Event.ENTER_FRAME, arguments.callee); this.popScene(); outScene.dispatchEvent(new enchant.Event(enchant.Event.TRANSITIONEXIT)); inScene.dispatchEvent(new enchant.Event(enchant.Event.TRANSITIONENTER)); } c++; }); Effect.transitBackIn.call(inScene, time); Effect.transitBackOut.call(outScene, time); return this._scenes[this._scenes.length - 1]; }; /** * @scope enchant.widget.GestureDetector */ enchant.widget.GestureDetector = enchant.Class.create(enchant.EventTarget, { /** * タッチ入力の動きから幾つかのジェスチャーを検出してイベントを発行する. * タップ, ダブルタップ, ホールド, ドラッグ, フリックなどを検出することができる. * @param {enchant.Entity} target 入力を検出させたいオブジェクト. * @constructs * @extends enchant.EventTarget */ initialize: function(target) { var core = enchant.Core.instance; enchant.EventTarget.call(this); this._target; this._startX = 0; this._startY = 0; this._lastX = 0; this._lastY = 0; this._touchElapsed = 0; this._releaseElapsed = 0; this._state = NOTOUCH; this._velobase = (core.width > core.height) ? core.height : core.width; var detector = this; this._handler = function(e) { detector.dispatchEvent(e); }; this._types = [ enchant.Event.TOUCH_START, enchant.Event.TOUCH_MOVE, enchant.Event.TOUCH_END, enchant.Event.ENTER_FRAME ]; if (target) { this.attach(target); } }, attach: function(target) { this._target = target; this._types.forEach(function(event) { this._target.addEventListener(event, this._handler); }, this); }, detach: function() { this._types.forEach(function(event) { this._target.removeEventListener(event, this._handler); }, this); this._target = null; }, ontouchstart: function(e) { var core = enchant.Core.instance; this._startFrame = core.frame; this._startX = this._lastX = e.x; this._startY = this._lastY = e.y; if (this._state == WAITDBL) { this._state = NOMOVEDBL; } else if (this._state == NOTOUCH) { this._state = NOMOVE; } }, ontouchmove: function(e) { var dx = e.x - this._lastX; var dy = e.y - this._lastY; this._lastX = e.x; this._lastY = e.y; switch (this._state) { case NOMOVE: case NOMOVEDBL: this._state = MOVED; case MOVED: var evt = new enchant.Event(enchant.Event.SLIP); evt.x = this._lastX; evt.y = this._lastY; evt.dx = dx; evt.dy = dy; this._target.dispatchEvent(evt); break; case HOLD: var evt = new enchant.Event(enchant.Event.DRAG); evt.x = this._lastX; evt.y = this._lastY; evt.dx = dx; evt.dy = dy; this._target.dispatchEvent(evt); break; default: break; } }, ontouchend: function(e) { var core = enchant.Core.instance; switch (this._state) { case MOVED: velocityX = (this._lastX - this._startX) / this._velobase / this._touchElapsed * 1000; velocityY = (this._lastY - this._startY) / this._velobase / this._touchElapsed * 1000; if (velocityX > enchant.widget._env.FLINGVEL || velocityY > enchant.widget._env.FLINGVEL) { var evt = new enchant.Event(enchant.Event.FLING); evt.x = this._startX; evt.y = this._startY; evt.ex = this._lastX; evt.ey = this._lastY; evt.velocityX = velocityX; evt.velocityY = velocityY; this._target.dispatchEvent(evt); } this._state = NOTOUCH; break; case HOLD: var evt = new enchant.Event(enchant.Event.RELEASE); evt.x = this._lastX; evt.y = this._lastY; this._target.dispatchEvent(evt); this._state = NOTOUCH; break; case NOMOVEDBL: var evt = new enchant.Event(enchant.Event.DOUBLETAP); evt.x = this._lastX; evt.y = this._lastY; this._target.dispatchEvent(evt); this._state = NOTOUCH; this._releaseElapsed = 0; break; case NOMOVE: this._state = WAITDBL; break; default: this._state = NOTOUCH; break; } this._touchElapsed = 0; this._startX = 0; this._startY = 0; }, onenterframe: function(e) { var elapsed = e.elapsed; switch (this._state) { case WAITDBL: this._releaseElapsed += elapsed; if (this._releaseElapsed >= enchant.widget._env.DBLLIMIT) { var evt = new enchant.Event(enchant.Event.TAP); evt.x = this._lastX; evt.y = this._lastY; this._lastX = 0; this._lastY = 0; this._target.dispatchEvent(evt); this._state = NOTOUCH; this._releaseElapsed = 0; } break; case NOMOVEDBL: this._releaseElapsed += elapsed; if (this._releaseElapsed >= enchant.widget._env.DBLLIMIT) { this._state = NOMOVE; this._releaseElapsed = 0; } case NOMOVE: this._touchElapsed += elapsed; if (this._touchElapsed >= enchant.widget._env.HOLDTIME) { var evt = new enchant.Event(enchant.Event.HOLD); evt.x = this._lastX; evt.y = this._lastY; this._target.dispatchEvent(evt); this._state = HOLD; this._touchElapsed = 0; } break; case MOVED: this._touchElapsed += elapsed; break; case NOTOUCH: case HOLD: default: break; } } }); enchant.widget.GestureDetector.gestureEvents = [ enchant.Event.ACCEPT, enchant.Event.CANCEL, enchant.Event.TAP, enchant.Event.DOUBLETAP, enchant.Event.HOLD, enchant.Event.DRAG, enchant.Event.RELEASE, enchant.Event.SLIP, enchant.Event.FLING ]; /** * @scope enchant.widget.Ninepatch */ enchant.widget.Ninepatch = enchant.Class.create(enchant.Surface, { /** * 9patchに対応したサーフェース. * コンテンツ領域の設定には対応していない. * @param {Number} width Surfaceの横幅. * @param {Number} height Surfaceの高さ. * @constructs * @extends enchant.Surface */ initialize: function(width, height) { enchant.Surface.call(this, width, height); this._horScStore = []; this._horNoScStore = []; this._verScStore = []; this._verNoScStore = []; this._src; }, /** * 9patchのソース. * @type {enchant.Surface} */ src: { get: function() { return this._src; }, set: function(surface) { if (surface == this._src || !(surface instanceof enchant.Surface)) { return; } this._slicedraw(surface); this._src = surface; } }, _detect: function(img) { this._horScStore = []; this._horNoScStore = []; this._verScStore = []; this._verNoScStore = []; var elem = img._element; var cvs = document.createElement('canvas'); var width = cvs.width = img.width; var height = cvs.height = img.height; var ctx = cvs.getContext('2d'); ctx.drawImage(elem, 0, 0, width, height); var pixels = ctx.getImageData(0, 0, width, height); var isBlack = function(i) { return pixels.data[i] == 0 && pixels.data[i + 1] == 0 && pixels.data[i + 2] == 0 && pixels.data[i + 3] == 255; }; var last = false; var tmp = []; var scalable = []; var noscalable = []; for (var i = 1, l = width - 1; i < l; i++) { last = isBlack(i * 4); if (last) { if (scalable.length == 0) { scalable.push(i); } if (noscalable.length == 1) { noscalable.push(i - 1); this._horNoScStore.push(noscalable); noscalable = []; } } else { if (noscalable.length == 0) { noscalable.push(i); } if (scalable.length == 1) { scalable.push(i - 1); this._horScStore.push(scalable); scalable = []; } } } if (scalable.length == 1) { scalable.push(i - 1); this._horScStore.push(scalable); } if (noscalable.length == 1) { noscalable.push(i - 1); this._horNoScStore.push(noscalable); } scalable = []; noscalable = []; for (var i = 1, l = height - 1; i < l; i++) { last = isBlack(i * width * 4); if (last) { if (scalable.length == 0) { scalable.push(i); } if (noscalable.length == 1) { noscalable.push(i - 1); this._verNoScStore.push(noscalable); noscalable = []; } } else { if (noscalable.length == 0) { noscalable.push(i); } if (scalable.length == 1) { scalable.push(i - 1); this._verScStore.push(scalable); scalable = []; } } } if (scalable.length == 1) { scalable.push(i - 1); this._verScStore.push(scalable); } if (noscalable.length == 1) { noscalable.push(i - 1); this._verNoScStore.push(noscalable); } }, _slicedraw: function(img) { this._detect(img); var elem = img._element; var w = img.width; var h = img.height; var width = this.width; var height = this.height; var ctx = this.context; var getSum = function(store) { var s; var sum = 0; for (var i = 0, l = store.length; i < l; i++) { s = store[i]; sum += s[1] - s[0] + 1; } return sum; }; var getRatio = function(array) { var a, ret = []; for (var i = 0, l = array.length; i < l; i++) { a = array[i]; ret.push(a[1] - a[0] + 1); } return ret; }; var fix = function(array, fix) { var a; for (var i = 0, l = array.length; i < l; i++) { a = array[i]; a.fix = fix[i]; } }; var distribute = function(value, ratio) { var ret = new Array(ratio.length); var retSum = 0; var maxi = 0; var max = 0; var sum = 0; var quo; ratio.forEach(function(n) { sum += n; }); quo = value / sum; for (var i = 0, l = ret.length; i < l; i++) { ret[i] = Math.round(quo * ratio[i]); if (ratio[i] < max) { maxi = i; max = ratio[i]; } } ret.forEach(function(n) { retSum += n; }); ret[maxi] += value - retSum; return ret; }; var ratioH = getRatio(this._horScStore); var valueH = width - getSum(this._horNoScStore); var scaledW = distribute(valueH, ratioH); var ratioV = getRatio(this._verScStore); var valueV = height - getSum(this._verNoScStore); var scaledH = distribute(valueV, ratioV); fix(this._horScStore, scaledW); fix(this._verScStore, scaledH); var verQueue = this._verScStore.concat(this._verNoScStore).sort(function(a, b) { return a[0] - b[0]; }); var horQueue = this._horScStore.concat(this._horNoScStore).sort(function(a, b) { return a[0] - b[0]; }); var verQ; var horQ; var sx, sy, sw, sh, dw, dh; var dx = 0; var dy = 0; ctx.clearRect(0, 0, this.width, this.height); for (var i = 0, l = horQueue.length; i < l; i++) { horQ = horQueue[i]; sx = horQ[0]; sw = horQ[1] - horQ[0] + 1; dw = (typeof horQ.fix == 'number') ? horQ.fix : sw; dy = 0; for (var j = 0, ll = verQueue.length; j < ll; j++) { verQ = verQueue[j]; sy = verQ[0]; sh = verQ[1] - verQ[0] + 1; dh = (typeof verQ.fix == 'number') ? verQ.fix : sh; ctx.drawImage(elem, sx, sy, sw, sh, dx, dy, dw, dh); dy += dh; } dx += dw; } }, /** * @type {Number} */ width: { get: function() { return this._width; }, set: function(width) { this._width = width; if (this._element) { this._element.width = width; } if (this._src instanceof enchant.Surface) { this._slicedraw(this._src); } } }, /** * @type {Number} */ height: { get: function() { return this._height; }, set: function(height) { this._height = height; if (this._element) { this._element.height = height; } if (this._src instanceof enchant.Surface) { this._slicedraw(this._src); } } }, /** * 指定したサイズで作りなおす. * @param {Number} width 新しい横幅. * @param {Number} height 新しい高さ. */ resize: function(width, height) { this._width = width; this._height = height; this._element.width = width; this._element.height = height; if (this._src instanceof enchant.Surface) { this._slicedraw(this._src); } } }); /** * @scope enchant.widget.EntityGroup */ enchant.widget.EntityGroup = enchant.Class.create(enchant.Entity, { /** * 子を持つことができるEntity. * @param {Number} width Entityの横幅. * @param {Number} height Entityの高さ. * @constructs * @extends enchant.Entity */ initialize: function(width, height) { enchant.Entity.call(this); this.childNodes = []; this._background; this.width = width; this.height = height; [ enchant.Event.ADDED_TO_SCENE, enchant.Event.REMOVED_FROM_SCENE ] .forEach(function(event) { this.addEventListener(event, function(e) { this.childNodes.slice().forEach(function(child) { child.scene = this.scene; child.dispatchEvent(e); }, this); }); }, this); }, /** * @type {Number} */ width: { get: function() { return this._width; }, set: function(width) { this._width = width; this._dirty = true; if (this.background instanceof enchant.widget.Ninepatch) { this.background.width = this.width; } } }, /** * @type {Number} */ height: { get: function() { return this._height; }, set: function(height) { this._height = height; this._dirty = true; if (this.background instanceof enchant.widget.Ninepatch) { this.background.height = this.height; } } }, /** * 背景として使用するSurface. * @type {enchant.Surface} */ background: { get: function() { return this._background; }, set: function(surface) { if (surface instanceof enchant.Surface) { this._background = surface; if (surface._css) { this._style['background-image'] = surface._css; } } } }, /** * EntityGroupにNodeを追加する. * @param {enchant.Node} child 追加するNode. */ addChild: enchant.Group.prototype.addChild, /** * EntityGroupにNodeを挿入する. * @param {enchant.Node} child 挿入するNode. * @param {enchant.Node} reference 挿入位置の前にあるNode. */ insertBefore: enchant.Group.prototype.insertBefore, /** * EntityGroupからNodeを削除する. * @param {enchant.Node} child 削除するNode. */ removeChild: enchant.Group.prototype.removeChild, /** * 最初の子Node. */ firstChild: Object.getOwnPropertyDescriptor(enchant.Group.prototype, 'firstChild'), /** * 最後の子Node. * @type {enchant.Node} */ lastChild: Object.getOwnPropertyDescriptor(enchant.Group.prototype, 'lastChild'), _dirty: Object.getOwnPropertyDescriptor(enchant.Group.prototype, '_dirty'), cvsRender: function(ctx) { if (this.background && this.background._element.width > 0 && this.background._element.height > 0) { ctx.drawImage(this.background._element, 0, 0, this.width, this.height); } } }); /** * @scope enchant.widget.Modal */ enchant.widget.Modal = enchant.Class.create(enchant.Scene, { /** * モーダルシーン. * @constructs * @extends enchant.Scene */ initialize: function() { enchant.Scene.call(this); var core = enchant.Core.instance; var shade = new enchant.Sprite(core.width, core.height); shade.backgroundColor = 'rgba(0, 0, 0, 0.1)'; this.addChild(shade); this.addEventListener(enchant.Event.ENTER, function() { shade.tl.fadeTo(0.7, 5, enchant.Easing.QUAD_EASEOUT); }); } }); /** * @scope enchant.widget.Button.prototype */ enchant.widget.Button = enchant.Class.create(enchant.widget.EntityGroup, { /** * ボタン. * 通常の背景と押下中の背景を設定できる. * @param {*} content ボタンの内容. * @constructs * @extends enchant.widget.EntityGroup */ initialize: function(content) { var core = enchant.Core.instance; content = content || ''; var minwidth = enchant.widget._env.buttonWidth; var minheight = enchant.widget._env.buttonHeight; enchant.widget.EntityGroup.call(this, minwidth, minheight); this._image; this._pushedimage; this._content; this._rawContent; var bg1 = new enchant.widget.Ninepatch(minwidth, minheight); bg1.src = core.assets['button.png']; this.image = bg1; var bg2 = new enchant.widget.Ninepatch(minwidth, minheight); bg2.src = core.assets['buttonPushed.png']; this.pushedimage = bg2; this.content = content; this.width = Math.max(this._content.width, minwidth); this.height = Math.max(this._content.height, minheight); this.addEventListener(enchant.Event.TOUCH_START, function() { if (!this._pushedimage) { return; } this.background = this._pushedimage; }); this.addEventListener(enchant.Event.TOUCH_END, function() { if (!this._pushedimage) { return; } this.background = this._image; }); }, refresh: function() { if (this._content) { this._content.alignHorizontalCenterIn(this).alignVerticalCenterIn(this); } }, /** * ボタンの幅 * @type number */ width: { get: function() { return this._width; }, set: function(width) { this._style.width = (this._width = width) + 'px'; if (this._image instanceof enchant.widget.Ninepatch) { this._image.width = width; } if (this._pushedimage instanceof enchant.widget.Ninepatch) { this._pushedimage.width = width; } this.refresh(); } }, /** * ボタンの高さ * @type number */ height: { get: function() { return this._height; }, set: function(height) { this._style.height = (this._height = height) + 'px'; if (this._image instanceof enchant.widget.Ninepatch) { this._image.height = height; } if (this._pushedimage instanceof enchant.widget.Ninepatch) { this._pushedimage.height = height; } this.refresh(); } }, /** * ボタンの背景. */ image: { get: function() { return this._image; }, set: function(image) { if (image == this._image) { return; } this.background = image; this._image = image; } }, /** * ボタンが押されている時の背景. * @type {enchant.Surface} */ pushedimage: { get: function() { return this._pushedimage; }, set: function(image) { if (image == this._pushedimage) { return; } this._pushedimage = image; } }, /** * ボタンの内容 * @type {String} */ content: { get: function() { return this._rawContent; }, set: function(content) { this._rawContent = content; var font = enchant.widget._env.buttonFont; content = enchant.widget.parseContent(content, font); if (this._content) { this.removeChild(this._content); } this.addChild(content); this._content = content; this.refresh(); } } }); /** * @scope enchant.widget.Alert */ enchant.widget.Alert = enchant.Class.create(enchant.widget.EntityGroup, { /** * アラートダイアログ. * 通常{@link enchant.widget.AlertScene}から使用する. * @param {*} content 表示するコンテンツ. * @param {String} ac 了承ボタンのラベル. * @see enchant.widget.AlertScene * @constructs * @extends enchant.widget.EntityGroup */ initialize: function(content, ac) { var core = enchant.Core.instance; var dialogwidth = enchant.widget._env.dialogWidth; var dialogheight = enchant.widget._env.dialogHeight; enchant.widget.EntityGroup.call(this, dialogwidth, dialogheight); var margin = enchant.widget._env.dialogMargin; content = enchant.widget.parseContent(content); content.alignHorizontalCenterIn(this).alignTopIn(this, margin); var accept = new enchant.widget.Button(ac); accept.alignHorizontalCenterIn(this).alignBottomIn(this, margin); var that = this; accept.addEventListener(enchant.Event.TOUCH_END, function() { that.dispatchEvent(new enchant.Event(enchant.Event.ACCEPT)); }); var np = new enchant.widget.Ninepatch(this.width, this.height); np.src = core.assets['dialog.png']; this.background = np; this._content = content; this._accept = accept; this.addChild(content); this.addChild(accept); }, /** * 了承ボタンが押されたときに実行される関数. * @type {Function} */ onaccept: function() { } }); /** * @scope enchant.widget.Confirm */ enchant.widget.Confirm = enchant.Class.create(enchant.widget.EntityGroup, { /** * コンファームダイアログ. * 通常{@link enchant.widget.ConfirmScene}から使用する. * @param {*} content 表示するコンテンツ. * @param {String} ac 了承ボタンのラベル. * @param {String} ig キャンセルボタンのラベル. * @see enchant.widget.ConfirmScene * @constructs * @extends enchant.widget.EntityGroup */ initialize: function(content, ac, ig) { var core = enchant.Core.instance; var dialogwidth = enchant.widget._env.dialogWidth; var dialogheight = enchant.widget._env.dialogHeight; enchant.widget.EntityGroup.call(this, dialogwidth, dialogheight); var margin = enchant.widget._env.dialogMargin; var content = enchant.widget.parseContent(content); content.alignHorizontalCenterIn(this).alignTopIn(this, margin); var cancel = new enchant.widget.Button(ig); cancel.alignLeftIn(this, margin).alignBottomIn(this, margin); var accept = new enchant.widget.Button(ac); accept.alignRightIn(this, margin).alignBottomIn(this, margin); var that = this; cancel.addEventListener(enchant.Event.TOUCH_END, function() { that.dispatchEvent(new enchant.Event(enchant.Event.CANCEL)); }); accept.addEventListener(enchant.Event.TOUCH_END, function() { that.dispatchEvent(new enchant.Event(enchant.Event.ACCEPT)); }); var np = new enchant.widget.Ninepatch(this.width, this.height); np.src = core.assets['dialog.png']; this.background = np; this._content = content; this._cancel = cancel; this._accept = accept; this.addChild(content); this.addChild(cancel); this.addChild(accept); }, /** * キャンセルボタンが押されたときに実行される関数. * @type {Function} */ oncancel: function() { }, /** * 了承ボタンが押されたときに実行される関数. */ onaccept: function() { } }); /** * @scope enchant.widget.Prompt */ enchant.widget.Prompt = enchant.Class.create(enchant.widget.Confirm, { /** * プロンプトダイアログ. * 通常{@link enchant.widget.PromptScene}から使用する. * @param {*} content 表示するコンテンツ. * @param {String} ac 了承ボタンのラベル. * @param {String} ig キャンセルボタンのラベル. * @see enchant.widget.PromptScene * @constructs * @extends enchant.widget.Confirm */ initialize: function(content, ac, ig, placeholder) { enchant.widget.Confirm.call(this, content, ac, ig); var margin = enchant.widget._env.dialogMargin; var input = this._input = new enchant.widget.InputTextBox(); input.width = this.width / 4 * 3; input.placeholder = placeholder; input.alignHorizontalCenterIn(this).alignBottomOf(this._content, margin); this.addChild(input); }, /** * content of prompt. */ value: { get: function() { return this._input.value; }, set: function(value) { this._input.value = value; } } }); /** * @scope enchant.widget.Input */ enchant.widget.Input = enchant.Class.create(enchant.Entity, { /** * <input>を内包したEntity. * @param {String} type <input>のtype. * @constructs * @extends enchant.Entity */ initialize: function(type) { enchant.Entity.call(this); if (!type) { type = 'input'; } var that = this; this._input = document.createElement(type); this._input.addEventListener('change', function(e) { that.dispatchEvent(new enchant.Event(enchant.Event.CHANGE)); }); this._element = document.createElement('div'); this._element.appendChild(this._input); }, /** * 入力を許可するか決定する. * @type {Boolean} */ disabled: { get: function() { return this._input.disbaled; }, set: function(value) { this._input.disabled = !!value; } } }); /** * @scope enchant.widget.InputTextBox */ enchant.widget.InputTextBox = enchant.Class.create(enchant.widget.Input, { /** * テキストボックス. * @constructs * @extends enchant.widget.Input */ initialize: function() { enchant.widget.Input.call(this); this._input.type = 'text'; var metrics = getElementMetrics(this._element.innerHTML); this.width = metrics.width; this.height = metrics.height; var that = this; this._focused = false; this._input.addEventListener('focus', function() { that._focused = true; }); this._input.addEventListener('blur', function() { that._focused = false; }); }, /** * @type {Number} */ selectionStart: { get: function() { return this._input.selectionStart; }, set: function(n) { this._input.selectionStart = n; } }, /** * @type {Number} */ selectionEnd: { get: function() { return this._input.selectionEnd; }, set: function(n) { this._input.selectionEnd = n; } }, /** * @type {Boolean} */ focused: { get: function() { return this._focused; }, set: function(bool) { this._focused = bool; if (bool) { this._input.focus(); } else { this._input.blur(); } } }, /** * プレースホルダ. * @type {String} */ placeholder: { get: function() { return this._input.placeholder; }, set: function(value) { this._input.placeholder = value; } }, /** * テキストボックスに入力された値. * @type {String} */ value: { get: function() { return this._input.value; }, set: function(value) { this._input.value = value; } }, /** * テキストボックスの横幅. * @type {Number} */ width: { get: function() { return this._width; }, set: function(width) { this._width = width; this._style.width = width + 'px'; this._input.style.width = width + 'px'; } }, /** * テキストボックスの縦幅. * @type {Number} */ height: { get: function() { return this._height; }, set: function(height) { this._height = height; this._style.height = height + 'px'; this._input.style.height = height + 'px'; } } }); /** * @scope enchant.widget.InputSelectBox */ enchant.widget.InputSelectBox = enchant.Class.create(enchant.widget.Input, { /** * セレクトボックス. * @param {*} option オプションに設定する値. * @example * var option = { * male: '男', * female: '女' * }; * var selectbox = new InputSelectBox(option); * * @constructs * @extends enchant.widget.Input */ initialize: function(table) { enchant.widget.Input.call(this, 'select'); var content; for (var prop in table) { content = table[prop]; opt = document.createElement('option'); opt.value = prop; opt.textContent = content; this._input.appendChild(opt); } this._input.addEventListener('mousedown', function(e) { e.stopPropagation(); }); var metrics = getElementMetrics(this._element.innerHTML); this.width = metrics.width; this.height = metrics.height; }, /** * 選択されている項目. * @type {String} */ selected: { get: function() { return this._input.options[this._input.selectedIndex].value; }, set: function(value) { var opt; for (var i = 0, l = this._input.options.length; i < l; i++) { opt = this._input.options[i]; if (opt.getAttribute('value') == value) { opt.selected = true; } else { opt.selected = false; } } return value; } } }); /** * @scope enchant.widget.InputCheckBox */ enchant.widget.InputCheckBox = enchant.Class.create(enchant.widget.Input, { /** * チェックボックス. * @param {String} value 値. * @param {String} text ラベルテキスト. * @param {Boolean} checked チェックされているかどうか. * @constructs * @extends enchant.widget.Input */ initialize: function(value, text, checked) { enchant.widget.Input.call(this); this._input.type = 'checkbox'; var label = document.createDocumentFragment(); label.textContent = text; this._element.appendChild(label); this.checked = checked; var metrics = getElementMetrics(this._element.innerHTML); this.width = metrics.width; this.height = metrics.height; }, /** * チェックされているかどうか. * @type {Boolean} */ checked: { get: function() { return this._input.checked; }, set: function(value) { this._input.checked = !!value; } } }); /** * @scope enchant.widget.InputTextArea */ enchant.widget.InputTextArea = enchant.Class.create(enchant.Entity, { /** * テキストエリア. * @constructs * @extends enchant.Entity */ initialize: function() { enchant.Entity.call(this); var textarea = this._textarea = document.createElement('textarea'); textarea.style.resize = 'none'; textarea.style.font = enchant.widget._env.textareaFont; this._element = document.createElement('div'); this._element.appendChild(textarea); var that = this; this._focused = false; this._next = null; this._prev = null; var that = this; this.addEventListener(enchant.Event.TOUCH_END, function() { this._updateVerticalDist(); }); this._textarea.addEventListener('input', function() { that._updateVerticalDist(); }); this._textarea.addEventListener('focus', function() { that._focused = true; }); this._textarea.addEventListener('blur', function() { that._focused = false; }); this._textarea.addEventListener('change', function(e) { that.dispatchEvent(new enchant.Event(enchant.Event.CHANGE)); }); }, _updateVerticalDist: function() { var w = this.value.split('\n'); var n = this.selectionStart; var s = 0; for (var i = 0, l = w.length; i < l; i++) { n -= w[i].length + 1; if (n < 0) { break; } s += w[i].length + 1; } var ind = this.selectionStart - s; if (0 < i) { this._prev = -Math.max(w[i - 1].length, ind) - 1; } else { this._prev = -ind; } if (i < l - 1) { this._next = w[i].length - ind + Math.min(ind, w[i + 1].length) + 1; } else { this._next = w[i].length - ind; } }, /** * @type {Number} */ selectionStart: { get: function() { return this._textarea.selectionStart; }, set: function(n) { this._textarea.selectionStart = n; } }, /** * @type {Number} */ selectionEnd: { get: function() { return this._textarea.selectionEnd; }, set: function(n) { this._textarea.selectionEnd = n; } }, /** * @type {Boolean} */ focused: { get: function() { return this._focused; }, set: function(bool) { this._focused = bool; if (bool) { this._textarea.focus(); } else { this._textarea.blur(); } } }, /** [lang]ja] * プレースホルダ. [/lang] * @type {String} */ placeholder: { get: function() { return this._textarea.placeholder; }, set: function(value) { this._textarea.placeholder = value; } }, /** * テキストエリアに入力された値. * @type {String} */ value: { get: function() { return this._textarea.value; }, set: function(value) { this._textarea.value = value; } }, /** * テキストエリアの横幅. * @type {Number} */ width: { get: function() { return this._width; }, set: function(width) { this._width = width; this._style.width = width + 'px'; this._textarea.style.width = width + 'px'; } }, /** * テキストエリアの縦幅. * @type {Number} */ height: { get: function() { return this._height; }, set: function(height) { this._height = height; this._style.height = height + 'px'; this._textarea.style.height = height + 'px'; } } }); /** * @scope enchant.widget.AlertScene */ enchant.widget.AlertScene = enchant.Class.create(enchant.widget.Modal, { /** * アラートシーン. * 他の入力を遮り, アラートを表示する. * @param {*} content 表示するコンテンツ. * @param {String} acceptName 了承ボタンのラベル. * @example * var alert = new ConfirmScene('それはできません', 'OK'); * alert.callback = function() { * }; * alert.onaccept = function() { * }; * @constructs * @extends enchant.widget.Modal */ initialize: function(content, acceptName) { var core = enchant.Core.instance; enchant.widget.Modal.call(this); this._onaccept = function() { }; this.callback = function() { }; acceptName = acceptName || enchant.widget._env.acceptName; var alert = new enchant.widget.Alert(content, acceptName); this.addChild(alert); alert.alignHorizontalCenterIn(this).alignVerticalCenterIn(this); var scene = this; alert.onaccept = function() { core.popScene(); scene._onaccept.apply(this, arguments); }; alert.addEventListener(enchant.Event.ACCEPT, function() { scene.callback(); }); this.addEventListener(enchant.Event.ENTER, function() { Effect.popup.call(alert); }); }, /** * @type {Function} */ onaccept: { get: function() { return this._onaccept; }, set: function(func) { this._onaccept = func; } } }); /** * @scope enchant.widget.ConfirmScene */ enchant.widget.ConfirmScene = enchant.Class.create(enchant.widget.Modal, { /** * コンファームシーン. * 他の入力を遮り, 選択画面を表示する. * @param {*} content 表示するコンテンツ. * @param {String} acceptName 了承ボタンのラベル. * @param {String} cancelName キャンセルボタンのラベル. * @example * var confirm = new ConfirmScene('よろしいですか', 'OK', 'NO'); * confirm.callback = function(bool) { * // acceptならtrue, cancelならfalseが返ってってくる. * }; * // cancel, accept個別に処理を設定することも可能. * confirm.oncancel = function() { * }; * confirm.onaccept = function() { * }; * @constructs * @extends enchant.widget.Modal */ initialize: function(content, acceptName, cancelName) { var core = enchant.Core.instance; enchant.widget.Modal.call(this); this._oncancel = function() { }; this._onaccept = function() { }; this.callback = function() { }; cancelName = cancelName || enchant.widget._env.cancelName; acceptName = acceptName || enchant.widget._env.acceptName; var confirm = new enchant.widget.Confirm(content, acceptName, cancelName); this.addChild(confirm); confirm.alignHorizontalCenterIn(this).alignVerticalCenterIn(this); var scene = this; confirm.oncancel = function() { core.popScene(); scene._oncancel.apply(this, arguments); }; confirm.onaccept = function() { core.popScene(); scene._onaccept.apply(this, arguments); }; confirm.addEventListener(enchant.Event.CANCEL, function() { scene.callback(false); }); confirm.addEventListener(enchant.Event.ACCEPT, function() { scene.callback(true); }); this.addEventListener(enchant.Event.ENTER, function() { Effect.popup.call(confirm); }); }, /** * @type {Function} */ oncancel: { get: function() { return this._oncancel; }, set: function(func) { this._oncancel = func; } }, /** * @type {Function} */ onaccept: { get: function() { return this._onaccept; }, set: function(func) { this._onaccept = func; } } }); /** * @scope enchant.widget.PromptScene */ enchant.widget.PromptScene = enchant.Class.create(enchant.widget.Modal, { /** * コンファームシーン. * 他の入力を遮り, 入力画面を表示する. * 複数行に渡る入力をさせたい時は, {@link enchant.widget.InputScene}を使用する. * @param {*} content 表示するコンテンツ. * @param {String} acceptName 了承ボタンのラベル. * @param {String} cancelName キャンセルボタンのラベル. * @param {String} placeholder プレースホルダ. * @example * var confirm = new PromptScene('名前を入力してください', 'OK', 'cancel'); * confirm.placeholder = 'なまえ'; * confirm.callback = function(text) { * // acceptなら入力された文字列, cancelならnullが返ってってくる. * }; * // cancel, accept個別に処理を設定することも可能. * confirm.oncancel = function() { * }; * confirm.onaccept = function(text) { * }; * @see enchant.widget.InputScene * @constructs * @extends enchant.widget.Modal */ initialize: function(content, acceptName, cancelName, placeholder) { var core = enchant.Core.instance; var margin = enchant.widget._env.dialogMargin; enchant.widget.Modal.call(this); cancelName = cancelName || enchant.widget._env.cancelName; acceptName = acceptName || enchant.widget._env.acceptName; this.callback = function() { }; this._oncancel = function() { }; this._onaccept = function() { }; placeholder = placeholder || ''; var prompt = this._prompt = new enchant.widget.Prompt(content, acceptName, cancelName, placeholder); prompt.alignHorizontalCenterIn(this).alignVerticalCenterIn(this); this.addChild(prompt); var scene = this; prompt.oncancel = function() { core.popScene(); scene._oncancel.apply(this, arguments); }; prompt.onaccept = function() { core.popScene(); scene._onaccept.apply(this, arguments); }; prompt.addEventListener(enchant.Event.CANCEL, function() { scene.callback(null); }); prompt.addEventListener(enchant.Event.ACCEPT, function() { scene.callback(prompt.value); }); this.addEventListener(enchant.Event.ENTER, function() { Effect.popup.call(prompt); }); this.addEventListener(enchant.Event.UP_BUTTON_DOWN, function() { if (prompt._input.focused) { prompt._input.selectionStart = 0; prompt._input.selectionEnd = 0; } }); this.addEventListener(enchant.Event.DOWN_BUTTON_DOWN, function() { if (prompt._input.focused) { prompt._input.selectionStart = prompt._input.value.length; prompt._input.selectionEnd = prompt._input.value.length; } }); this.addEventListener(enchant.Event.LEFT_BUTTON_DOWN, function() { if (prompt._input.focused) { prompt._input.selectionStart -= 1; prompt._input.selectionEnd -= 1; } }); this.addEventListener(enchant.Event.RIGHT_BUTTON_DOWN, function() { if (prompt._input.focused) { prompt._input.selectionStart += 1; } }); }, /** * content of prompt * @type {String} */ value: { get: function() { return this._prompt.value; }, set: function(value) { this._prompt.value = value; } }, /** * @type {Function} */ oncancel: { get: function() { return this._oncancel; }, set: function(func) { this._oncancel = func; } }, /** * @type {Function} */ onaccept: { get: function() { return this._onaccept; }, set: function(func) { this._onaccept = func; } } }); /** * @scope enchant.widget.InputScene */ enchant.widget.InputScene = enchant.Class.create(enchant.widget.Modal, { /** * インプットシーン. * 他の入力を遮り, 入力画面を表示する. * {@link enchant.widget.PromptScene}と違い, 複数行に渡る入力ができる. * @param {*} content 表示するコンテンツ. * @param {String} acceptName 了承ボタンのラベル. * @param {String} cancelName キャンセルボタンのラベル. * @param {String} placeholder プレースホルダ. * @example * var input = new InputScene('新しいツイート', 'ツイート', 'やめる', '@twitter '); * input.callback = function(text) { * // acceptなら入力された文字列, cancelならnullが返ってってくる. * }; * // cancel, accept個別に処理を設定することも可能. * input.oncancel = function() { * }; * input.onaccept = function(text) { * }; * @constructs * @extends enchant.widget.Modal */ initialize: function(text, acceptName, cancelName, placeholder) { var core = enchant.Core.instance; var minheight = enchant.widget._env.inputMinHeight; var maxheight = enchant.widget._env.inputMaxHeight; var dh = maxheight - minheight; this.callback = function() { }; this._oncancel = function() { }; this._onaccept = function() { }; this._menu = null; cancelName = cancelName || enchant.widget._env.cancelName; acceptName = acceptName || enchant.widget._env.acceptName; placeholder = placeholder || ''; enchant.widget.Modal.call(this); var scene = this; var cancel = new enchant.widget.Button(cancelName); var accept = new enchant.widget.Button(acceptName); var bar = new enchant.widget.NavigationBar(text, cancel, accept); this.addChild(bar); var textarea = this._textarea = new enchant.widget.InputTextArea(); textarea.y += bar.height; textarea.width = core.width; textarea.height = maxheight; textarea.placeholder = placeholder; textarea.oncancel = function() { core.popScene(); scene._oncancel.apply(this, arguments); }; textarea.onaccept = function() { core.popScene(); scene._onaccept.apply(this, arguments); }; this.addChild(textarea); var _area = textarea._textarea; _area.onfocus = function() { Effect.resizeTo.call(textarea, core.width, minheight, 5, enchant.Easing.QUAD_EASEOUT); if (scene._menu != null) { scene._menu.tl.moveBy(0, -dh, 5, enchant.Easing.QUAD_EASEOUT); } }; _area.onblur = function() { Effect.resizeTo.call(textarea, core.width, maxheight, 5, enchant.Easing.QUAD_EASEOUT); if (scene._menu != null) { scene._menu.tl.moveBy(0, dh, 5, enchant.Easing.QUAD_EASEOUT); } }; cancel.addEventListener(enchant.Event.TOUCH_END, function() { textarea.dispatchEvent(new enchant.Event(enchant.Event.CANCEL)); scene.callback(null); }); accept.addEventListener(enchant.Event.TOUCH_END, function() { textarea.dispatchEvent(new enchant.Event(enchant.Event.ACCEPT)); scene.callback(textarea.value); }); this.addEventListener(enchant.Event.UP_BUTTON_DOWN, function() { if (textarea.focused) { textarea.selectionStart += textarea._prev; textarea.selectionEnd += textarea._prev; textarea._updateVerticalDist(); } }); this.addEventListener(enchant.Event.DOWN_BUTTON_DOWN, function() { if (textarea.focused) { textarea.selectionStart += textarea._next; textarea._updateVerticalDist(); } }); this.addEventListener(enchant.Event.LEFT_BUTTON_DOWN, function() { if (textarea.focused) { textarea.selectionStart -= 1; textarea.selectionEnd -= 1; textarea._updateVerticalDist(); } }); this.addEventListener(enchant.Event.RIGHT_BUTTON_DOWN, function() { if (textarea.focused) { textarea.selectionStart += 1; textarea._updateVerticalDist(); } }); }, /** * @type {*} */ menu: { get: function() { return this._menu; }, set: function(menu) { if (this._menu) { this.removeChild(this._menu); } this.x = 0; this.y = enchant.widget._env.itemHeight + enchant.widget._env.inputMaxHeight; this.addChild(menu); this._menu = menu; } }, /** * テキストエリアに入力された値. * @type {String} */ value: { get: function() { return this._textarea.value; }, set: function(value) { this._textarea.value = value; } }, /** * @type {String} */ placeholder: { get: function() { return this._textarea.placeholder; }, set: function(str) { this._textarea.placeholder = str; } }, /** * @type {Function} */ oncancel: { get: function() { return this._oncancel; }, set: function(func) { this._oncancel = func; } }, /** * @type {Function} */ onaccept: { get: function() { return this._onaccept; }, set: function(func) { this._onaccept = func; } } }); /** * @scope enchant.widget.ListElement */ enchant.widget.ListElement = enchant.Class.create(enchant.widget.EntityGroup, { /** * Listの項目. * 通常, {@link enchant.widget.ListItem}や, {@link enchant.widget.ListItemVertical}を使用する. * @param {Number} width 要素の横幅. * @param {Number} height 要素の縦幅. * @constructs * @extends enchant.widget.EntityGroup */ initialize: function(width, height) { enchant.widget.EntityGroup.call(this, width, height); this._content; this._rawContent; }, /** * 変更を更新する. */ refresh: function() { var content = this._content; var margin = enchant.widget._env.listItemMargin; if (content) { content.alignLeftIn(this, margin).alignVerticalCenterIn(this); } this.background = this._background; }, /** * ListElementの内容. * @type {enchant.Entity[]} */ content: { get: function() { return this._rawContent; }, set: function(content) { this._rawContent = content; content = enchant.widget.parseContent(content); if (this._content) { this.removeChild(this._content); } this.addChild(content); this._content = content; this.refresh(); } }, /** * @type {Number} */ width: { get: function() { return this._width; }, set: function(width) { this._style.width = (this._width = width) + 'px'; if (this.background instanceof enchant.widget.Ninepatch) { this.background.width = this.width; } if (this._content) { this.refresh(); } } }, /** * @type {Number} */ height: { get: function() { return this._height; }, set: function(height) { this._style.height = (this._height = height) + 'px'; if (this.background instanceof enchant.widget.Ninepatch) { this.background.height = this.height; } if (this._content) { this.refresh(); } } } }); /** * @scope enchant.widget.ListItem */ enchant.widget.ListItem = enchant.Class.create(enchant.widget.ListElement, { /** * Listの項目. * アイコン, 左端のボタンが設定できる. * 縦に並ぶ項目を設定したいときは, {@link enchant.widget.ListItemVertical}を使用する. * @param {Number} width 要素の横幅. * @param {Number} height 要素の縦幅. * @param {*} [content] ListItemの内容. * @param {enchant.Sprite|enchant.Surface} [icon] ListItemのアイコン. * @param {enchant.Sprite|enchant.Surface} [rightIcon] ListItemの左側のアイコン. * @see enchant.widget.ListItemVertical * @constructs * @extends enchant.widget.ListElement */ initialize: function(width, height, content, icon, rightIcon) { var core = enchant.Core.instance; width = width || core.width; height = height || enchant.widget._env.itemHeight; content = content || ''; enchant.widget.ListElement.call(this, width, height); this._icon; this._rawIcon; this._rightIcon; this._rawRightIcon; this.content = content; if (icon) { this.icon = icon; } if (rightIcon) { this.rightIcon = rightIcon; } var np = new enchant.widget.Ninepatch(this.width, this.height); np.src = core.assets['listItemBg.png']; this.background = np; }, /** * 変更を更新する. */ refresh: function() { var icon = this._icon; var content = this._content; var right = this._rightIcon; var margin = enchant.widget._env.listItemMargin; if (icon) { Adjust.fitToY.call(icon, this, margin, margin); icon.alignLeftIn(this, margin).alignVerticalCenterIn(this); if (content) { content.alignRightOf(icon, margin).alignVerticalCenterIn(this); } } else if (content) { content.alignLeftIn(this, margin).alignVerticalCenterIn(this); } if (right) { right.alignRightIn(this, margin).alignVerticalCenterIn(this); } }, /** * アイコン. * 左側に表示される. * @type {enchant.Sprite|enchant.Surface} */ icon: { get: function() { return this._rawIcon; }, set: function(icon) { this._rawIcon = icon; icon = enchant.widget.parseContent(icon); if (this._icon) { this.removeChild(this._icon); } this.addChild(icon); this._icon = icon; this.refresh(); } }, /** * 右側のアイコン. * 右側に表示される. * @type {enchant.Sprite|enchant.Surface} */ rightIcon: { get: function() { return this._rawRightIcon; }, set: function(right) { this._rawRightIcon = right; right = enchant.widget.parseContent(right); if (this._rightIcon) { this.removeChild(this._rightIcon); } this.addChild(right); this._rightIcon = right; this.refresh(); } } }); /** * @scope enchant.widget.ListItemVertical */ enchant.widget.ListItemVertical = enchant.Class.create(enchant.widget.ListElement, { /** * Listの項目. * ヘッダ, フッタが設定できる. * @param {Number} width 要素の横幅. * @param {Number} height 要素の縦幅. * @param {*} [content] ListItemVerticalの内容. * @param {*} [header] ListItemのヘッダ. * @param {*} [footer] ListItemのフッタ. * @constructs * @extends enchant.widget.ListElement */ initialize: function(width, height, content, header, footer) { var core = enchant.Core.instance; enchant.widget.ListElement.call(this, width, height); this._header; this._rawHeader; this._footer; this._rawFooter; if (content) { this.content = content; } if (header) { this.header = header; } if (footer) { this.footer = footer; } this.refresh(); var np = new enchant.widget.Ninepatch(this.width, this.height); np.src = core.assets['listItemBg.png']; this.background = np; }, /** * 変更を更新する. */ refresh: function() { var header = this._header; var footer = this._footer; var content = this._content; var margin = enchant.widget._env.listItemMargin; if (header) { header.alignLeftIn(this, margin).alignTopIn(this, margin); Adjust.fillX.call(content, this, margin); if (content) { content.alignLeftIn(this, margin).alignBottomOf(header, margin); } } else { Adjust.fillX.call(content, this, margin); if (content) { content.alignLeftIn(this, margin).alignTopIn(this, margin); } } if (footer) { footer.alignLeftIn(this, margin).alignBottomOf(content, margin); } var height = 0; var p; var scale; var contents = [ header, content, footer ]; for (prop in contents) { p = contents[prop]; if (p) { scale = p.scaleY || 1; height += ~~(p.height * scale); height += margin * 2; } } this._style.height = (this._height = height) + 'px'; if (this.background instanceof enchant.widget.Ninepatch) { this.background.height = this.height; } }, /** * ヘッダ. * contentの上に表示される. * @type {*} */ header: { get: function() { return this._rawHeader; }, set: function(header) { this._rawHeader = header; header = enchant.widget.parseContent(header); if (this._header) { this.removeChild(this._header); } this.addChild(header); this._header = header; this.refresh(); } }, /** * フッタ. * contentの下に表示される. * @type {*} */ footer: { get: function() { return this._rawFooter; }, set: function(footer) { this._rawFooter = footer; footer = enchant.widget.parseContent(footer); if (this._footer) { this.removeChild(this._footer); } this.addChild(footer); this._footer = footer; this.refresh(); } } }); /** * @scope enchant.widget.ScrollView */ enchant.widget.ScrollView = enchant.Class.create(enchant.widget.EntityGroup, { /** * スクロールビュー. * 設定したコンテンツをスクロール可能. * @param {Number} width ビューの横幅. * @param {Number} height ビューの縦幅. * @constructs * @extends enchant.widget.EntityGroup */ initialize: function(width, height) { enchant.widget.EntityGroup.call(this, width, height); this._style.overflow = 'hidden'; this._content; }, /** * ScrollViewの内容. * @type {enchant.Entity} */ content: { get: function() { return this._content; }, set: function(content) { if (this._content) { this.removeChild(this._content); } this.addChild(content); this._content = content; } }, /** * コンテンツのスクロールを行う. * 正の値が上方向のスクロールとなる. * @param {Number} dy スクロール量. */ scroll: function(dy) { if (!this._content) { return; } if (this.height >= this._content.height) { this._content.y = 0; return; } var max = 0 var min = this.height - this._content.height var sy = this._content.y + dy; if (sy > max) { dy = max - this._content.y; } else if (sy < min) { dy = min - this._content.y; } this._content.y += dy; } }); /** * @scope enchant.widget.ListView */ enchant.widget.ListView = enchant.Class.create(enchant.widget.ScrollView, { /** * リストビュー. * @param {Number} width メニューの横幅. * @param {Number} height メニューの縦幅. * @param {Boolean} draggable 項目をドラッグできるか設定する. * List view. * @constructs * @extends enchant.widget.ScrollView */ initialize: function(width, height, draggable) { enchant.widget.ScrollView.call(this, width, height); var detector = new enchant.widget.GestureDetector(this); this.draggable = !!draggable; this.content = []; var dragging = null; var dy = 0; var prev = null; var next = null; var pthreshold = 0; var nthreshold = 0; this._clipping = true; enchant.widget.GestureDetector.gestureEvents.forEach(function(type) { this.addEventListener(type, function(e) { var item = this.getSelectedItem(e); if (item != null) { item.dispatchEvent(e); } }); }, this); var removeChild = enchant.widget.EntityGroup.prototype.removeChild; var insertBefore = enchant.widget.EntityGroup.prototype.insertBefore; var that = this; var checkChangePos = function(direction) { var y = dragging.y; var my = dragging.height; var nextSibling; if (prev && y <= pthreshold && direction < 0) { prev.y += my; removeChild.call(that._content, dragging); insertBefore.call(that._content, dragging, prev); updateHoldStat(dragging); } else if (next && nthreshold <= y && direction > 0) { next.y -= my; removeChild.call(that._content, dragging); var nextSibling = that._content.childNodes[that._content.childNodes.indexOf(next) + 1]; insertBefore.call(that._content, dragging, nextSibling); updateHoldStat(dragging); } }; var updateHoldStat = function(element) { var i = that._content.childNodes.indexOf(element); if (i > 0) { prev = that._content.childNodes[i - 1]; pthreshold = prev.y + prev.height - element.height / 2; } else { prev = null; } if (i < that._content.childNodes.length - 1) { next = that._content.childNodes[i + 1]; nthreshold = next.y - element.height / 2; } else { next = null; } }; this.addEventListener(enchant.Event.ENTER_FRAME, function() { if (dy != 0) { var old = this._content.y; this.scroll(dy); checkChangePos(-dy); dragging.y -= this._content.y - old; } }); this.addEventListener(enchant.Event.HOLD, function(e) { if (!this.draggable) { return; } dragging = this.getSelectedItem(e); if (dragging == null) { return; } dragging.opacity = 0.8; dragging._style.zIndex = 2; updateHoldStat(dragging); }); this.addEventListener(enchant.Event.RELEASE, function() { if (!this.draggable || dragging == null) { return; } dy = 0; if (prev) { dragging.y = prev.y + prev.height; } else { dragging.y = 0; } dragging.opacity = 1.0; dragging._style.zIndex = 0; dragging = null; prev = null; next = null; }); var spd = 40; this.addEventListener(enchant.Event.DRAG, function(e) { if (!this.draggable || dragging == null) { return; } checkChangePos(e.dy); dragging.y += e.dy; if (e.localY < spd) { dy = spd - e.localY; } else if (this.height - spd < e.localY) { dy = this.height - spd - e.localY; } else { dy = 0; } }); this.addEventListener(enchant.Event.SLIP, function(e) { this.scroll(e.dy); }); }, /** * リストビューの内容を設定する. * @type {enchant.widget.ListElement[]} */ content: { get: function() { return this._content.childNodes; }, set: function(content) { var addChild = enchant.widget.EntityGroup.prototype.addChild; var removeChild = enchant.widget.EntityGroup.prototype.removeChild; if (this._content) { removeChild.call(this, this._content); } var list = new List(content); list.width = this.width; addChild.call(this, list); this._content = list; } }, /** * イベントの対象を取得する. * @param {enchant.Event} event * @return {enchant.widget.ListElement} */ getSelectedItem: function(e) { var y = e.localY - this._content.y; var list = this._content; var child; var h = 0; for (var i = 0, l = list.childNodes.length; i < l; i++) { child = list.childNodes[i]; h += child.height; if (h > y) { return child; } } return null; }, addChild: function(child) { this._content.addChild(child); }, removeChild: function(child) { this._content.removeChild(child); }, insertBefore: function(child, reference) { this._content.insertBefore(child, reference); } }); var _emptyFunction = function(){}; /** * @scope enchant.widget.LazyListItem */ enchant.widget.LazyListItem = enchant.Class.create(enchant.widget.ListItem, { /** * LazyListItem is a class which can be used in an enchant.widget.LazyListView instance * to enable the lazy loading of the content of a list item. * The LazyListView instance will call the loadResources function of the LazyListItem instance * when it feels like the content will be required soon. * Implementors must implement the loadResources function. * See the LazyListView example of enchant.js (examples/plugins/widget/LazyListView/). * * @see enchant.widget.LazyListView * @see enchant.widget.ListItem * @constructs * @extends enchant.widget.ListItem */ initialize: function() { enchant.widget.ListItem.apply(this, arguments); }, _loadResources: function() { if(this.loadResources) { this.loadResources(); this._loadResources = _emptyFunction; } } }); var _enchantWidgetListViewPrototypeScroll = enchant.widget.ListView.prototype.scroll; var _enchantWidgetListViewPrototypeAddChild = enchant.widget.ListView.prototype.addChild; var _enchantWidgetListViewPrototypeRemoveChild = enchant.widget.ListView.prototype.removeChild; var _enchantWidgetListViewPrototypeInsertBefore = enchant.widget.ListView.prototype.insertBefore; /** * @scope enchant.widget.LazyListView */ enchant.widget.LazyListView = enchant.Class.create(enchant.widget.ListView, { /** * LazyListView is a class which enables a ListView to load the content of it's * child ListItems lazily by using enchant.widget.LazyListItem (s). * It is also possible to use regular ListItems which will behave * like if they where added to a ListView (therefore, no lazy initialization). * Furthermore, this LazyListView will dispatch an enchant.Event.CONTENT_REQUESTED event * when the ListView feels like the available content is not sufficient. * The enchant.Event.CONTENT_REQUESTED can be used to add new items to the LazyListView. * See the LazyListView example of enchant.js (examples/plugins/widget/LazyListView/). * * @see enchant.widget.ListView * @see enchant.widget.LazyListItem * @constructs * @extends enchant.widget.ListView */ initialize: function() { enchant.widget.ListView.apply(this, arguments); }, _updateContent: function() { var visibleHeight = this.height - this._content.y + 100; var content = this.content; var contentLength = content.length; for(var i = 0; i < contentLength; i++) { if(content[i].y <= visibleHeight && content[i]._loadResources) { content[i]._loadResources.call(content[i]); } else if(content[i].y > visibleHeight) { return; } } var event = new enchant.Event(enchant.Event.CONTENT_REQUESTED); this.dispatchEvent(event); // as we did not return in the loop there are not enough list items available, request new content }, scroll: function() { _enchantWidgetListViewPrototypeScroll.apply(this, arguments); this._updateContent(); }, addChild: function(child) { _enchantWidgetListViewPrototypeAddChild.apply(this, arguments); this._updateContent(); }, removeChild: function(child) { _enchantWidgetListViewPrototypeRemoveChild.apply(this, arguments); this._updateContent(); }, insertBefore: function(child, reference) { _enchantWidgetListViewPrototypeInsertBefore.apply(this, arguments); this._updateContent(); } }); var List = enchant.Class.create(enchant.widget.EntityGroup, { initialize: function(array) { var core = enchant.Core.instance; enchant.widget.EntityGroup.call(this); this.width = core.width; this.height = core.height; this._itemHeight = 0; var element; for (var i = 0, l = array.length; i < l; i++) { element = array[i]; this.addChild(element); } this._dragging = null; this._pthreshold = 0; this._nthreshold = 0; this._index = 0; }, addChild: function(child) { var i = this.childNodes.length; enchant.widget.EntityGroup.prototype.addChild.call(this, child); this.refresh(i - 1); }, insertBefore: function(child, reference) { enchant.widget.EntityGroup.prototype.insertBefore.call(this, child, reference); var i = this.childNodes.indexOf(child); this.refresh(i - 1); }, removeChild: function(child) { var i = this.childNodes.indexOf(child); if (i != -1) { enchant.widget.EntityGroup.prototype.removeChild.call(this, child); this.refresh(i - 1); } }, refresh: function(i) { var i, l, h, start, child; if (i > 0) { start = this.childNodes[i - 1]; h = start.y + start.height; } else { i = 0; h = 0; } for (l = this.childNodes.length; i < l; i++) { child = this.childNodes[i]; child.y = h; h += child.height; } this.height = this._itemHeight = h; }, _getElementByLocalPosition: function(localX, localY) { var child; var h = 0; for (var i = 0, l = this.childNodes.length; i < l; i++) { child = this.childNodes[i]; h += child.height; if (h > localY) { break; } } return child; } }); /** * @scope enchant.widget.NavigationBar */ enchant.widget.NavigationBar = enchant.Class.create(enchant.widget.EntityGroup, { /** * ナビゲーションバー. * 中央, 右, 左それぞれに項目を設定できる. * @param {*} center 中央に表示させたい項目. * @param {*} left 左に表示させたい項目. * @param {*} right 右に表示させたい項目. * @constructs * @extends enchant.widget.EntityGroup */ initialize: function(center, left, right) { var core = enchant.Core.instance; enchant.widget.EntityGroup.call(this, core.width, enchant.widget._env.itemHeight); this._center; this._rawCenter; this._left; this._rawLeft; this._right; this._rawRight; this.center = center; if (left) { this.left = left; } if (right) { this.right = right; } this.refresh(); var np = new enchant.widget.Ninepatch(this.width, this.height); np.src = core.assets['navigationBar.png']; this.background = np; }, /** * 変更を更新する. */ refresh: function() { var center = this._center; var left = this._left; var right = this._right; var margin = enchant.widget._env.listItemMargin; if (center) { center.alignHorizontalCenterIn(this).alignVerticalCenterIn(this); } if (left) { left.alignLeftIn(this, margin).alignVerticalCenterIn(this); } if (right) { right.alignRightIn(this, margin).alignVerticalCenterIn(this); } }, /** * 中央の項目. * @type {*} */ center: { get: function() { return this._rawCenter; }, set: function(center) { this._rawCenter = center; center = enchant.widget.parseContent(center, enchant.widget._env.navigationBarFont); if (this._center) { this.removeChild(this._center); } this.addChild(center); this._center = center; this.refresh(); } }, /** * 左の項目. * 左詰めで表示される. * @type {*} */ left: { get: function() { return this._rawLeft; }, set: function(left) { this._rawLeft = left; left = enchant.widget.parseContent(left); if (this._left) { this.removeChild(this._left); } this.addChild(left); this._left = left; this.refresh(); } }, /** * 右の項目. * 右詰めで表示される. * @type {*} */ right: { get: function() { return this._rawRight; }, set: function(right) { this._rawRight = right; right = enchant.widget.parseContent(right); if (this._right) { this.removeChild(this._right); } this.addChild(right); this._right = right; this.refresh(); } } }); enchant.widget.Icon = enchant.Class.create(enchant.widget.EntityGroup, { initialize: function(icon, text) { enchant.widget.EntityGroup.call(this, 44, 44); icon = enchant.widget.parseContent(icon); text = enchant.widget.parseContent(text, enchant.widget._env.font); var sx = 32 / icon.width; var sy = 32 / icon.height; icon.scaleX = icon.scaleY = Math.min(sx, sy); icon.alignHorizontalCenterIn(this).alignTopIn(this); text.alignHorizontalCenterIn(this).alignBottomOf(icon, -7); this.addChild(icon); this.addChild(text); } }); /** * @scope enchant.widget.IconMenu */ enchant.widget.IconMenu = enchant.Class.create(enchant.widget.EntityGroup, { /** * アイコンが横に並ぶメニュー. * @param {enchant.Entity[]} buttons 設定したいボタンの配列. * @constructs * @extends enchant.widget.EntityGroup */ initialize: function(buttons) { var core = enchant.Core.instance; if (!(buttons instanceof Array)) { buttons = Array.prototype.slice.call(arguments); } enchant.widget.EntityGroup.call(this, core.width, enchant.widget._env.itemHeight); this._bgs = []; this._icons = []; this.content = buttons; this.refresh(); this._bgs.forEach(function(bg) { var width = bg.width; var height = bg.height; var np = new enchant.widget.Ninepatch(width, height); np.src = core.assets['iconMenuBg.png']; bg.image = np; }); }, /** * 変更を更新する. */ getSelectedItem: function(e) { var x = e.localX; var list = this._bgs; var child; var w = 0; for (var i = 0, l = list.childNodes.length; i < l; i++) { child = list.childNodes[i]; w += child.width; if (w > x) { return this._icons[i]; } } return null; }, refresh: function() { var icon, bg, bgwidth; var margin = enchant.widget._env.listItemMargin; var arr = distribute(this.width, this._icons.length); var _width = 0; var menu = this; for (var i = 0, l = this._icons.length; i < l; i++) { bgwidth = arr[i]; icon = this._icons[i]; bg = this._bgs[i]; bg.width = bgwidth; bg.height = this.height; bg.image.resize(bg.width, bg.height); bg.x = _width; icon.addEventListener(enchant.Event.TOUCH_END, (function(bg) { return function(e) { bg.dispatchEvent(e); }; })(bg)); bg.addEventListener(enchant.Event.TOUCH_END, (function(i, elem) { return function(e) { var evt = new enchant.Event(enchant.Event.TAP); evt.x = e.x; evt.y = e.y; evt.index = i; evt.element = elem; menu.dispatchEvent(evt); }; })(i, icon)); icon.alignHorizontalCenterIn(bg).alignVerticalCenterIn(bg); icon.x += _width; _width += bg.width; } }, addChild: function(child) { var core = enchant.Core.instance; var addChild = enchant.widget.EntityGroup.prototype.addChild; var size = enchant.widget._env.itemHeight; var sp = new enchant.Sprite(size, size); addChild.call(this, sp); this._bgs.push(sp); addChild.call(this, child); this._icons.push(child); var np = new enchant.widget.Ninepatch(sp.width, sp.height); np.src = core.assets['iconMenuBg.png']; sp.image = np; this.refresh(); }, insertBefore: function(child, target) { var core = enchant.Core.instance; var insertBefore = enchant.widget.EntityGroup.prototype.insertBefore; var i = this._icons.indexOf(target); var size = enchant.widget._env.itemHeight; var sp, np; if (i != -1) { target = this._bgs[i]; sp = new enchant.Sprite(size, size); insertBefore.call(this, sp, target); this._bgs.splice(i, 0, sp); insertBefore.call(this, child, target); this._icons.splice(i, 0, child); np = new enchant.widget.Ninepatch(sp.width, sp.height); np.src = core.assets['iconMenuBg.png']; sp.image = np; this.refresh(); } }, removeChild: function(child) { var removeChild = enchant.widget.EntityGroup.prototype.removeChild; var i = this._icons.indexOf(child); if (i != -1) { var bg = this._bgs[this._bgs.length - 1]; removeChild.call(this, bg); this._bgs.pop(); removeChild.call(this, child); this._icons.splice(i, 1); this.refresh(); } }, /** * アイコンを設定する. * @param {enchant.Entity[]} content 表示させたいオブジェクトの配列. */ content: { get: function() { return this._icons; }, set: function(content) { var removeChild = enchant.widget.EntityGroup.prototype.removeChild; var menu = this; if (this.childNodes) { this.childNodes.slice().forEach(function(child) { removeChild.call(menu, child); }); } content.forEach(function(child) { menu.addChild(child); }); } } }); })();
/*! * jquery.event.drag - v 2.3.0 * Copyright (c) 2010 Three Dub Media - http://threedubmedia.com * Open Source MIT License - http://threedubmedia.com/code/license */ // Created: 2008-06-04 // Updated: 2012-05-21 // Updated: 2016-08-16 Luiz Gonzaga dos Santos Filho // REQUIRES: jquery 1.8 +, , event.drag 2.3.0 // TESTED WITH: jQuery 1.8.3, 1.11.2, 2.2.4, and 3.1.0 ;(function( $ ) { // add the jquery instance method $.fn.drag = function( str, arg, opts ){ // figure out the event type var type = typeof str == "string" ? str : "", // figure out the event handler... fn = $.isFunction( str ) ? str : $.isFunction( arg ) ? arg : null; // fix the event type if ( type.indexOf("drag") !== 0 ) type = "drag"+ type; // were options passed opts = ( str == fn ? arg : opts ) || {}; // trigger or bind event handler return fn ? this.on( type, opts, fn ) : this.trigger( type ); }; // local refs (increase compression) var $event = $.event, $special = $event.special, // configure the drag special event drag = $special.drag = { // these are the default settings defaults: { which: 1, // mouse button pressed to start drag sequence distance: 0, // distance dragged before dragstart not: ':input', // selector to suppress dragging on target elements handle: null, // selector to match handle target elements relative: false, // true to use "position", false to use "offset" drop: true, // false to suppress drop events, true or selector to allow click: false // false to suppress click events after dragend (no proxy) }, // the key name for stored drag data datakey: "dragdata", // prevent bubbling for better performance noBubble: true, // count bound related events add: function( obj ){ // read the interaction data var data = $.data( this, drag.datakey ), // read any passed options opts = obj.data || {}; // count another realted event data.related += 1; // extend data options bound with this event // don't iterate "opts" in case it is a node $.each( drag.defaults, function( key, def ){ if ( opts[ key ] !== undefined ) data[ key ] = opts[ key ]; }); }, // forget unbound related events remove: function(){ $.data( this, drag.datakey ).related -= 1; }, // configure interaction, capture settings setup: function(){ // check for related events if ( $.data( this, drag.datakey ) ) return; // initialize the drag data with copied defaults var data = $.extend({ related:0 }, drag.defaults ); // store the interaction data $.data( this, drag.datakey, data ); // bind the mousedown event, which starts drag interactions $event.add( this, "touchstart mousedown", drag.init, data ); // prevent image dragging in IE... if ( this.attachEvent ) this.attachEvent("ondragstart", drag.dontstart ); }, // destroy configured interaction teardown: function(){ var data = $.data( this, drag.datakey ) || {}; // check for related events if ( data.related ) return; // remove the stored data $.removeData( this, drag.datakey ); // remove the mousedown event $event.remove( this, "touchstart mousedown", drag.init ); // enable text selection drag.textselect( true ); // un-prevent image dragging in IE... if ( this.detachEvent ) this.detachEvent("ondragstart", drag.dontstart ); }, // initialize the interaction init: function( event ){ // sorry, only one touch at a time if ( drag.touched ) return; // the drag/drop interaction data var dd = event.data, results; // check the which directive if ( event.which != 0 && dd.which > 0 && event.which != dd.which ) return; // check for suppressed selector if ( $( event.target ).is( dd.not ) ) return; // check for handle selector if ( dd.handle && !$( event.target ).closest( dd.handle, event.currentTarget ).length ) return; drag.touched = event.type == 'touchstart' ? this : null; dd.propagates = 1; dd.mousedown = this; dd.interactions = [ drag.interaction( this, dd ) ]; dd.target = event.target; dd.pageX = event.pageX; dd.pageY = event.pageY; dd.dragging = null; // handle draginit event... results = drag.hijack( event, "draginit", dd ); // early cancel if ( !dd.propagates ) return; // flatten the result set results = drag.flatten( results ); // insert new interaction elements if ( results && results.length ){ dd.interactions = []; $.each( results, function(){ dd.interactions.push( drag.interaction( this, dd ) ); }); } // remember how many interactions are propagating dd.propagates = dd.interactions.length; // locate and init the drop targets if ( dd.drop !== false && $special.drop ) $special.drop.handler( event, dd ); // if user is not dragging if(!dd.click && dd.distance === 0 && !dd.dragging) { drag.textselect( true ); return; } // disable text selection drag.textselect( false ); // bind additional events... if ( drag.touched ) $event.add( drag.touched, "touchmove touchend", drag.handler, dd ); else $event.add( document, "mousemove mouseup", drag.handler, dd ); // helps prevent text selection or scrolling if ( !drag.touched || dd.live ) return false; }, // returns an interaction object interaction: function( elem, dd ){ var offset = (elem && elem.ownerDocument) ? $( elem )[ dd.relative ? "position" : "offset" ]() || { top:0, left:0 } : { top: 0, left: 0 }; return { drag: elem, callback: new drag.callback(), droppable: [], offset: offset }; }, // handle drag-releatd DOM events handler: function( event ){ // read the data before hijacking anything var dd = event.data; // handle various events switch ( event.type ){ // mousemove, check distance, start dragging case !dd.dragging && 'touchmove': event.preventDefault(); case !dd.dragging && 'mousemove': // drag tolerance, x² + y² = distance² if ( Math.pow( event.pageX-dd.pageX, 2 ) + Math.pow( event.pageY-dd.pageY, 2 ) < Math.pow( dd.distance, 2 ) ) break; // distance tolerance not reached event.target = dd.target; // force target from "mousedown" event (fix distance issue) drag.hijack( event, "dragstart", dd ); // trigger "dragstart" if ( dd.propagates ) // "dragstart" not rejected dd.dragging = true; // activate interaction // mousemove, dragging case 'touchmove': event.preventDefault(); case 'mousemove': if ( dd.dragging ){ // trigger "drag" drag.hijack( event, "drag", dd ); if ( dd.propagates ){ // manage drop events if ( dd.drop !== false && $special.drop ) $special.drop.handler( event, dd ); // "dropstart", "dropend" break; // "drag" not rejected, stop } event.type = "mouseup"; // helps "drop" handler behave } // mouseup, stop dragging case 'touchend': case 'mouseup': default: if ( drag.touched ) $event.remove( drag.touched, "touchmove touchend", drag.handler ); // remove touch events else $event.remove( document, "mousemove mouseup", drag.handler ); // remove page events if ( dd.dragging ){ if ( dd.drop !== false && $special.drop ) $special.drop.handler( event, dd ); // "drop" drag.hijack( event, "dragend", dd ); // trigger "dragend" } drag.textselect( true ); // enable text selection // if suppressing click events... if ( dd.click === false && dd.dragging ) $.data( dd.mousedown, "suppress.click", new Date().getTime() + 5 ); dd.dragging = drag.touched = false; // deactivate element break; } }, // re-use event object for custom events hijack: function( event, type, dd, x, elem ){ // not configured if ( !dd ) return; // remember the original event and type var orig = { event:event.originalEvent, type:event.type }, // is the event drag related or drog related? mode = type.indexOf("drop") ? "drag" : "drop", // iteration vars result, i = x || 0, ia, $elems, callback, len = !isNaN( x ) ? x : dd.interactions.length; // modify the event type event.type = type; // protects originalEvent from side-effects var noop = function(){}; event.originalEvent = new jQuery.Event(orig.event, { preventDefault: noop, stopPropagation: noop, stopImmediatePropagation: noop }); // initialize the results dd.results = []; // handle each interacted element do if ( ia = dd.interactions[ i ] ){ // validate the interaction if ( type !== "dragend" && ia.cancelled ) continue; // set the dragdrop properties on the event object callback = drag.properties( event, dd, ia ); // prepare for more results ia.results = []; // handle each element $( elem || ia[ mode ] || dd.droppable ).each(function( p, subject ){ // identify drag or drop targets individually callback.target = subject; // force propagtion of the custom event event.isPropagationStopped = function(){ return false; }; // handle the event result = subject ? $event.dispatch.call( subject, event, callback ) : null; // stop the drag interaction for this element if ( result === false ){ if ( mode == "drag" ){ ia.cancelled = true; dd.propagates -= 1; } if ( type == "drop" ){ ia[ mode ][p] = null; } } // assign any dropinit elements else if ( type == "dropinit" ) ia.droppable.push( drag.element( result ) || subject ); // accept a returned proxy element if ( type == "dragstart" ) ia.proxy = $( drag.element( result ) || ia.drag )[0]; // remember this result ia.results.push( result ); // forget the event result, for recycling delete event.result; // break on cancelled handler if ( type !== "dropinit" ) return result; }); // flatten the results dd.results[ i ] = drag.flatten( ia.results ); // accept a set of valid drop targets if ( type == "dropinit" ) ia.droppable = drag.flatten( ia.droppable ); // locate drop targets if ( type == "dragstart" && !ia.cancelled ) callback.update(); } while ( ++i < len ) // restore the original event & type event.type = orig.type; event.originalEvent = orig.event; // return all handler results return drag.flatten( dd.results ); }, // extend the callback object with drag/drop properties... properties: function( event, dd, ia ){ var obj = ia.callback; // elements obj.drag = ia.drag; obj.proxy = ia.proxy || ia.drag; // starting mouse position obj.startX = dd.pageX; obj.startY = dd.pageY; // current distance dragged obj.deltaX = event.pageX - dd.pageX; obj.deltaY = event.pageY - dd.pageY; // original element position obj.originalX = ia.offset.left; obj.originalY = ia.offset.top; // adjusted element position obj.offsetX = obj.originalX + obj.deltaX; obj.offsetY = obj.originalY + obj.deltaY; // assign the drop targets information obj.drop = drag.flatten( ( ia.drop || [] ).slice() ); obj.available = drag.flatten( ( ia.droppable || [] ).slice() ); return obj; }, // determine is the argument is an element or jquery instance element: function( arg ){ if ( arg && ( arg.jquery || arg.nodeType == 1 ) ) return arg; }, // flatten nested jquery objects and arrays into a single dimension array flatten: function( arr ){ return $.map( arr, function( member ){ return member && member.jquery ? $.makeArray( member ) : member && member.length ? drag.flatten( member ) : member; }); }, // toggles text selection attributes ON (true) or OFF (false) textselect: function( bool ){ $( document )[ bool ? "off" : "on" ]("selectstart", drag.dontstart ) .css("MozUserSelect", bool ? "" : "none" ); // .attr("unselectable", bool ? "off" : "on" ) document.unselectable = bool ? "off" : "on"; }, // suppress "selectstart" and "ondragstart" events dontstart: function(){ return false; }, // a callback instance contructor callback: function(){} }; // callback methods drag.callback.prototype = { update: function(){ if ( $special.drop && this.available.length ) $.each( this.available, function( i ){ $special.drop.locate( this, i ); }); } }; // patch $.event.$dispatch to allow suppressing clicks var $dispatch = $event.dispatch; $event.dispatch = function( event ){ if ( $.data( this, "suppress."+ event.type ) - new Date().getTime() > 0 ){ $.removeData( this, "suppress."+ event.type ); return; } return $dispatch.apply( this, arguments ); }; // share the same special event configuration with related events... $special.draginit = $special.dragstart = $special.dragend = drag; })( jQuery );
/* * * * (c) 2010-2019 Torstein Honsi * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import H from '../parts/Globals.js'; import '../parts/Color.js'; import '../parts/Legend.js'; import '../parts/Options.js'; import '../parts/Point.js'; import '../parts/ScatterSeries.js'; import '../parts/Series.js'; import U from '../parts/Utilities.js'; var isArray = U.isArray, isNumber = U.isNumber, objectEach = U.objectEach, splat = U.splat; var colorPointMixin = H.colorPointMixin, colorSeriesMixin = H.colorSeriesMixin, extend = H.extend, LegendSymbolMixin = H.LegendSymbolMixin, merge = H.merge, noop = H.noop, pick = H.pick, Point = H.Point, Series = H.Series, seriesType = H.seriesType, seriesTypes = H.seriesTypes; /** * @private * @class * @name Highcharts.seriesTypes.map * * @augments Highcharts.Series */ seriesType('map', 'scatter', /** * The map series is used for basic choropleth maps, where each map area has * a color based on its value. * * @sample maps/demo/all-maps/ * Choropleth map * * @extends plotOptions.scatter * @excluding marker * @product highmaps * @optionparent plotOptions.map */ { animation: false, dataLabels: { /** @ignore-option */ crop: false, // eslint-disable-next-line valid-jsdoc /** @ignore-option */ formatter: function () { return this.point.value; }, /** @ignore-option */ inside: true, /** @ignore-option */ overflow: false, /** @ignore-option */ padding: 0, /** @ignore-option */ verticalAlign: 'middle' }, /** * @ignore-option * * @private */ marker: null, /** * The color to apply to null points. * * In styled mode, the null point fill is set in the * `.highcharts-null-point` class. * * @sample maps/demo/all-areas-as-null/ * Null color * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * * @private */ nullColor: '#f7f7f7', /** * Whether to allow pointer interaction like tooltips and mouse events * on null points. * * @type {boolean} * @since 4.2.7 * @apioption plotOptions.map.nullInteraction * * @private */ stickyTracking: false, tooltip: { followPointer: true, pointFormat: '{point.name}: {point.value}<br/>' }, /** * @ignore-option * * @private */ turboThreshold: 0, /** * Whether all areas of the map defined in `mapData` should be rendered. * If `true`, areas which don't correspond to a data point, are rendered * as `null` points. If `false`, those areas are skipped. * * @sample maps/plotoptions/series-allareas-false/ * All areas set to false * * @type {boolean} * @default true * @product highmaps * @apioption plotOptions.series.allAreas * * @private */ allAreas: true, /** * The border color of the map areas. * * In styled mode, the border stroke is given in the `.highcharts-point` * class. * * @sample {highmaps} maps/plotoptions/series-border/ * Borders demo * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @default '#cccccc' * @product highmaps * @apioption plotOptions.series.borderColor * * @private */ borderColor: '#cccccc', /** * The border width of each map area. * * In styled mode, the border stroke width is given in the * `.highcharts-point` class. * * @sample maps/plotoptions/series-border/ * Borders demo * * @type {number} * @default 1 * @product highmaps * @apioption plotOptions.series.borderWidth * * @private */ borderWidth: 1, /** * Set this option to `false` to prevent a series from connecting to * the global color axis. This will cause the series to have its own * legend item. * * @type {boolean} * @product highmaps * @apioption plotOptions.series.colorAxis */ /** * What property to join the `mapData` to the value data. For example, * if joinBy is "code", the mapData items with a specific code is merged * into the data with the same code. For maps loaded from GeoJSON, the * keys may be held in each point's `properties` object. * * The joinBy option can also be an array of two values, where the first * points to a key in the `mapData`, and the second points to another * key in the `data`. * * When joinBy is `null`, the map items are joined by their position in * the array, which performs much better in maps with many data points. * This is the recommended option if you are printing more than a * thousand data points and have a backend that can preprocess the data * into a parallel array of the mapData. * * @sample maps/plotoptions/series-border/ * Joined by "code" * @sample maps/demo/geojson/ * GeoJSON joined by an array * @sample maps/series/joinby-null/ * Simple data joined by null * * @type {string|Array<string>} * @default hc-key * @product highmaps * @apioption plotOptions.series.joinBy * * @private */ joinBy: 'hc-key', /** * Define the z index of the series. * * @type {number} * @product highmaps * @apioption plotOptions.series.zIndex */ /** * @apioption plotOptions.series.states * * @private */ states: { /** * @apioption plotOptions.series.states.hover */ hover: { /** @ignore-option */ halo: null, /** * The color of the shape in this state. * * @sample maps/plotoptions/series-states-hover/ * Hover options * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @product highmaps * @apioption plotOptions.series.states.hover.color */ /** * The border color of the point in this state. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @product highmaps * @apioption plotOptions.series.states.hover.borderColor */ /** * The border width of the point in this state * * @type {number} * @product highmaps * @apioption plotOptions.series.states.hover.borderWidth */ /** * The relative brightness of the point when hovered, relative * to the normal point color. * * @type {number} * @product highmaps * @default 0.2 * @apioption plotOptions.series.states.hover.brightness */ brightness: 0.2 }, /** * @apioption plotOptions.series.states.normal */ normal: { /** * @productdesc {highmaps} * The animation adds some latency in order to reduce the effect * of flickering when hovering in and out of for example an * uneven coastline. * * @sample {highmaps} maps/plotoptions/series-states-animation-false/ * No animation of fill color * * @apioption plotOptions.series.states.normal.animation */ animation: true }, /** * @apioption plotOptions.series.states.select */ select: { /** * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @default #cccccc * @product highmaps * @apioption plotOptions.series.states.select.color */ color: '#cccccc' }, inactive: { opacity: 1 } } // Prototype members }, merge(colorSeriesMixin, { type: 'map', getExtremesFromAll: true, useMapGeometry: true, forceDL: true, searchPoint: noop, // When tooltip is not shared, this series (and derivatives) requires // direct touch/hover. KD-tree does not apply. directTouch: true, // X axis and Y axis must have same translation slope preserveAspectRatio: true, pointArrayMap: ['value'], // Extend setOptions by picking up the joinBy option and applying it // to a series property setOptions: function (itemOptions) { var options = Series.prototype.setOptions.call(this, itemOptions), joinBy = options.joinBy, joinByNull = joinBy === null; if (joinByNull) { joinBy = '_i'; } joinBy = this.joinBy = splat(joinBy); if (!joinBy[1]) { joinBy[1] = joinBy[0]; } return options; }, // Get the bounding box of all paths in the map combined. getBox: function (paths) { var MAX_VALUE = Number.MAX_VALUE, maxX = -MAX_VALUE, minX = MAX_VALUE, maxY = -MAX_VALUE, minY = MAX_VALUE, minRange = MAX_VALUE, xAxis = this.xAxis, yAxis = this.yAxis, hasBox; // Find the bounding box (paths || []).forEach(function (point) { if (point.path) { if (typeof point.path === 'string') { point.path = H.splitPath(point.path); } var path = point.path || [], i = path.length, even = false, // while loop reads from the end pointMaxX = -MAX_VALUE, pointMinX = MAX_VALUE, pointMaxY = -MAX_VALUE, pointMinY = MAX_VALUE, properties = point.properties; // The first time a map point is used, analyze its box if (!point._foundBox) { while (i--) { if (isNumber(path[i])) { if (even) { // even = x pointMaxX = Math.max(pointMaxX, path[i]); pointMinX = Math.min(pointMinX, path[i]); } else { // odd = Y pointMaxY = Math.max(pointMaxY, path[i]); pointMinY = Math.min(pointMinY, path[i]); } even = !even; } } // Cache point bounding box for use to position data // labels, bubbles etc point._midX = (pointMinX + (pointMaxX - pointMinX) * pick(point.middleX, properties && properties['hc-middle-x'], 0.5)); point._midY = (pointMinY + (pointMaxY - pointMinY) * pick(point.middleY, properties && properties['hc-middle-y'], 0.5)); point._maxX = pointMaxX; point._minX = pointMinX; point._maxY = pointMaxY; point._minY = pointMinY; point.labelrank = pick(point.labelrank, (pointMaxX - pointMinX) * (pointMaxY - pointMinY)); point._foundBox = true; } maxX = Math.max(maxX, point._maxX); minX = Math.min(minX, point._minX); maxY = Math.max(maxY, point._maxY); minY = Math.min(minY, point._minY); minRange = Math.min(point._maxX - point._minX, point._maxY - point._minY, minRange); hasBox = true; } }); // Set the box for the whole series if (hasBox) { this.minY = Math.min(minY, pick(this.minY, MAX_VALUE)); this.maxY = Math.max(maxY, pick(this.maxY, -MAX_VALUE)); this.minX = Math.min(minX, pick(this.minX, MAX_VALUE)); this.maxX = Math.max(maxX, pick(this.maxX, -MAX_VALUE)); // If no minRange option is set, set the default minimum zooming // range to 5 times the size of the smallest element if (xAxis && xAxis.options.minRange === undefined) { xAxis.minRange = Math.min(5 * minRange, (this.maxX - this.minX) / 5, xAxis.minRange || MAX_VALUE); } if (yAxis && yAxis.options.minRange === undefined) { yAxis.minRange = Math.min(5 * minRange, (this.maxY - this.minY) / 5, yAxis.minRange || MAX_VALUE); } } }, // Define hasData function for non-cartesian series. // Returns true if the series has points at all. hasData: function () { return !!this.processedXData.length; // != 0 }, getExtremes: function () { // Get the actual value extremes for colors Series.prototype.getExtremes.call(this, this.valueData); // Recalculate box on updated data if (this.chart.hasRendered && this.isDirtyData) { this.getBox(this.options.data); } this.valueMin = this.dataMin; this.valueMax = this.dataMax; // Extremes for the mock Y axis this.dataMin = this.minY; this.dataMax = this.maxY; }, // Translate the path, so it automatically fits into the plot area box translatePath: function (path) { var series = this, even = false, // while loop reads from the end xAxis = series.xAxis, yAxis = series.yAxis, xMin = xAxis.min, xTransA = xAxis.transA, xMinPixelPadding = xAxis.minPixelPadding, yMin = yAxis.min, yTransA = yAxis.transA, yMinPixelPadding = yAxis.minPixelPadding, i, ret = []; // Preserve the original // Do the translation if (path) { i = path.length; while (i--) { if (isNumber(path[i])) { ret[i] = even ? (path[i] - xMin) * xTransA + xMinPixelPadding : (path[i] - yMin) * yTransA + yMinPixelPadding; even = !even; } else { ret[i] = path[i]; } } } return ret; }, // Extend setData to join in mapData. If the allAreas option is true, // all areas from the mapData are used, and those that don't correspond // to a data value are given null values. setData: function (data, redraw, animation, updatePoints) { var options = this.options, chartOptions = this.chart.options.chart, globalMapData = chartOptions && chartOptions.map, mapData = options.mapData, joinBy = this.joinBy, pointArrayMap = options.keys || this.pointArrayMap, dataUsed = [], mapMap = {}, mapPoint, mapTransforms = this.chart.mapTransforms, props, i; // Collect mapData from chart options if not defined on series if (!mapData && globalMapData) { mapData = typeof globalMapData === 'string' ? H.maps[globalMapData] : globalMapData; } // Pick up numeric values, add index // Convert Array point definitions to objects using pointArrayMap if (data) { data.forEach(function (val, i) { var ix = 0; if (isNumber(val)) { data[i] = { value: val }; } else if (isArray(val)) { data[i] = {}; // Automatically copy first item to hc-key if there is // an extra leading string if (!options.keys && val.length > pointArrayMap.length && typeof val[0] === 'string') { data[i]['hc-key'] = val[0]; ++ix; } // Run through pointArrayMap and what's left of the // point data array in parallel, copying over the values for (var j = 0; j < pointArrayMap.length; ++j, ++ix) { if (pointArrayMap[j] && val[ix] !== undefined) { if (pointArrayMap[j].indexOf('.') > 0) { H.Point.prototype.setNestedProperty(data[i], val[ix], pointArrayMap[j]); } else { data[i][pointArrayMap[j]] = val[ix]; } } } } if (joinBy && joinBy[0] === '_i') { data[i]._i = i; } }); } this.getBox(data); // Pick up transform definitions for chart this.chart.mapTransforms = mapTransforms = chartOptions && chartOptions.mapTransforms || mapData && mapData['hc-transform'] || mapTransforms; // Cache cos/sin of transform rotation angle if (mapTransforms) { objectEach(mapTransforms, function (transform) { if (transform.rotation) { transform.cosAngle = Math.cos(transform.rotation); transform.sinAngle = Math.sin(transform.rotation); } }); } if (mapData) { if (mapData.type === 'FeatureCollection') { this.mapTitle = mapData.title; mapData = H.geojson(mapData, this.type, this); } this.mapData = mapData; this.mapMap = {}; for (i = 0; i < mapData.length; i++) { mapPoint = mapData[i]; props = mapPoint.properties; mapPoint._i = i; // Copy the property over to root for faster access if (joinBy[0] && props && props[joinBy[0]]) { mapPoint[joinBy[0]] = props[joinBy[0]]; } mapMap[mapPoint[joinBy[0]]] = mapPoint; } this.mapMap = mapMap; // Registered the point codes that actually hold data if (data && joinBy[1]) { data.forEach(function (point) { if (mapMap[point[joinBy[1]]]) { dataUsed.push(mapMap[point[joinBy[1]]]); } }); } if (options.allAreas) { this.getBox(mapData); data = data || []; // Registered the point codes that actually hold data if (joinBy[1]) { data.forEach(function (point) { dataUsed.push(point[joinBy[1]]); }); } // Add those map points that don't correspond to data, which // will be drawn as null points dataUsed = ('|' + dataUsed.map(function (point) { return point && point[joinBy[0]]; }).join('|') + '|'); // Faster than array.indexOf mapData.forEach(function (mapPoint) { if (!joinBy[0] || dataUsed.indexOf('|' + mapPoint[joinBy[0]] + '|') === -1) { data.push(merge(mapPoint, { value: null })); // #5050 - adding all areas causes the update // optimization of setData to kick in, even though // the point order has changed updatePoints = false; } }); } else { this.getBox(dataUsed); // Issue #4784 } } Series.prototype.setData.call(this, data, redraw, animation, updatePoints); }, // No graph for the map series drawGraph: noop, // We need the points' bounding boxes in order to draw the data labels, // so we skip it now and call it from drawPoints instead. drawDataLabels: noop, // Allow a quick redraw by just translating the area group. Used for // zooming and panning in capable browsers. doFullTranslate: function () { return (this.isDirtyData || this.chart.isResizing || this.chart.renderer.isVML || !this.baseTrans); }, // Add the path option for data points. Find the max value for color // calculation. translate: function () { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, doFullTranslate = series.doFullTranslate(); series.generatePoints(); series.data.forEach(function (point) { // Record the middle point (loosely based on centroid), // determined by the middleX and middleY options. point.plotX = xAxis.toPixels(point._midX, true); point.plotY = yAxis.toPixels(point._midY, true); if (doFullTranslate) { point.shapeType = 'path'; point.shapeArgs = { d: series.translatePath(point.path) }; } }); series.translateColors(); }, // Get presentational attributes. In the maps series this runs in both // styled and non-styled mode, because colors hold data when a colorAxis // is used. pointAttribs: function (point, state) { var attr = point.series.chart.styledMode ? this.colorAttribs(point) : seriesTypes.column.prototype.pointAttribs.call(this, point, state); // Set the stroke-width on the group element and let all point // graphics inherit. That way we don't have to iterate over all // points to update the stroke-width on zooming. attr['stroke-width'] = pick(point.options[(this.pointAttrToOptions && this.pointAttrToOptions['stroke-width']) || 'borderWidth'], 'inherit'); return attr; }, // Use the drawPoints method of column, that is able to handle simple // shapeArgs. Extend it by assigning the tooltip position. drawPoints: function () { var series = this, xAxis = series.xAxis, yAxis = series.yAxis, group = series.group, chart = series.chart, renderer = chart.renderer, scaleX, scaleY, translateX, translateY, baseTrans = this.baseTrans, transformGroup, startTranslateX, startTranslateY, startScaleX, startScaleY; // Set a group that handles transform during zooming and panning in // order to preserve clipping on series.group if (!series.transformGroup) { series.transformGroup = renderer.g() .attr({ scaleX: 1, scaleY: 1 }) .add(group); series.transformGroup.survive = true; } // Draw the shapes again if (series.doFullTranslate()) { // Individual point actions. if (chart.hasRendered && !chart.styledMode) { series.points.forEach(function (point) { // Restore state color on update/redraw (#3529) if (point.shapeArgs) { point.shapeArgs.fill = series.pointAttribs(point, point.state).fill; } }); } // Draw them in transformGroup series.group = series.transformGroup; seriesTypes.column.prototype.drawPoints.apply(series); series.group = group; // Reset // Add class names series.points.forEach(function (point) { if (point.graphic) { var className = ''; if (point.name) { className += 'highcharts-name-' + point.name.replace(/ /g, '-').toLowerCase(); } if (point.properties && point.properties['hc-key']) { className += ' highcharts-key-' + point.properties['hc-key'].toLowerCase(); } if (className) { point.graphic.addClass(className); } // In styled mode, apply point colors by CSS if (chart.styledMode) { point.graphic.css(series.pointAttribs(point, (point.selected && 'select'))); } } }); // Set the base for later scale-zooming. The originX and originY // properties are the axis values in the plot area's upper left // corner. this.baseTrans = { originX: (xAxis.min - xAxis.minPixelPadding / xAxis.transA), originY: (yAxis.min - yAxis.minPixelPadding / yAxis.transA + (yAxis.reversed ? 0 : yAxis.len / yAxis.transA)), transAX: xAxis.transA, transAY: yAxis.transA }; // Reset transformation in case we're doing a full translate // (#3789) this.transformGroup.animate({ translateX: 0, translateY: 0, scaleX: 1, scaleY: 1 }); // Just update the scale and transform for better performance } else { scaleX = xAxis.transA / baseTrans.transAX; scaleY = yAxis.transA / baseTrans.transAY; translateX = xAxis.toPixels(baseTrans.originX, true); translateY = yAxis.toPixels(baseTrans.originY, true); // Handle rounding errors in normal view (#3789) if (scaleX > 0.99 && scaleX < 1.01 && scaleY > 0.99 && scaleY < 1.01) { scaleX = 1; scaleY = 1; translateX = Math.round(translateX); translateY = Math.round(translateY); } /* Animate or move to the new zoom level. In order to prevent flickering as the different transform components are set out of sync (#5991), we run a fake animator attribute and set scale and translation synchronously in the same step. A possible improvement to the API would be to handle this in the renderer or animation engine itself, to ensure that when we are animating multiple properties, we make sure that each step for each property is performed in the same step. Also, for symbols and for transform properties, it should induce a single updateTransform and symbolAttr call. */ transformGroup = this.transformGroup; if (chart.renderer.globalAnimation) { startTranslateX = transformGroup.attr('translateX'); startTranslateY = transformGroup.attr('translateY'); startScaleX = transformGroup.attr('scaleX'); startScaleY = transformGroup.attr('scaleY'); transformGroup .attr({ animator: 0 }) .animate({ animator: 1 }, { step: function (now, fx) { transformGroup.attr({ translateX: (startTranslateX + (translateX - startTranslateX) * fx.pos), translateY: (startTranslateY + (translateY - startTranslateY) * fx.pos), scaleX: (startScaleX + (scaleX - startScaleX) * fx.pos), scaleY: (startScaleY + (scaleY - startScaleY) * fx.pos) }); } }); // When dragging, animation is off. } else { transformGroup.attr({ translateX: translateX, translateY: translateY, scaleX: scaleX, scaleY: scaleY }); } } /* Set the stroke-width directly on the group element so the children inherit it. We need to use setAttribute directly, because the stroke-widthSetter method expects a stroke color also to be set. */ if (!chart.styledMode) { group.element.setAttribute('stroke-width', (pick(series.options[(series.pointAttrToOptions && series.pointAttrToOptions['stroke-width']) || 'borderWidth'], 1 // Styled mode ) / (scaleX || 1))); } this.drawMapDataLabels(); }, // Draw the data labels. Special for maps is the time that the data // labels are drawn (after points), and the clipping of the // dataLabelsGroup. drawMapDataLabels: function () { Series.prototype.drawDataLabels.call(this); if (this.dataLabelsGroup) { this.dataLabelsGroup.clip(this.chart.clipRect); } }, // Override render to throw in an async call in IE8. Otherwise it chokes // on the US counties demo. render: function () { var series = this, render = Series.prototype.render; // Give IE8 some time to breathe. if (series.chart.renderer.isVML && series.data.length > 3000) { setTimeout(function () { render.call(series); }); } else { render.call(series); } }, // The initial animation for the map series. By default, animation is // disabled. Animation of map shapes is not at all supported in VML // browsers. animate: function (init) { var chart = this.chart, animation = this.options.animation, group = this.group, xAxis = this.xAxis, yAxis = this.yAxis, left = xAxis.pos, top = yAxis.pos; if (chart.renderer.isSVG) { if (animation === true) { animation = { duration: 1000 }; } // Initialize the animation if (init) { // Scale down the group and place it in the center group.attr({ translateX: left + xAxis.len / 2, translateY: top + yAxis.len / 2, scaleX: 0.001, scaleY: 0.001 }); // Run the animation } else { group.animate({ translateX: left, translateY: top, scaleX: 1, scaleY: 1 }, animation); // Delete this function to allow it only once this.animate = null; } } }, // Animate in the new series from the clicked point in the old series. // Depends on the drilldown.js module animateDrilldown: function (init) { var toBox = this.chart.plotBox, level = this.chart.drilldownLevels[this.chart.drilldownLevels.length - 1], fromBox = level.bBox, animationOptions = this.chart.options.drilldown.animation, scale; if (!init) { scale = Math.min(fromBox.width / toBox.width, fromBox.height / toBox.height); level.shapeArgs = { scaleX: scale, scaleY: scale, translateX: fromBox.x, translateY: fromBox.y }; this.points.forEach(function (point) { if (point.graphic) { point.graphic .attr(level.shapeArgs) .animate({ scaleX: 1, scaleY: 1, translateX: 0, translateY: 0 }, animationOptions); } }); this.animate = null; } }, drawLegendSymbol: LegendSymbolMixin.drawRectangle, // When drilling up, pull out the individual point graphics from the // lower series and animate them into the origin point in the upper // series. animateDrillupFrom: function (level) { seriesTypes.column.prototype .animateDrillupFrom.call(this, level); }, // When drilling up, keep the upper series invisible until the lower // series has moved into place animateDrillupTo: function (init) { seriesTypes.column.prototype .animateDrillupTo.call(this, init); } // Point class }), extend({ // Extend the Point object to split paths applyOptions: function (options, x) { var series = this.series, point = Point.prototype.applyOptions.call(this, options, x), joinBy = series.joinBy, mapPoint; if (series.mapData) { mapPoint = point[joinBy[1]] !== undefined && series.mapMap[point[joinBy[1]]]; if (mapPoint) { // This applies only to bubbles if (series.xyFromShape) { point.x = mapPoint._midX; point.y = mapPoint._midY; } extend(point, mapPoint); // copy over properties } else { point.value = point.value || null; } } return point; }, // Stop the fade-out onMouseOver: function (e) { H.clearTimeout(this.colorInterval); if (this.value !== null || this.series.options.nullInteraction) { Point.prototype.onMouseOver.call(this, e); } else { // #3401 Tooltip doesn't hide when hovering over null points this.series.onMouseOut(e); } }, // eslint-disable-next-line valid-jsdoc /** * Highmaps only. Zoom in on the point using the global animation. * * @sample maps/members/point-zoomto/ * Zoom to points from butons * * @requires module:modules/map * * @function Highcharts.Point#zoomTo */ zoomTo: function () { var point = this, series = point.series; series.xAxis.setExtremes(point._minX, point._maxX, false); series.yAxis.setExtremes(point._minY, point._maxY, false); series.chart.redraw(); } }, colorPointMixin)); /** * A map data object containing a `path` definition and optionally additional * properties to join in the data as per the `joinBy` option. * * @sample maps/demo/category-map/ * Map data and joinBy * * @type {Array<Highcharts.SeriesMapDataOptions>|*} * @product highmaps * @apioption series.mapData */ /** * A `map` series. If the [type](#series.map.type) option is not specified, it * is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.map * @excluding dataParser, dataURL, marker * @product highmaps * @apioption series.map */ /** * An array of data points for the series. For the `map` series type, points can * be given in the following ways: * * 1. An array of numerical values. In this case, the numerical values will be * interpreted as `value` options. Example: * ```js * data: [0, 5, 3, 5] * ``` * * 2. An array of arrays with 2 values. In this case, the values correspond to * `[hc-key, value]`. Example: * ```js * data: [ * ['us-ny', 0], * ['us-mi', 5], * ['us-tx', 3], * ['us-ak', 5] * ] * ``` * * 3. An array of objects with named values. The following snippet shows only a * few settings, see the complete options set below. If the total number of * data points exceeds the series' * [turboThreshold](#series.map.turboThreshold), * this option is not available. * ```js * data: [{ * value: 6, * name: "Point2", * color: "#00FF00" * }, { * value: 6, * name: "Point1", * color: "#FF00FF" * }] * ``` * * @type {Array<number|Array<string,(number|null)>|null|*>} * @product highmaps * @apioption series.map.data */ /** * Individual color for the point. By default the color is either used * to denote the value, or pulled from the global `colors` array. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @product highmaps * @apioption series.map.data.color */ /** * Individual data label for each point. The options are the same as * the ones for [plotOptions.series.dataLabels]( * #plotOptions.series.dataLabels). * * @sample maps/series/data-datalabels/ * Disable data labels for individual areas * * @type {Highcharts.DataLabelsOptionsObject} * @product highmaps * @apioption series.map.data.dataLabels */ /** * The `id` of a series in the [drilldown.series](#drilldown.series) * array to use for a drilldown for this point. * * @sample maps/demo/map-drilldown/ * Basic drilldown * * @type {string} * @product highmaps * @apioption series.map.data.drilldown */ /** * An id for the point. This can be used after render time to get a * pointer to the point object through `chart.get()`. * * @sample maps/series/data-id/ * Highlight a point by id * * @type {string} * @product highmaps * @apioption series.map.data.id */ /** * When data labels are laid out on a map, Highmaps runs a simplified * algorithm to detect collision. When two labels collide, the one with * the lowest rank is hidden. By default the rank is computed from the * area. * * @type {number} * @product highmaps * @apioption series.map.data.labelrank */ /** * The relative mid point of an area, used to place the data label. * Ranges from 0 to 1\. When `mapData` is used, middleX can be defined * there. * * @type {number} * @default 0.5 * @product highmaps * @apioption series.map.data.middleX */ /** * The relative mid point of an area, used to place the data label. * Ranges from 0 to 1\. When `mapData` is used, middleY can be defined * there. * * @type {number} * @default 0.5 * @product highmaps * @apioption series.map.data.middleY */ /** * The name of the point as shown in the legend, tooltip, dataLabel * etc. * * @sample maps/series/data-datalabels/ * Point names * * @type {string} * @product highmaps * @apioption series.map.data.name */ /** * For map and mapline series types, the SVG path for the shape. For * compatibily with old IE, not all SVG path definitions are supported, * but M, L and C operators are safe. * * To achieve a better separation between the structure and the data, * it is recommended to use `mapData` to define that paths instead * of defining them on the data points themselves. * * @sample maps/series/data-path/ * Paths defined in data * * @type {string} * @product highmaps * @apioption series.map.data.path */ /** * The numeric value of the data point. * * @type {number|null} * @product highmaps * @apioption series.map.data.value */ /** * Individual point events * * @extends plotOptions.series.point.events * @product highmaps * @apioption series.map.data.events */ ''; // adds doclets above to the transpiled file
/* ======================================================================== * Bootstrap: carousel.js v3.3.7 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = null this.sliding = null this.interval = null this.$active = null this.$items = null this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this)) this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element .on('mouseenter.bs.carousel', $.proxy(this.pause, this)) .on('mouseleave.bs.carousel', $.proxy(this.cycle, this)) } Carousel.VERSION = '3.3.7' Carousel.TRANSITION_DURATION = 600 Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true, keyboard: true } Carousel.prototype.keydown = function (e) { if (/input|textarea/i.test(e.target.tagName)) return switch (e.which) { case 37: this.prev(); break case 39: this.next(); break default: return } e.preventDefault() } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getItemIndex = function (item) { this.$items = item.parent().children('.item') return this.$items.index(item || this.$active) } Carousel.prototype.getItemForDirection = function (direction, active) { var activeIndex = this.getItemIndex(active) var willWrap = (direction == 'prev' && activeIndex === 0) || (direction == 'next' && activeIndex == (this.$items.length - 1)) if (willWrap && !this.options.wrap) return active var delta = direction == 'prev' ? -1 : 1 var itemIndex = (activeIndex + delta) % this.$items.length return this.$items.eq(itemIndex) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active')) if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid" if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos)) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || this.getItemForDirection(type, $active) var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var that = this if ($next.hasClass('active')) return (this.sliding = false) var relatedTarget = $next[0] var slideEvent = $.Event('slide.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) this.$element.trigger(slideEvent) if (slideEvent.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]) $nextIndicator && $nextIndicator.addClass('active') } var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid" if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one('bsTransitionEnd', function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger(slidEvent) }, 0) }) .emulateTransitionEnd(Carousel.TRANSITION_DURATION) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger(slidEvent) } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } var old = $.fn.carousel $.fn.carousel = Plugin $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= var clickHandler = function (e) { var href var $this = $(this) var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7 if (!$target.hasClass('carousel')) return var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false Plugin.call($target, options) if (slideIndex) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() } $(document) .on('click.bs.carousel.data-api', '[data-slide]', clickHandler) .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) Plugin.call($carousel, $carousel.data()) }) }) }(jQuery);
import * as ActionTypes from '../constants/constants'; const initialState = { posts: [], selectedPost: null }; const postReducer = (state = initialState, action) => { switch (action.type) { case ActionTypes.ADD_POST : return { posts: [{ name: action.name, title: action.title, content: action.content, slug: action.slug, cuid: action.cuid, _id: action._id, }, ...state.posts], post: state.post }; case ActionTypes.CHANGE_SELECTED_POST : return { posts: state.posts, post: action.slug, }; case ActionTypes.ADD_POSTS : return { posts: action.posts, post: state.post, }; case ActionTypes.ADD_SELECTED_POST : return { post: action.post, posts: state.posts, }; case ActionTypes.DELETE_POST : return { posts: state.posts.filter((post) => post._id !== action.post._id), }; default: return state; } }; export default postReducer;
var parseXlsx = require('excel'), Server = require( './src/server' ), Client = require( './src/client' ), Row = require( './src/row' ); var Runner = function() { this._serverReady = false; this._parsedSpec = null; this._isRunning = false; this._currentRow = null; this._currentRowIndex = 0; this._portA = 6014; this._portB = 6015; this._maxEntrySizes = []; this._serverA = new Server( this._portA ); this._serverA.on( 'ready', this._checkReady.bind( this ) ); this._serverB = new Server( this._portB ); this._serverB.on( 'ready', this._checkReady.bind( this ) ); parseXlsx('Protocoll.xlsx', this._onSpec.bind( this ) ); }; Runner.prototype._calculateMaxEntrySizes = function() { var i, j; for( i = 0; i < this._parsedSpec.length; i++ ) { for( j = 0; j < this._parsedSpec[ i ].length; j++ ) { if( this._maxEntrySizes[ j ] === undefined ) { this._maxEntrySizes[ j ] = 0; } if( this._parsedSpec[ i ][ j ].length > this._maxEntrySizes[ j ] ) { this._maxEntrySizes[ j ] = this._parsedSpec[ i ][ j ].length; } } } }; Runner.prototype._run = function() { if( this._currentRowIndex >= this._parsedSpec.length ) { this._done(); return; } var rowData = this._parsedSpec[ this._currentRowIndex ], clients = [ this._clientA1, this._clientA2, this._clientB1 ]; this._currentRow = new Row( rowData, clients ); this._currentRow.once( 'done', this._processResult.bind( this ) ); }; Runner.prototype._processResult = function() { this._currentRow.log( this._maxEntrySizes ); if( this._currentRow.isValid() ) { this._currentRowIndex++; this._clientA1.reset(); this._clientA2.reset(); this._clientB1.reset(); this._run(); } else { this._failed(); } }; Runner.prototype._failed = function() { console.log( '------ TESTS FAILED ------'.red ); process.exit(); }; Runner.prototype._done = function() { console.log( '------ TEST SUCCESFUL ------'.green ); process.exit(); }; Runner.prototype._checkReady = function() { if( this._serverA.isReady && this._serverB.isReady && this._serverReady === false ) { this._serverReady = true; this._startClients(); } if( this._serverReady === false ) { return; } if( this._clientA1.isReady && this._clientA2.isReady && this._clientB1.isReady && this._parsedSpec && this._isRunning === false ) { this._isRunning = true; this._calculateMaxEntrySizes(); this._run(); } }; Runner.prototype._startClients = function() { this._clientA1 = new Client( this._portA ); this._clientA1.on( 'ready', this._checkReady.bind( this ) ); this._clientA2 = new Client( this._portA ); this._clientA2.on( 'ready', this._checkReady.bind( this ) ); this._clientB1 = new Client( this._portB ); this._clientB1.on( 'ready', this._checkReady.bind( this ) ); }; Runner.prototype._onSpec = function( error, data ) { if( error !== null ) { throw error; } var validRows = []; for( var i = 0; i < data.length; i++ ) { if( data[ i ].join( '' ).trim().length > 0 ) { validRows.push( data[ i ] ); } } this._parsedSpec = validRows; }; new Runner();
Package.describe({ name: 'standard-minifier-css', version: '1.1.8', summary: 'Standard css minifier used with Meteor apps by default. [Custom]', documentation: 'README.md' }); Package.registerBuildPlugin({ name: "minifyStdCSS", use: [ 'minifier-css' ], npmDependencies: { "source-map": "0.5.3" }, sources: [ 'plugin/minify-css.js' ] }); Package.onUse(function(api) { api.use('isobuild:minifier-plugin@1.0.0'); }); Package.onTest(function(api) { });
/** * @license * v1.2.9 * MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE) * Copyright (c) 2019 Microsoft * docs: https://pnp.github.io/pnpjs/ * source: https://github.com/pnp/pnpjs * bugs: https://github.com/pnp/pnpjs/issues */ import { ClientSvcQueryable, MethodParams, property, setProperty, method, objConstructor, objectPath, objectProperties, opQuery, ObjectPathBatch, staticMethod } from '@pnp/sp-clientsvc'; import { stringIsNullOrEmpty, extend, sanitizeGuid, getGUID, objectDefinedNotNull } from '@pnp/common'; import { sp } from '@pnp/sp'; /** * Represents a collection of labels */ class Labels extends ClientSvcQueryable { constructor(parent = "", _objectPaths = null) { super(parent, _objectPaths); this._objectPaths.add(property("Labels")); } /** * Gets a label from the collection by its value * * @param value The value to retrieve */ getByValue(value) { const params = MethodParams.build().string(value); return this.getChild(Label, "GetByValue", params); } /** * Loads the data and merges with with the ILabel instances */ get() { return this.sendGetCollection((d) => { if (!stringIsNullOrEmpty(d.Value)) { return this.getByValue(d.Value); } throw Error("Could not find Value in Labels.get(). You must include at least one of these in your select fields."); }); } } /** * Represents a label instance */ class Label extends ClientSvcQueryable { /** * Gets the data for this Label */ get() { return this.sendGet(Label); } /** * Sets this label as the default */ setAsDefaultForLanguage() { return this.invokeNonQuery("SetAsDefaultForLanguage"); } /** * Deletes this label */ delete() { return this.invokeNonQuery("DeleteObject"); } } class Terms extends ClientSvcQueryable { /** * Gets the terms in this collection */ get() { return this.sendGetCollection((d) => { if (!stringIsNullOrEmpty(d.Name)) { return this.getByName(d.Name); } else if (!stringIsNullOrEmpty(d.Id)) { return this.getById(d.Id); } throw Error("Could not find Name or Id in Terms.get(). You must include at least one of these in your select fields."); }); } /** * Gets a term by id * * @param id The id of the term */ getById(id) { const params = MethodParams.build() .string(sanitizeGuid(id)); return this.getChild(Term, "GetById", params); } /** * Gets a term by name * * @param name Term name */ getByName(name) { const params = MethodParams.build() .string(name); return this.getChild(Term, "GetByName", params); } } /** * Represents the operations available on a given term */ class Term extends ClientSvcQueryable { addTerm(name, lcid, isAvailableForTagging = true, id = getGUID()) { const params = MethodParams.build() .string(name) .number(lcid) .string(sanitizeGuid(id)); this._useCaching = false; return this.invokeMethod("CreateTerm", params, setProperty("IsAvailableForTagging", "Boolean", `${isAvailableForTagging}`)) .then(r => extend(this.termSet.getTermById(r.Id), r)); } get terms() { return this.getChildProperty(Terms, "Terms"); } get labels() { return new Labels(this); } get parent() { return this.getChildProperty(Term, "Parent"); } get pinSourceTermSet() { return this.getChildProperty(TermSet, "PinSourceTermSet"); } get reusedTerms() { return this.getChildProperty(Terms, "ReusedTerms"); } get sourceTerm() { return this.getChildProperty(Term, "SourceTerm"); } get termSet() { return this.getChildProperty(TermSet, "TermSet"); } get termSets() { return this.getChildProperty(TermSets, "TermSets"); } /** * Creates a new label for this Term * * @param name label value * @param lcid language code * @param isDefault Is the default label */ createLabel(name, lcid, isDefault = false) { const params = MethodParams.build() .string(name) .number(lcid) .boolean(isDefault); this._useCaching = false; return this.invokeMethod("CreateLabel", params) .then(r => extend(this.labels.getByValue(name), r)); } /** * Sets the deprecation flag on a term * * @param doDeprecate New value for the deprecation flag */ deprecate(doDeprecate) { const params = MethodParams.build().boolean(doDeprecate); return this.invokeNonQuery("Deprecate", params); } /** * Loads the term data */ get() { return this.sendGet(Term); } /** * Gets the appropriate description for a term * * @param lcid Language code */ getDescription(lcid) { const params = MethodParams.build().number(lcid); return this.invokeMethodAction("GetDescription", params); } /** * Sets the description * * @param description Term description * @param lcid Language code */ setDescription(description, lcid) { const params = MethodParams.build().string(description).number(lcid); return this.invokeNonQuery("SetDescription", params); } /** * Sets a custom property on this term * * @param name Property name * @param value Property value */ setLocalCustomProperty(name, value) { const params = MethodParams.build().string(name).string(value); return this.invokeNonQuery("SetLocalCustomProperty", params); } /** * Updates the specified properties of this term, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ update(properties) { return this.invokeUpdate(properties, Term); } } class TermSets extends ClientSvcQueryable { /** * Gets the termsets in this collection */ get() { return this.sendGetCollection((d) => { if (!stringIsNullOrEmpty(d.Name)) { return this.getByName(d.Name); } else if (!stringIsNullOrEmpty(d.Id)) { return this.getById(d.Id); } throw Error("Could not find Value in Labels.get(). You must include at least one of these in your select fields."); }); } /** * Gets a TermSet from this collection by id * * @param id TermSet id */ getById(id) { const params = MethodParams.build() .string(sanitizeGuid(id)); return this.getChild(TermSet, "GetById", params); } /** * Gets a TermSet from this collection by name * * @param name TermSet name */ getByName(name) { const params = MethodParams.build() .string(name); return this.getChild(TermSet, "GetByName", params); } } class TermSet extends ClientSvcQueryable { /** * Gets the group containing this Term set */ get group() { return this.getChildProperty(TermGroup, "Group"); } /** * Access all the terms in this termset */ get terms() { return this.getChild(Terms, "GetAllTerms", null); } /** * Adds a stakeholder to the TermSet * * @param stakeholderName The login name of the user to be added as a stakeholder */ addStakeholder(stakeholderName) { const params = MethodParams.build() .string(stakeholderName); return this.invokeNonQuery("DeleteStakeholder", params); } /** * Deletes a stakeholder to the TermSet * * @param stakeholderName The login name of the user to be added as a stakeholder */ deleteStakeholder(stakeholderName) { const params = MethodParams.build() .string(stakeholderName); return this.invokeNonQuery("AddStakeholder", params); } /** * Gets the data for this TermSet */ get() { return this.sendGet(TermSet); } /** * Get a term by id * * @param id Term id */ getTermById(id) { const params = MethodParams.build() .string(sanitizeGuid(id)); return this.getChild(Term, "GetTerm", params); } /** * Adds a term to this term set * * @param name Name for the term * @param lcid Language code * @param isAvailableForTagging set tagging availability (default: true) * @param id GUID id for the term (optional) */ addTerm(name, lcid, isAvailableForTagging = true, id = getGUID()) { const params = MethodParams.build() .string(name) .number(lcid) .string(sanitizeGuid(id)); this._useCaching = false; return this.invokeMethod("CreateTerm", params, setProperty("IsAvailableForTagging", "Boolean", `${isAvailableForTagging}`)) .then(r => extend(this.getTermById(r.Id), r)); } /** * Copies this term set immediately */ copy() { return this.invokeMethod("Copy", null); } /** * Updates the specified properties of this term set, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ update(properties) { return this.invokeUpdate(properties, TermSet); } } /** * Term Groups collection in Term Store */ class TermGroups extends ClientSvcQueryable { /** * Gets the groups in this collection */ get() { return this.sendGetCollection((d) => { if (!stringIsNullOrEmpty(d.Name)) { return this.getByName(d.Name); } else if (!stringIsNullOrEmpty(d.Id)) { return this.getById(d.Id); } throw Error("Could not find Name or Id in TermGroups.get(). You must include at least one of these in your select fields."); }); } /** * Gets a TermGroup from this collection by id * * @param id TermGroup id */ getById(id) { const params = MethodParams.build() .string(sanitizeGuid(id)); return this.getChild(TermGroup, "GetById", params); } /** * Gets a TermGroup from this collection by name * * @param name TErmGroup name */ getByName(name) { const params = MethodParams.build() .string(name); return this.getChild(TermGroup, "GetByName", params); } } /** * Represents a group in the taxonomy heirarchy */ class TermGroup extends ClientSvcQueryable { constructor(parent = "", _objectPaths) { super(parent, _objectPaths); // this should mostly be true this.store = parent instanceof TermStore ? parent : null; } /** * Gets the collection of term sets in this group */ get termSets() { return this.getChildProperty(TermSets, "TermSets"); } /** * Adds a contributor to the Group * * @param principalName The login name of the user to be added as a contributor */ addContributor(principalName) { const params = MethodParams.build().string(principalName); return this.invokeNonQuery("AddContributor", params); } /** * Adds a group manager to the Group * * @param principalName The login name of the user to be added as a group manager */ addGroupManager(principalName) { const params = MethodParams.build().string(principalName); return this.invokeNonQuery("AddGroupManager", params); } /** * Creates a new TermSet in this Group using the provided language and unique identifier * * @param name The name of the new TermSet being created * @param lcid The language that the new TermSet name is in * @param id The unique identifier of the new TermSet being created (optional) */ createTermSet(name, lcid, id = getGUID()) { const params = MethodParams.build() .string(name) .string(sanitizeGuid(id)) .number(lcid); this._useCaching = false; return this.invokeMethod("CreateTermSet", params) .then(r => extend(this.store.getTermSetById(r.Id), r)); } /** * Gets this term store's data */ get() { return this.sendGet(TermGroup); } /** * Updates the specified properties of this term set, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ update(properties) { return this.invokeUpdate(properties, TermGroup); } } /** * Represents the set of available term stores and the collection methods */ class TermStores extends ClientSvcQueryable { constructor(parent = "") { super(parent); this._objectPaths.add(property("TermStores", // actions objectPath())); } /** * Gets the term stores */ get() { return this.sendGetCollection((d) => { if (!stringIsNullOrEmpty(d.Name)) { return this.getByName(d.Name); } else if (!stringIsNullOrEmpty(d.Id)) { return this.getById(d.Id); } throw Error("Could not find Name or Id in TermStores.get(). You must include at least one of these in your select fields."); }); } /** * Returns the TermStore specified by its index name * * @param name The index name of the TermStore to be returned */ getByName(name) { return this.getChild(TermStore, "GetByName", MethodParams.build().string(name)); } /** * Returns the TermStore specified by its GUID index * * @param id The GUID index of the TermStore to be returned */ getById(id) { return this.getChild(TermStore, "GetById", MethodParams.build().string(sanitizeGuid(id))); } } class TermStore extends ClientSvcQueryable { constructor(parent = "", _objectPaths = null) { super(parent, _objectPaths); } get hashTagsTermSet() { return this.getChildProperty(TermSet, "HashTagsTermSet"); } get keywordsTermSet() { return this.getChildProperty(TermSet, "KeywordsTermSet"); } get orphanedTermsTermSet() { return this.getChildProperty(TermSet, "OrphanedTermsTermSet"); } get systemGroup() { return this.getChildProperty(TermGroup, "SystemGroup"); } get groups() { return this.getChildProperty(TermGroups, "Groups"); } /** * Gets the term store data */ get() { return this.sendGet(TermStore); } /** * Gets term sets * * @param name * @param lcid */ getTermSetsByName(name, lcid) { const params = MethodParams.build() .string(name) .number(lcid); return this.getChild(TermSets, "GetTermSetsByName", params); } /** * Provides access to an ITermSet by id * * @param id */ getTermSetById(id) { const params = MethodParams.build().string(sanitizeGuid(id)); return this.getChild(TermSet, "GetTermSet", params); } /** * Provides access to an ITermSet by id * * @param id */ getTermById(id) { const params = MethodParams.build().string(sanitizeGuid(id)); return this.getChild(Term, "GetTerm", params); } /** * Provides access to an ITermSet by id * * @param id */ getTermsById(...ids) { const params = MethodParams.build().strArray(ids.map(id => sanitizeGuid(id))); return this.getChild(Terms, "GetTermsById", params); } /** * Gets a term from a term set based on the supplied ids * * @param termId Term Id * @param termSetId Termset Id */ getTermInTermSet(termId, termSetId) { const params = MethodParams.build().string(sanitizeGuid(termId)).string(sanitizeGuid(termSetId)); return this.getChild(Term, "GetTermInTermSet", params); } /** * This method provides access to a ITermGroup by id * * @param id The group id */ getTermGroupById(id) { const params = MethodParams.build() .string(sanitizeGuid(id)); return this.getChild(TermGroup, "GetGroup", params); } /** * Gets the terms by the supplied information (see: https://msdn.microsoft.com/en-us/library/hh626704%28v=office.12%29.aspx) * * @param info */ getTerms(info) { const objectPaths = this._objectPaths.copy(); // this will be the parent of the GetTerms call, but we need to create the input param first const parentIndex = objectPaths.lastIndex; // this is our input object const input = objConstructor("{61a1d689-2744-4ea3-a88b-c95bee9803aa}", // actions objectPath(), ...objectProperties(info)); // add the input object path const inputIndex = objectPaths.add(input); // this sets up the GetTerms call const params = MethodParams.build().objectPath(inputIndex); // call the method const methodIndex = objectPaths.add(method("GetTerms", params, // actions objectPath())); // setup the parent relationship even though they are seperated in the collection objectPaths.addChildRelationship(parentIndex, methodIndex); return new Terms(this, objectPaths); } /** * Gets the site collection group associated with the current site * * @param createIfMissing If true the group will be created, otherwise null (default: false) */ getSiteCollectionGroup(createIfMissing = false) { const objectPaths = this._objectPaths.copy(); const methodParent = objectPaths.lastIndex; const siteIndex = objectPaths.siteIndex; const params = MethodParams.build().objectPath(siteIndex).boolean(createIfMissing); const methodIndex = objectPaths.add(method("GetSiteCollectionGroup", params, // actions objectPath())); // the parent of this method call is this instance, not the current/site objectPaths.addChildRelationship(methodParent, methodIndex); return new TermGroup(this, objectPaths); } /** * Adds a working language to the TermStore * * @param lcid The locale identifier of the working language to add */ addLanguage(lcid) { const params = MethodParams.build().number(lcid); return this.invokeNonQuery("AddLanguage", params); } /** * Creates a new Group in this TermStore * * @param name The name of the new Group being created * @param id The ID (Guid) that the new group should have */ addGroup(name, id = getGUID()) { const params = MethodParams.build() .string(name) .string(sanitizeGuid(id)); this._useCaching = false; return this.invokeMethod("CreateGroup", params) .then(r => extend(this.getTermGroupById(r.Id), r)); } /** * Commits all updates to the database that have occurred since the last commit or rollback */ commitAll() { return this.invokeNonQuery("CommitAll"); } /** * Delete a working language from the TermStore * * @param lcid locale ID for the language to be deleted */ deleteLanguage(lcid) { const params = MethodParams.build().number(lcid); return this.invokeNonQuery("DeleteLanguage", params); } /** * Discards all updates that have occurred since the last commit or rollback */ rollbackAll() { return this.invokeNonQuery("RollbackAll"); } /** * Updates the cache */ updateCache() { return this.invokeNonQuery("UpdateCache"); } /** * Updates the specified properties of this term set, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ update(properties) { return this.invokeUpdate(properties, TermStore); } /** * This method makes sure that this instance is aware of all child terms that are used in the current site collection */ updateUsedTermsOnSite() { const objectPaths = this._objectPaths.copy(); const methodParent = objectPaths.lastIndex; const siteIndex = objectPaths.siteIndex; const params = MethodParams.build().objectPath(siteIndex); const methodIndex = objectPaths.add(method("UpdateUsedTermsOnSite", params)); // the parent of this method call is this instance, not the current context/site objectPaths.addChildRelationship(methodParent, methodIndex); return this.send(objectPaths); } /** * Gets a list of changes * * @param info Lookup information */ getChanges(info) { const objectPaths = this._objectPaths.copy(); const methodParent = objectPaths.lastIndex; const inputIndex = objectPaths.add(objConstructor("{1f849fb0-4fcb-4a54-9b01-9152b9e482d3}", // actions objectPath(), ...objectProperties(info))); const params = MethodParams.build().objectPath(inputIndex); const methodIndex = objectPaths.add(method("GetChanges", params, // actions objectPath(), opQuery([], this.getSelects()))); objectPaths.addChildRelationship(methodParent, methodIndex); return this.send(objectPaths); } } /** * The root taxonomy object */ class Session extends ClientSvcQueryable { constructor(webUrl = "") { super(webUrl); // everything starts with the session this._objectPaths.add(staticMethod("GetTaxonomySession", "{981cbc68-9edc-4f8d-872f-71146fcbb84f}", // actions objectPath())); } /** * The collection of term stores */ get termStores() { return new TermStores(this); } /** * Provides access to sp.setup from @pnp/sp * * @param config Configuration */ setup(config) { sp.setup(config); } /** * Creates a new batch */ createBatch() { return new ObjectPathBatch(this.toUrl()); } /** * Gets the default keyword termstore for this session */ getDefaultKeywordTermStore() { return this.getChild(TermStore, "GetDefaultKeywordsTermStore", null); } /** * Gets the default site collection termstore for this session */ getDefaultSiteCollectionTermStore() { return this.getChild(TermStore, "GetDefaultSiteCollectionTermStore", null); } } var StringMatchOption; (function (StringMatchOption) { StringMatchOption[StringMatchOption["StartsWith"] = 0] = "StartsWith"; StringMatchOption[StringMatchOption["ExactMatch"] = 1] = "ExactMatch"; })(StringMatchOption || (StringMatchOption = {})); var ChangedItemType; (function (ChangedItemType) { ChangedItemType[ChangedItemType["Unknown"] = 0] = "Unknown"; ChangedItemType[ChangedItemType["Term"] = 1] = "Term"; ChangedItemType[ChangedItemType["TermSet"] = 2] = "TermSet"; ChangedItemType[ChangedItemType["Group"] = 3] = "Group"; ChangedItemType[ChangedItemType["TermStore"] = 4] = "TermStore"; ChangedItemType[ChangedItemType["Site"] = 5] = "Site"; })(ChangedItemType || (ChangedItemType = {})); var ChangedOperationType; (function (ChangedOperationType) { ChangedOperationType[ChangedOperationType["Unknown"] = 0] = "Unknown"; ChangedOperationType[ChangedOperationType["Add"] = 1] = "Add"; ChangedOperationType[ChangedOperationType["Edit"] = 2] = "Edit"; ChangedOperationType[ChangedOperationType["DeleteObject"] = 3] = "DeleteObject"; ChangedOperationType[ChangedOperationType["Move"] = 4] = "Move"; ChangedOperationType[ChangedOperationType["Copy"] = 5] = "Copy"; ChangedOperationType[ChangedOperationType["PathChange"] = 6] = "PathChange"; ChangedOperationType[ChangedOperationType["Merge"] = 7] = "Merge"; ChangedOperationType[ChangedOperationType["ImportObject"] = 8] = "ImportObject"; ChangedOperationType[ChangedOperationType["Restore"] = 9] = "Restore"; })(ChangedOperationType || (ChangedOperationType = {})); function setItemMetaDataField(item, fieldName, term) { if (!objectDefinedNotNull(term)) { return Promise.resolve(null); } const postData = {}; postData[fieldName] = { "Label": term.Name, "TermGuid": sanitizeGuid(term.Id), "WssId": "-1", "__metadata": { "type": "SP.Taxonomy.TaxonomyFieldValue" }, }; return item.update(postData); } function setItemMetaDataMultiField(item, fieldName, ...terms) { if (terms.length < 1) { return Promise.resolve(null); } return item.list.fields.getByTitle(`${fieldName}_0`).select("InternalName").get().then(i => { const postData = {}; postData[i.InternalName] = terms.map(term => `-1;#${term.Name}|${sanitizeGuid(term.Id)};#`).join(""); return item.update(postData); }); } // export an existing session instance const taxonomy = new Session(); export { taxonomy, Labels, Label, Session, TermGroups, TermGroup, Terms, Term, TermSets, TermSet, TermStores, TermStore, StringMatchOption, ChangedItemType, ChangedOperationType, setItemMetaDataField, setItemMetaDataMultiField }; //# sourceMappingURL=sp-taxonomy.js.map
/* eslint-disable */ const Gatsby = require(`gatsby`); export const query = graphql` query { allSitePages { prefix } } `;
var get = Ember.get, forEach = Ember.EnumerableUtils.forEach, RETAIN = 'r', FILTER = 'f'; function Operation (type, count) { this.type = type; this.count = count; } /** An `Ember.SubArray` tracks an array in a way similar to, but more specialized than, `Ember.TrackedArray`. It is useful for keeping track of the indexes of items within a filtered array. @class SubArray @namespace Ember */ Ember.SubArray = function (length) { if (arguments.length < 1) { length = 0; } if (length > 0) { this._operations = [new Operation(RETAIN, length)]; } else { this._operations = []; } }; Ember.SubArray.prototype = { /** Track that an item was added to the tracked array. @method addItem @param {number} index The index of the item in the tracked array. @param {boolean} match `true` iff the item is included in the subarray. @return {number} The index of the item in the subarray. */ addItem: function(index, match) { var returnValue = -1, itemType = match ? RETAIN : FILTER, self = this; this._findOperation(index, function(operation, operationIndex, rangeStart, rangeEnd, seenInSubArray) { var newOperation, splitOperation; if (itemType === operation.type) { ++operation.count; } else if (index === rangeStart) { // insert to the left of `operation` self._operations.splice(operationIndex, 0, new Operation(itemType, 1)); } else { newOperation = new Operation(itemType, 1); splitOperation = new Operation(operation.type, rangeEnd - index + 1); operation.count = index - rangeStart; self._operations.splice(operationIndex + 1, 0, newOperation, splitOperation); } if (match) { if (operation.type === RETAIN) { returnValue = seenInSubArray + (index - rangeStart); } else { returnValue = seenInSubArray; } } self._composeAt(operationIndex); }, function(seenInSubArray) { self._operations.push(new Operation(itemType, 1)); if (match) { returnValue = seenInSubArray; } self._composeAt(self._operations.length-1); }); return returnValue; }, /** Track that an item was removed from the tracked array. @method removeItem @param {number} index The index of the item in the tracked array. @return {number} The index of the item in the subarray, or `-1` if the item was not in the subarray. */ removeItem: function(index) { var returnValue = -1, self = this; this._findOperation(index, function (operation, operationIndex, rangeStart, rangeEnd, seenInSubArray) { if (operation.type === RETAIN) { returnValue = seenInSubArray + (index - rangeStart); } if (operation.count > 1) { --operation.count; } else { self._operations.splice(operationIndex, 1); self._composeAt(operationIndex); } }, function() { throw new Ember.Error("Can't remove an item that has never been added."); }); return returnValue; }, _findOperation: function (index, foundCallback, notFoundCallback) { var operationIndex, len, operation, rangeStart, rangeEnd, seenInSubArray = 0; // OPTIMIZE: change to balanced tree // find leftmost operation to the right of `index` for (operationIndex = rangeStart = 0, len = this._operations.length; operationIndex < len; rangeStart = rangeEnd + 1, ++operationIndex) { operation = this._operations[operationIndex]; rangeEnd = rangeStart + operation.count - 1; if (index >= rangeStart && index <= rangeEnd) { foundCallback(operation, operationIndex, rangeStart, rangeEnd, seenInSubArray); return; } else if (operation.type === RETAIN) { seenInSubArray += operation.count; } } notFoundCallback(seenInSubArray); }, _composeAt: function(index) { var op = this._operations[index], otherOp; if (!op) { // Composing out of bounds is a no-op, as when removing the last operation // in the list. return; } if (index > 0) { otherOp = this._operations[index-1]; if (otherOp.type === op.type) { op.count += otherOp.count; this._operations.splice(index-1, 1); --index; } } if (index < this._operations.length-1) { otherOp = this._operations[index+1]; if (otherOp.type === op.type) { op.count += otherOp.count; this._operations.splice(index+1, 1); } } }, toString: function () { var str = ""; forEach(this._operations, function (operation) { str += " " + operation.type + ":" + operation.count; }); return str.substring(1); } };
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const msRest = require('ms-rest'); const msRestAzure = require('ms-rest-azure'); const WebResource = msRest.WebResource; /** * Fetches the result of any operation on the container. * * @param {string} vaultName The name of the recovery services vault. * * @param {string} resourceGroupName The name of the resource group where the * recovery services vault is present. * * @param {string} fabricName Fabric name associated with the container. * * @param {string} containerName Container name whose information should be * fetched. * * @param {string} operationId Operation ID which represents the operation * whose result needs to be fetched. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback - The callback. * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainerResource} for more * information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ function _get(vaultName, resourceGroupName, fabricName, containerName, operationId, options, callback) { /* jshint validthis: true */ let client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } let apiVersion = '2016-12-01'; // Validate try { if (vaultName === null || vaultName === undefined || typeof vaultName.valueOf() !== 'string') { throw new Error('vaultName cannot be null or undefined and it must be of type string.'); } if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') { throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.'); } if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') { throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.'); } if (fabricName === null || fabricName === undefined || typeof fabricName.valueOf() !== 'string') { throw new Error('fabricName cannot be null or undefined and it must be of type string.'); } if (containerName === null || containerName === undefined || typeof containerName.valueOf() !== 'string') { throw new Error('containerName cannot be null or undefined and it must be of type string.'); } if (operationId === null || operationId === undefined || typeof operationId.valueOf() !== 'string') { throw new Error('operationId cannot be null or undefined and it must be of type string.'); } if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL let baseUrl = this.client.baseUri; let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/operationResults/{operationId}'; requestUrl = requestUrl.replace('{vaultName}', encodeURIComponent(vaultName)); requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName)); requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId)); requestUrl = requestUrl.replace('{fabricName}', encodeURIComponent(fabricName)); requestUrl = requestUrl.replace('{containerName}', encodeURIComponent(containerName)); requestUrl = requestUrl.replace('{operationId}', encodeURIComponent(operationId)); let queryParameters = []; queryParameters.push('api-version=' + encodeURIComponent(apiVersion)); if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects let httpRequest = new WebResource(); httpRequest.method = 'GET'; httpRequest.url = requestUrl; httpRequest.headers = {}; // Set Headers httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(let headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.body = null; // Send Request return client.pipeline(httpRequest, (err, response, responseBody) => { if (err) { return callback(err); } let statusCode = response.statusCode; if (statusCode !== 200 && statusCode !== 202 && statusCode !== 204) { let error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; let parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { let resultMapper = new client.models['CloudError']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` + `- "${responseBody}" for the default response.`; return callback(error); } return callback(error); } // Create Result let result = null; if (responseBody === '') responseBody = null; // Deserialize Response if (statusCode === 200) { let parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { let resultMapper = new client.models['ProtectionContainerResource']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } } return callback(null, result, httpRequest, response); }); } /** Class representing a ProtectionContainerOperationResults. */ class ProtectionContainerOperationResults { /** * Create a ProtectionContainerOperationResults. * @param {RecoveryServicesBackupClient} client Reference to the service client. */ constructor(client) { this.client = client; this._get = _get; } /** * Fetches the result of any operation on the container. * * @param {string} vaultName The name of the recovery services vault. * * @param {string} resourceGroupName The name of the resource group where the * recovery services vault is present. * * @param {string} fabricName Fabric name associated with the container. * * @param {string} containerName Container name whose information should be * fetched. * * @param {string} operationId Operation ID which represents the operation * whose result needs to be fetched. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProtectionContainerResource>} - The deserialized result object. * * @reject {Error} - The error object. */ getWithHttpOperationResponse(vaultName, resourceGroupName, fabricName, containerName, operationId, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._get(vaultName, resourceGroupName, fabricName, containerName, operationId, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Fetches the result of any operation on the container. * * @param {string} vaultName The name of the recovery services vault. * * @param {string} resourceGroupName The name of the resource group where the * recovery services vault is present. * * @param {string} fabricName Fabric name associated with the container. * * @param {string} containerName Container name whose information should be * fetched. * * @param {string} operationId Operation ID which represents the operation * whose result needs to be fetched. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {ProtectionContainerResource} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link ProtectionContainerResource} for more * information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ get(vaultName, resourceGroupName, fabricName, containerName, operationId, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._get(vaultName, resourceGroupName, fabricName, containerName, operationId, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._get(vaultName, resourceGroupName, fabricName, containerName, operationId, options, optionalCallback); } } } module.exports = ProtectionContainerOperationResults;
var chalk = require('chalk'); var ErrorHandler = { separator: '\n' + chalk.bgBlack.bold('\n ') + '\n', constructHeader: function ( title, message ){ return chalk.bgRed.black(' ') + chalk.red(' !!! ') + chalk.bgRed.black(' ' + title + ' ') + chalk.red(' => ' + message); }, handleMochaError: function( error ){ ErrorHandler.errorPrinter( 'Mocha', error ); this.emit('end'); }, handleBundlingError: function( error ){ ErrorHandler.errorPrinter( 'Bundling', error ); this.emit('end'); }, handlePhantomError: function( error ){ ErrorHandler.errorPrinter( 'Phantom', error ); this.emit('end'); }, errorPrinter: function ( name, error ){ var message = typeof error !== 'undefined'? error.message : ''; console.log( ErrorHandler.separator ); console.log( ErrorHandler.constructHeader( name + " Error", message ) ); console.log(chalk.cyan.bold('\n error object: ') + '\n', error); console.log( ErrorHandler.separator ); } }; module.exports = ErrorHandler;
import { Resource } from 'resource-loader'; import url from 'url'; import { Spritesheet } from '../core'; export default function () { return function spritesheetParser(resource, next) { const imageResourceName = `${resource.name}_image`; // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists if (!resource.data || resource.type !== Resource.TYPE.JSON || !resource.data.frames || this.resources[imageResourceName] ) { next(); return; } const loadOptions = { crossOrigin: resource.crossOrigin, loadType: Resource.LOAD_TYPE.IMAGE, metadata: resource.metadata.imageMetadata, parentResource: resource, }; const resourcePath = getResourcePath(resource, this.baseUrl); // load the image for this sheet this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { const spritesheet = new Spritesheet( res.texture.baseTexture, resource.data, resource.url ); spritesheet.parse(() => { resource.spritesheet = spritesheet; resource.textures = spritesheet.textures; next(); }); }); }; } export function getResourcePath(resource, baseUrl) { // Prepend url path unless the resource image is a data url if (resource.isDataUrl) { return resource.data.meta.image; } return url.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); }
/// Knockout Mapping plugin v2.4.1 /// (c) 2013 Steven Sanderson, Roy Jacobs - http://knockoutjs.com/ /// License: MIT (http://www.opensource.org/licenses/mit-license.php) (function(e){"function"===typeof require&&"object"===typeof exports&&"object"===typeof module?e(require("knockout"),exports):"function"===typeof define&&define.amd?define(["knockout","exports"],e):e(ko,ko.mapping={})})(function(e,f){function y(b,c){var a,d;for(d in c)if(c.hasOwnProperty(d)&&c[d])if(a=f.getType(b[d]),d&&b[d]&&"array"!==a&&"string"!==a)y(b[d],c[d]);else if("array"===f.getType(b[d])&&"array"===f.getType(c[d])){a=b;for(var e=d,l=b[d],n=c[d],t={},g=l.length-1;0<=g;--g)t[l[g]]=l[g];for(g= n.length-1;0<=g;--g)t[n[g]]=n[g];l=[];n=void 0;for(n in t)l.push(t[n]);a[e]=l}else b[d]=c[d]}function E(b,c){var a={};y(a,b);y(a,c);return a}function z(b,c){for(var a=E({},b),e=L.length-1;0<=e;e--){var f=L[e];a[f]&&(a[""]instanceof Object||(a[""]={}),a[""][f]=a[f],delete a[f])}c&&(a.ignore=h(c.ignore,a.ignore),a.include=h(c.include,a.include),a.copy=h(c.copy,a.copy),a.observe=h(c.observe,a.observe));a.ignore=h(a.ignore,j.ignore);a.include=h(a.include,j.include);a.copy=h(a.copy,j.copy);a.observe=h(a.observe, j.observe);a.mappedProperties=a.mappedProperties||{};a.copiedProperties=a.copiedProperties||{};return a}function h(b,c){"array"!==f.getType(b)&&(b="undefined"===f.getType(b)?[]:[b]);"array"!==f.getType(c)&&(c="undefined"===f.getType(c)?[]:[c]);return e.utils.arrayGetDistinctValues(b.concat(c))}function F(b,c,a,d,k,l,n){var t="array"===f.getType(e.utils.unwrapObservable(c));l=l||"";if(f.isMapped(b)){var g=e.utils.unwrapObservable(b)[p];a=E(g,a)}var j=n||k,h=function(){return a[d]&&a[d].create instanceof Function},x=function(b){var f=G,g=e.dependentObservable;e.dependentObservable=function(a,b,c){c=c||{};a&&"object"==typeof a&&(c=a);var d=c.deferEvaluation,M=!1;c.deferEvaluation=!0;a=new H(a,b,c);if(!d){var g=a,d=e.dependentObservable;e.dependentObservable=H;a=e.isWriteableObservable(g);e.dependentObservable=d;d=H({read:function(){M||(e.utils.arrayRemoveItem(f,g),M=!0);return g.apply(g,arguments)},write:a&&function(a){return g(a)},deferEvaluation:!0});d.__DO=g;a=d;f.push(a)}return a};e.dependentObservable.fn= H.fn;e.computed=e.dependentObservable;b=e.utils.unwrapObservable(k)instanceof Array?a[d].create({data:b||c,parent:j,skip:N}):a[d].create({data:b||c,parent:j});e.dependentObservable=g;e.computed=e.dependentObservable;return b},u=function(){return a[d]&&a[d].update instanceof Function},v=function(b,f){var g={data:f||c,parent:j,target:e.utils.unwrapObservable(b)};e.isWriteableObservable(b)&&(g.observable=b);return a[d].update(g)};if(n=I.get(c))return n;d=d||"";if(t){var t=[],s=!1,m=function(a){return a}; a[d]&&a[d].key&&(m=a[d].key,s=!0);e.isObservable(b)||(b=e.observableArray([]),b.mappedRemove=function(a){var c="function"==typeof a?a:function(b){return b===m(a)};return b.remove(function(a){return c(m(a))})},b.mappedRemoveAll=function(a){var c=C(a,m);return b.remove(function(a){return-1!=e.utils.arrayIndexOf(c,m(a))})},b.mappedDestroy=function(a){var c="function"==typeof a?a:function(b){return b===m(a)};return b.destroy(function(a){return c(m(a))})},b.mappedDestroyAll=function(a){var c=C(a,m);return b.destroy(function(a){return-1!= e.utils.arrayIndexOf(c,m(a))})},b.mappedIndexOf=function(a){var c=C(b(),m);a=m(a);return e.utils.arrayIndexOf(c,a)},b.mappedGet=function(a){return b()[b.mappedIndexOf(a)]},b.mappedCreate=function(a){if(-1!==b.mappedIndexOf(a))throw Error("There already is an object with the key that you specified.");var c=h()?x(a):a;u()&&(a=v(c,a),e.isWriteableObservable(c)?c(a):c=a);b.push(c);return c});n=C(e.utils.unwrapObservable(b),m).sort();g=C(c,m);s&&g.sort();s=e.utils.compareArrays(n,g);n={};var J,A=e.utils.unwrapObservable(c), y={},z=!0,g=0;for(J=A.length;g<J;g++){var r=m(A[g]);if(void 0===r||r instanceof Object){z=!1;break}y[r]=A[g]}var A=[],B=0,g=0;for(J=s.length;g<J;g++){var r=s[g],q,w=l+"["+g+"]";switch(r.status){case "added":var D=z?y[r.value]:K(e.utils.unwrapObservable(c),r.value,m);q=F(void 0,D,a,d,b,w,k);h()||(q=e.utils.unwrapObservable(q));w=O(e.utils.unwrapObservable(c),D,n);q===N?B++:A[w-B]=q;n[w]=!0;break;case "retained":D=z?y[r.value]:K(e.utils.unwrapObservable(c),r.value,m);q=K(b,r.value,m);F(q,D,a,d,b,w, k);w=O(e.utils.unwrapObservable(c),D,n);A[w]=q;n[w]=!0;break;case "deleted":q=K(b,r.value,m)}t.push({event:r.status,item:q})}b(A);a[d]&&a[d].arrayChanged&&e.utils.arrayForEach(t,function(b){a[d].arrayChanged(b.event,b.item)})}else if(P(c)){b=e.utils.unwrapObservable(b);if(!b){if(h())return s=x(),u()&&(s=v(s)),s;if(u())return v(s);b={}}u()&&(b=v(b));I.save(c,b);if(u())return b;Q(c,function(d){var f=l.length?l+"."+d:d;if(-1==e.utils.arrayIndexOf(a.ignore,f))if(-1!=e.utils.arrayIndexOf(a.copy,f))b[d]= c[d];else if("object"!=typeof c[d]&&"array"!=typeof c[d]&&0<a.observe.length&&-1==e.utils.arrayIndexOf(a.observe,f))b[d]=c[d],a.copiedProperties[f]=!0;else{var g=I.get(c[d]),k=F(b[d],c[d],a,d,b,f,b),g=g||k;if(0<a.observe.length&&-1==e.utils.arrayIndexOf(a.observe,f))b[d]=g(),a.copiedProperties[f]=!0;else{if(e.isWriteableObservable(b[d])){if(g=e.utils.unwrapObservable(g),b[d]()!==g)b[d](g)}else g=void 0===b[d]?g:e.utils.unwrapObservable(g),b[d]=g;a.mappedProperties[f]=!0}}})}else switch(f.getType(c)){case "function":u()? e.isWriteableObservable(c)?(c(v(c)),b=c):b=v(c):b=c;break;default:if(e.isWriteableObservable(b))return q=u()?v(b):e.utils.unwrapObservable(c),b(q),q;h()||u();b=h()?x():e.observable(e.utils.unwrapObservable(c));u()&&b(v(b))}return b}function O(b,c,a){for(var d=0,e=b.length;d<e;d++)if(!0!==a[d]&&b[d]===c)return d;return null}function R(b,c){var a;c&&(a=c(b));"undefined"===f.getType(a)&&(a=b);return e.utils.unwrapObservable(a)}function K(b,c,a){b=e.utils.unwrapObservable(b);for(var d=0,f=b.length;d< f;d++){var l=b[d];if(R(l,a)===c)return l}throw Error("When calling ko.update*, the key '"+c+"' was not found!");}function C(b,c){return e.utils.arrayMap(e.utils.unwrapObservable(b),function(a){return c?R(a,c):a})}function Q(b,c){if("array"===f.getType(b))for(var a=0;a<b.length;a++)c(a);else for(a in b)c(a)}function P(b){var c=f.getType(b);return("object"===c||"array"===c)&&null!==b}function T(){var b=[],c=[];this.save=function(a,d){var f=e.utils.arrayIndexOf(b,a);0<=f?c[f]=d:(b.push(a),c.push(d))}; this.get=function(a){a=e.utils.arrayIndexOf(b,a);return 0<=a?c[a]:void 0}}function S(){var b={},c=function(a){var c;try{c=a}catch(e){c="$$$"}a=b[c];void 0===a&&(a=new T,b[c]=a);return a};this.save=function(a,b){c(a).save(a,b)};this.get=function(a){return c(a).get(a)}}var p="__ko_mapping__",H=e.dependentObservable,B=0,G,I,L=["create","update","key","arrayChanged"],N={},x={include:["_destroy"],ignore:[],copy:[],observe:[]},j=x;f.isMapped=function(b){return(b=e.utils.unwrapObservable(b))&&b[p]};f.fromJS= function(b){if(0==arguments.length)throw Error("When calling ko.fromJS, pass the object you want to convert.");try{B++||(G=[],I=new S);var c,a;2==arguments.length&&(arguments[1][p]?a=arguments[1]:c=arguments[1]);3==arguments.length&&(c=arguments[1],a=arguments[2]);a&&(c=E(c,a[p]));c=z(c);var d=F(a,b,c);a&&(d=a);if(!--B)for(;G.length;){var e=G.pop();e&&(e(),e.__DO.throttleEvaluation=e.throttleEvaluation)}d[p]=E(d[p],c);return d}catch(f){throw B=0,f;}};f.fromJSON=function(b){var c=e.utils.parseJson(b); arguments[0]=c;return f.fromJS.apply(this,arguments)};f.updateFromJS=function(){throw Error("ko.mapping.updateFromJS, use ko.mapping.fromJS instead. Please note that the order of parameters is different!");};f.updateFromJSON=function(){throw Error("ko.mapping.updateFromJSON, use ko.mapping.fromJSON instead. Please note that the order of parameters is different!");};f.toJS=function(b,c){j||f.resetDefaultOptions();if(0==arguments.length)throw Error("When calling ko.mapping.toJS, pass the object you want to convert."); if("array"!==f.getType(j.ignore))throw Error("ko.mapping.defaultOptions().ignore should be an array.");if("array"!==f.getType(j.include))throw Error("ko.mapping.defaultOptions().include should be an array.");if("array"!==f.getType(j.copy))throw Error("ko.mapping.defaultOptions().copy should be an array.");c=z(c,b[p]);return f.visitModel(b,function(a){return e.utils.unwrapObservable(a)},c)};f.toJSON=function(b,c){var a=f.toJS(b,c);return e.utils.stringifyJson(a)};f.defaultOptions=function(){if(0<arguments.length)j= arguments[0];else return j};f.resetDefaultOptions=function(){j={include:x.include.slice(0),ignore:x.ignore.slice(0),copy:x.copy.slice(0)}};f.getType=function(b){if(b&&"object"===typeof b){if(b.constructor===Date)return"date";if(b.constructor===Array)return"array"}return typeof b};f.visitModel=function(b,c,a){a=a||{};a.visitedObjects=a.visitedObjects||new S;var d,k=e.utils.unwrapObservable(b);if(P(k))a=z(a,k[p]),c(b,a.parentName),d="array"===f.getType(k)?[]:{};else return c(b,a.parentName);a.visitedObjects.save(b, d);var l=a.parentName;Q(k,function(b){if(!(a.ignore&&-1!=e.utils.arrayIndexOf(a.ignore,b))){var j=k[b],g=a,h=l||"";"array"===f.getType(k)?l&&(h+="["+b+"]"):(l&&(h+="."),h+=b);g.parentName=h;if(!(-1===e.utils.arrayIndexOf(a.copy,b)&&-1===e.utils.arrayIndexOf(a.include,b)&&k[p]&&k[p].mappedProperties&&!k[p].mappedProperties[b]&&k[p].copiedProperties&&!k[p].copiedProperties[b]&&"array"!==f.getType(k)))switch(f.getType(e.utils.unwrapObservable(j))){case "object":case "array":case "undefined":g=a.visitedObjects.get(j); d[b]="undefined"!==f.getType(g)?g:f.visitModel(j,c,a);break;default:d[b]=c(j,a.parentName)}}});return d}});
'use strict'; const dependencies = ['fbjs', 'object-assign', 'prop-types']; // TODO: enumerate all non-private package folders in packages/*? const projects = [ 'react', 'react-art', 'react-dom', 'react-reconciler', 'react-test-renderer', ]; const paramDefinitions = [ { name: 'dry', type: Boolean, description: 'Build artifacts but do not commit or publish', defaultValue: false, }, { name: 'path', type: String, alias: 'p', description: 'Location of React repository to release; defaults to [bold]{cwd}', defaultValue: '.', }, { name: 'version', type: String, alias: 'v', description: 'Semantic version number', }, ]; module.exports = { dependencies, paramDefinitions, projects, };
'use strict'; var log = require('../core/logger'); var _ = require('../mindash'); var warnings = require('../core/warnings'); var fetchResult = require('./fetch'); var StoreEvents = require('./storeEvents'); var CompoundError = require('../errors/compoundError'); var NotFoundError = require('../errors/notFoundError'); var FetchConstants = require('./fetchConstants'); function fetch(id, local, remote) { var store = this; var app = this.app; var options = undefined, result = undefined, error = undefined, cacheError = undefined; if (_.isObject(id)) { options = id; } else { options = { id: id, locally: local, remotely: remote }; } _.defaults(options, { locally: _.noop, remotely: _.noop }); if (!options || _.isUndefined(options.id)) { throw new Error('must specify an id'); } result = dependencyResult(this, options); if (result) { return result; } cacheError = _.isUndefined(options.cacheError) || options.cacheError; if (cacheError) { error = store.__failedFetches[options.id]; if (error) { return fetchFailed(error); } } if (store.__fetchInProgress[options.id]) { return fetchResult.pending(options.id, store); } if (app && app.fetchStarted) { app.fetchStarted(store.id, options.id); } return tryAndGetLocally() || tryAndGetRemotely(); function tryAndGetLocally(remoteCalled) { var result = options.locally.call(store); if (_.isUndefined(result)) { return; } if (_.isNull(result)) { return fetchNotFound(); } if (!remoteCalled) { finished(); } return fetchFinished(result); } function tryAndGetRemotely() { result = options.remotely.call(store); if (result) { if (_.isFunction(result.then)) { store.__fetchInProgress[options.id] = true; result.then(function () { store.__fetchHistory[options.id] = true; result = tryAndGetLocally(true); if (result) { fetchFinished(); store.hasChanged(); } else { fetchNotFound(); store.hasChanged(); } })['catch'](function (error) { fetchFailed(error); store.hasChanged(); store.app.dispatcher.dispatchAction({ type: FetchConstants.FETCH_FAILED, arguments: [error, options.id, store] }); }); return fetchPending(); } else { store.__fetchHistory[options.id] = true; result = tryAndGetLocally(true); if (result) { return result; } } } if (warnings.promiseNotReturnedFromRemotely) { log.warn(promiseNotReturnedWarning()); } return fetchNotFound(); } function promiseNotReturnedWarning() { var inStore = ''; if (store.displayName) { inStore = ' in ' + store.displayName; } return 'The remote fetch for \'' + options.id + '\' ' + inStore + ' ' + 'did not return a promise and the state was ' + 'not present after remotely finished executing. ' + 'This might be because you forgot to return a promise.'; } function finished() { store.__fetchHistory[options.id] = true; delete store.__fetchInProgress[options.id]; } function fetchPending() { return fetchResult.pending(options.id, store); } function fetchFinished(result) { finished(); if (app && app.fetchFinished && result) { app.fetchFinished(store.id, options.id, 'DONE', { result: result }); } return fetchChanged(fetchResult.done(result, options.id, store)); } function fetchFailed(error) { if (cacheError) { store.__failedFetches[options.id] = error; } finished(); if (app && app.fetchFinished) { app.fetchFinished(store.id, options.id, 'FAILED', { error: error }); } return fetchChanged(fetchResult.failed(error, options.id, store)); } function fetchNotFound() { return fetchFailed(new NotFoundError(), options.id, store); } function fetchChanged(fetch) { store.__emitter.emit(StoreEvents.FETCH_CHANGE_EVENT, fetch); return fetch; } } function dependencyResult(store, options) { var pending = false; var errors = []; var dependencies = options.dependsOn; if (!dependencies) { return; } if (!_.isArray(dependencies)) { dependencies = [dependencies]; } _.each(dependencies, function (dependency) { switch (dependency.status) { case FetchConstants.PENDING.toString(): pending = true; break; case FetchConstants.FAILED.toString(): errors.push(dependency.error); break; } }); if (errors.length) { var error = errors.length === 1 ? errors[0] : new CompoundError(errors); return fetchResult.failed(error, options.id, store); } if (pending) { // Wait for all dependencies to be done and then notify listeners Promise.all(_.invoke(dependencies, 'toPromise')).then(function () { store.fetch(options); store.hasChanged(); })['catch'](function () { store.fetch(options); store.hasChanged(); }); return fetchResult.pending(options.id, store); } } fetch.done = fetchResult.done; fetch.failed = fetchResult.failed; fetch.pending = fetchResult.pending; fetch.notFound = fetchResult.notFound; module.exports = fetch;
describe("@event and @fires tags", function() { var docSet = jasmine.getDocSetFromFile('test/fixtures/eventfirestag.js'), snowballMethod = docSet.getByLongname('Hurl#snowball')[0], snowballEvent = docSet.getByLongname('Hurl#event:snowball')[0]; // @event tag it('When a symbol has an @event tag, the doclet is of kind "event".', function() { expect(snowballEvent.kind).toEqual('event'); }); // @fires tag it('When a symbol has a @fires tag, the doclet has an array named "fires".', function() { expect(typeof snowballMethod.fires).toEqual('object'); }); it('When a symbol has a fires array, the members have the event namespace.', function() { expect(snowballMethod.fires[0]).toEqual('Hurl#event:snowball'); }); it('When a symbol has a fires array with a name that already has an event: namespace, it doesn\'t have a secong namespace applied.', function() { expect(snowballMethod.fires[1]).toEqual('Hurl#event:brick'); }); });
import { computed } from "ember-metal/computed"; import { get as emberGet } from "ember-metal/property_get"; import { observer } from "ember-metal/mixin"; import { testWithDefault } from "ember-metal/tests/props_helper"; import EmberObject from "ember-runtime/system/object"; function K() { return this; } QUnit.module('EmberObject computed property'); testWithDefault('computed property on instance', function(get, set) { var MyClass = EmberObject.extend({ foo: computed(function() { return 'FOO'; }) }); equal(get(new MyClass(), 'foo'), 'FOO'); }); testWithDefault('computed property on subclass', function(get, set) { var MyClass = EmberObject.extend({ foo: computed(function() { return 'FOO'; }) }); var Subclass = MyClass.extend({ foo: computed(function() { return 'BAR'; }) }); equal(get(new Subclass(), 'foo'), 'BAR'); }); testWithDefault('replacing computed property with regular val', function(get, set) { var MyClass = EmberObject.extend({ foo: computed(function() { return 'FOO'; }) }); var Subclass = MyClass.extend({ foo: 'BAR' }); equal(get(new Subclass(), 'foo'), 'BAR'); }); testWithDefault('complex depndent keys', function(get, set) { var MyClass = EmberObject.extend({ init: function() { this._super.apply(this, arguments); set(this, 'bar', { baz: 'BIFF' }); }, count: 0, foo: computed(function() { set(this, 'count', get(this, 'count')+1); return emberGet(get(this, 'bar'), 'baz') + ' ' + get(this, 'count'); }).property('bar.baz') }); var Subclass = MyClass.extend({ count: 20 }); var obj1 = new MyClass(); var obj2 = new Subclass(); equal(get(obj1, 'foo'), 'BIFF 1'); equal(get(obj2, 'foo'), 'BIFF 21'); set(get(obj1, 'bar'), 'baz', 'BLARG'); equal(get(obj1, 'foo'), 'BLARG 2'); equal(get(obj2, 'foo'), 'BIFF 21'); set(get(obj2, 'bar'), 'baz', 'BOOM'); equal(get(obj1, 'foo'), 'BLARG 2'); equal(get(obj2, 'foo'), 'BOOM 22'); }); testWithDefault('complex dependent keys changing complex dependent keys', function(get, set) { var MyClass = EmberObject.extend({ init: function() { this._super.apply(this, arguments); set(this, 'bar', { baz: 'BIFF' }); }, count: 0, foo: computed(function() { set(this, 'count', get(this, 'count')+1); return emberGet(get(this, 'bar'), 'baz') + ' ' + get(this, 'count'); }).property('bar.baz') }); var Subclass = MyClass.extend({ init: function() { this._super.apply(this, arguments); set(this, 'bar2', { baz: 'BIFF2' }); }, count: 0, foo: computed(function() { set(this, 'count', get(this, 'count')+1); return emberGet(get(this, 'bar2'), 'baz') + ' ' + get(this, 'count'); }).property('bar2.baz') }); var obj2 = new Subclass(); equal(get(obj2, 'foo'), 'BIFF2 1'); set(get(obj2, 'bar'), 'baz', 'BLARG'); equal(get(obj2, 'foo'), 'BIFF2 1', 'should not invalidate property'); set(get(obj2, 'bar2'), 'baz', 'BLARG'); equal(get(obj2, 'foo'), 'BLARG 2', 'should invalidate property'); }); QUnit.test("can retrieve metadata for a computed property", function() { var MyClass = EmberObject.extend({ computedProperty: computed(function() { }).meta({ key: 'keyValue' }) }); equal(emberGet(MyClass.metaForProperty('computedProperty'), 'key'), 'keyValue', "metadata saved on the computed property can be retrieved"); var ClassWithNoMetadata = EmberObject.extend({ computedProperty: computed(function() { }).volatile(), staticProperty: 12 }); equal(typeof ClassWithNoMetadata.metaForProperty('computedProperty'), "object", "returns empty hash if no metadata has been saved"); expectAssertion(function() { ClassWithNoMetadata.metaForProperty('nonexistentProperty'); }, "metaForProperty() could not find a computed property with key 'nonexistentProperty'."); expectAssertion(function() { ClassWithNoMetadata.metaForProperty('staticProperty'); }, "metaForProperty() could not find a computed property with key 'staticProperty'."); }); QUnit.test("can iterate over a list of computed properties for a class", function() { var MyClass = EmberObject.extend({ foo: computed(function() { }), fooDidChange: observer('foo', function() { }), bar: computed(function() { }) }); var SubClass = MyClass.extend({ baz: computed(function() { }) }); SubClass.reopen({ bat: computed(function() { }).meta({ iAmBat: true }) }); var list = []; MyClass.eachComputedProperty(function(name) { list.push(name); }); deepEqual(list.sort(), ['bar', 'foo'], "watched and unwatched computed properties are iterated"); list = []; SubClass.eachComputedProperty(function(name, meta) { list.push(name); if (name === 'bat') { deepEqual(meta, { iAmBat: true }); } else { deepEqual(meta, {}); } }); deepEqual(list.sort(), ['bar', 'bat', 'baz', 'foo'], "all inherited properties are included"); }); QUnit.test("list of properties updates when an additional property is added (such cache busting)", function() { var MyClass = EmberObject.extend({ foo: computed(K), fooDidChange: observer('foo', function() { }), bar: computed(K) }); var list = []; MyClass.eachComputedProperty(function(name) { list.push(name); }); deepEqual(list.sort(), ['bar', 'foo'].sort(), 'expected two computed properties'); MyClass.reopen({ baz: computed(K) }); MyClass.create(); // force apply mixins list = []; MyClass.eachComputedProperty(function(name) { list.push(name); }); deepEqual(list.sort(), ['bar', 'foo', 'baz'].sort(), 'expected three computed properties'); });
module.exports = process.env.dag_COV ? require('./lib-cov/dag') : require('./lib/dag');
var name = "Basic Larva Lover"; var collection_type = 0; var is_secret = 0; var desc = "Fed three Caterpillars until they metamorphosized into Butterflies"; var status_text = "You've nourished three wiggly Caterpillars into the full bloom of fluttery Butterflyhood. You've earned a Basic Larva Lover badge."; var last_published = 1338918900; var is_shareworthy = 0; var url = "basic-larva-lover"; var category = "animals"; var url_swf = "\/c2.glitch.bz\/achievements\/2011-05-09\/basic_larva_lover_1304984131.swf"; var url_img_180 = "\/c2.glitch.bz\/achievements\/2011-05-09\/basic_larva_lover_1304984131_180.png"; var url_img_60 = "\/c2.glitch.bz\/achievements\/2011-05-09\/basic_larva_lover_1304984131_60.png"; var url_img_40 = "\/c2.glitch.bz\/achievements\/2011-05-09\/basic_larva_lover_1304984131_40.png"; function on_apply(pc){ } var conditions = { 240 : { type : "counter", group : "animals_grown", label : "caterpillar", value : "3" }, }; function onComplete(pc){ // generated from rewards var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0; multiplier += pc.imagination_get_achievement_modifier(); if (/completist/i.exec(this.name)) { var level = pc.stats_get_level(); if (level > 4) { multiplier *= (pc.stats_get_level()/4); } } pc.stats_add_xp(round_to_5(100 * multiplier), true); pc.stats_add_favor_points("humbaba", round_to_5(15 * multiplier)); if(pc.buffs_has('gift_of_gab')) { pc.buffs_remove('gift_of_gab'); } else if(pc.buffs_has('silvertongue')) { pc.buffs_remove('silvertongue'); } } var rewards = { "xp" : 100, "favor" : { "giant" : "humbaba", "points" : 15 } }; // generated ok (NO DATE)
/* cribbed from http://nullstyle.com/2007/06/02/caching-time_ago_in_words */ function time_ago_in_words(from) { return distance_of_time_in_words(new Date(), new Date(from)) } function distance_of_time_in_words(to, from) { seconds_ago = ((to - from) / 1000); minutes_ago = Math.floor(seconds_ago / 60); if(minutes_ago <= 0) { return "less than a minute"; } if(minutes_ago == 1) { return "a minute"; } if(minutes_ago < 45) { return minutes_ago + " minutes"; } if(minutes_ago < 90) { return "1 hour"; } hours_ago = Math.round(minutes_ago / 60); if(minutes_ago < 1440) { return hours_ago + " hours"; } if(minutes_ago < 2880) { return "1 day"; } days_ago = Math.round(minutes_ago / 1440); if(minutes_ago < 43200) { return days_ago + " days"; } if(minutes_ago < 86400) { return "1 month"; } months_ago = Math.round(minutes_ago / 43200); if(minutes_ago < 525960) { return months_ago + " months"; } if(minutes_ago < 1051920) { return "1 year"; } years_ago = Math.round(minutes_ago / 525960); return "over " + years_ago + " years" } function clearField(e) { if (e.cleared) { return; } e.cleared = true; e.value = ''; e.style.color = '#333'; }
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; const msRest = require('ms-rest'); const msRestAzure = require('ms-rest-azure'); const WebResource = msRest.WebResource; /** * Gets all the Event Hubs in a service bus Namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback - The callback. * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link EventHubListResult} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ function _listByNamespace(resourceGroupName, namespaceName, options, callback) { /* jshint validthis: true */ let client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Validate try { if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') { throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.'); } if (resourceGroupName !== null && resourceGroupName !== undefined) { if (resourceGroupName.length > 90) { throw new Error('"resourceGroupName" should satisfy the constraint - "MaxLength": 90'); } if (resourceGroupName.length < 1) { throw new Error('"resourceGroupName" should satisfy the constraint - "MinLength": 1'); } } if (namespaceName === null || namespaceName === undefined || typeof namespaceName.valueOf() !== 'string') { throw new Error('namespaceName cannot be null or undefined and it must be of type string.'); } if (namespaceName !== null && namespaceName !== undefined) { if (namespaceName.length > 50) { throw new Error('"namespaceName" should satisfy the constraint - "MaxLength": 50'); } if (namespaceName.length < 6) { throw new Error('"namespaceName" should satisfy the constraint - "MinLength": 6'); } } if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') { throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.'); } if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') { throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.'); } if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL let baseUrl = this.client.baseUri; let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/eventhubs'; requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName)); requestUrl = requestUrl.replace('{namespaceName}', encodeURIComponent(namespaceName)); requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId)); let queryParameters = []; queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion)); if (queryParameters.length > 0) { requestUrl += '?' + queryParameters.join('&'); } // Create HTTP transport objects let httpRequest = new WebResource(); httpRequest.method = 'GET'; httpRequest.url = requestUrl; httpRequest.headers = {}; // Set Headers httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(let headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.body = null; // Send Request return client.pipeline(httpRequest, (err, response, responseBody) => { if (err) { return callback(err); } let statusCode = response.statusCode; if (statusCode !== 200) { let error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; let parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { let internalError = null; if (parsedErrorResponse.error) internalError = parsedErrorResponse.error; error.code = internalError ? internalError.code : parsedErrorResponse.code; error.message = internalError ? internalError.message : parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { let resultMapper = new client.models['ErrorResponse']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` + `- "${responseBody}" for the default response.`; return callback(error); } return callback(error); } // Create Result let result = null; if (responseBody === '') responseBody = null; // Deserialize Response if (statusCode === 200) { let parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { let resultMapper = new client.models['EventHubListResult']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } } return callback(null, result, httpRequest, response); }); } /** * Gets all the Event Hubs in a service bus Namespace. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} callback - The callback. * * @returns {function} callback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link EventHubListResult} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ function _listByNamespaceNext(nextPageLink, options, callback) { /* jshint validthis: true */ let client = this.client; if(!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error('callback cannot be null.'); } // Validate try { if (nextPageLink === null || nextPageLink === undefined || typeof nextPageLink.valueOf() !== 'string') { throw new Error('nextPageLink cannot be null or undefined and it must be of type string.'); } if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { throw new Error('this.client.acceptLanguage must be of type string.'); } } catch (error) { return callback(error); } // Construct URL let requestUrl = '{nextLink}'; requestUrl = requestUrl.replace('{nextLink}', nextPageLink); // Create HTTP transport objects let httpRequest = new WebResource(); httpRequest.method = 'GET'; httpRequest.url = requestUrl; httpRequest.headers = {}; // Set Headers httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; if (this.client.generateClientRequestId) { httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); } if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { httpRequest.headers['accept-language'] = this.client.acceptLanguage; } if(options) { for(let headerName in options['customHeaders']) { if (options['customHeaders'].hasOwnProperty(headerName)) { httpRequest.headers[headerName] = options['customHeaders'][headerName]; } } } httpRequest.body = null; // Send Request return client.pipeline(httpRequest, (err, response, responseBody) => { if (err) { return callback(err); } let statusCode = response.statusCode; if (statusCode !== 200) { let error = new Error(responseBody); error.statusCode = response.statusCode; error.request = msRest.stripRequest(httpRequest); error.response = msRest.stripResponse(response); if (responseBody === '') responseBody = null; let parsedErrorResponse; try { parsedErrorResponse = JSON.parse(responseBody); if (parsedErrorResponse) { let internalError = null; if (parsedErrorResponse.error) internalError = parsedErrorResponse.error; error.code = internalError ? internalError.code : parsedErrorResponse.code; error.message = internalError ? internalError.message : parsedErrorResponse.message; } if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { let resultMapper = new client.models['ErrorResponse']().mapper(); error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); } } catch (defaultError) { error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` + `- "${responseBody}" for the default response.`; return callback(error); } return callback(error); } // Create Result let result = null; if (responseBody === '') responseBody = null; // Deserialize Response if (statusCode === 200) { let parsedResponse = null; try { parsedResponse = JSON.parse(responseBody); result = JSON.parse(responseBody); if (parsedResponse !== null && parsedResponse !== undefined) { let resultMapper = new client.models['EventHubListResult']().mapper(); result = client.deserialize(resultMapper, parsedResponse, 'result'); } } catch (error) { let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`); deserializationError.request = msRest.stripRequest(httpRequest); deserializationError.response = msRest.stripResponse(response); return callback(deserializationError); } } return callback(null, result, httpRequest, response); }); } /** Class representing a EventHubs. */ class EventHubs { /** * Create a EventHubs. * @param {ServiceBusManagementClient} client Reference to the service client. */ constructor(client) { this.client = client; this._listByNamespace = _listByNamespace; this._listByNamespaceNext = _listByNamespaceNext; } /** * Gets all the Event Hubs in a service bus Namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<EventHubListResult>} - The deserialized result object. * * @reject {Error} - The error object. */ listByNamespaceWithHttpOperationResponse(resourceGroupName, namespaceName, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._listByNamespace(resourceGroupName, namespaceName, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Gets all the Event Hubs in a service bus Namespace. * * @param {string} resourceGroupName Name of the Resource group within the * Azure subscription. * * @param {string} namespaceName The namespace name * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {EventHubListResult} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link EventHubListResult} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ listByNamespace(resourceGroupName, namespaceName, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._listByNamespace(resourceGroupName, namespaceName, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._listByNamespace(resourceGroupName, namespaceName, options, optionalCallback); } } /** * Gets all the Event Hubs in a service bus Namespace. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<EventHubListResult>} - The deserialized result object. * * @reject {Error} - The error object. */ listByNamespaceNextWithHttpOperationResponse(nextPageLink, options) { let client = this.client; let self = this; return new Promise((resolve, reject) => { self._listByNamespaceNext(nextPageLink, options, (err, result, request, response) => { let httpOperationResponse = new msRest.HttpOperationResponse(request, response); httpOperationResponse.body = result; if (err) { reject(err); } else { resolve(httpOperationResponse); } return; }); }); } /** * Gets all the Event Hubs in a service bus Namespace. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {function} [optionalCallback] - The optional callback. * * @returns {function|Promise} If a callback was passed as the last parameter * then it returns the callback else returns a Promise. * * {Promise} A promise is returned * * @resolve {EventHubListResult} - The deserialized result object. * * @reject {Error} - The error object. * * {function} optionalCallback(err, result, request, response) * * {Error} err - The Error object if an error occurred, null otherwise. * * {object} [result] - The deserialized result object if an error did not occur. * See {@link EventHubListResult} for more information. * * {object} [request] - The HTTP Request object if an error did not occur. * * {stream} [response] - The HTTP Response stream if an error did not occur. */ listByNamespaceNext(nextPageLink, options, optionalCallback) { let client = this.client; let self = this; if (!optionalCallback && typeof options === 'function') { optionalCallback = options; options = null; } if (!optionalCallback) { return new Promise((resolve, reject) => { self._listByNamespaceNext(nextPageLink, options, (err, result, request, response) => { if (err) { reject(err); } else { resolve(result); } return; }); }); } else { return self._listByNamespaceNext(nextPageLink, options, optionalCallback); } } } module.exports = EventHubs;
version https://git-lfs.github.com/spec/v1 oid sha256:8cf72a08ee3f913acb0c5c4bbc757dfb1c077ae87ad3679ecd6cfd1483c0721d size 6779
/* Tabulator v4.0.3 (c) Oliver Folkerd */ !function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],t):"undefined"!=typeof module&&module.exports?module.exports=t(require("jquery")):t(jQuery)}(function(t,e){t.widget("ui.tabulator",{_create:function(){this.table=new Tabulator(this.element[0],this.options);for(var t in Tabulator.prototype)"function"==typeof Tabulator.prototype[t]&&"_"!==t.charAt(0)&&(this[t]=this.table[t].bind(this.table))},_setOption:function(t,e){console.error("Tabulator jQuery wrapper does not support setting options after the table has been instantiated")},_destroy:function(t,e){this.table.destroy()}})});
System.register([], function (_export) { "use strict"; var HelloWorld; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } return { setters: [], execute: function () { HelloWorld = function HelloWorld() { _classCallCheck(this, HelloWorld); }; _export("HelloWorld", HelloWorld); } }; });
import baseMerge from '../internal/baseMerge'; import createAssigner from '../internal/createAssigner'; /** * Recursively merges own enumerable properties of the source object(s), that * don't resolve to `undefined` into the destination object. Subsequent sources * overwrite property assignments of previous sources. If `customizer` is * provided it's invoked to produce the merged values of the destination and * source properties. If `customizer` returns `undefined` merging is handled * by the method instead. The `customizer` is bound to `thisArg` and invoked * with five arguments: (objectValue, sourceValue, key, object, source). * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @param {Function} [customizer] The function to customize assigned values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {Object} Returns `object`. * @example * * var users = { * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] * }; * * var ages = { * 'data': [{ 'age': 36 }, { 'age': 40 }] * }; * * _.merge(users, ages); * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } * * // using a customizer callback * var object = { * 'fruits': ['apple'], * 'vegetables': ['beet'] * }; * * var other = { * 'fruits': ['banana'], * 'vegetables': ['carrot'] * }; * * _.merge(object, other, function(a, b) { * if (_.isArray(a)) { * return a.concat(b); * } * }); * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } */ var merge = createAssigner(baseMerge); export default merge;
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-crumbly' };
module.exports = { dispatch: require('./dispatch'), createStore: require('./createStore'), hasDispatched: require('./hasDispatched'), createApplication: require('./createApplication'), getDispatchedActionsWithType: require('./getDispatchedActionsWithType') };
import * as THREE from '../../build/three.module.js'; import { UIRow, UIText, UIInteger, UICheckbox, UIButton, UINumber } from './libs/ui.js'; import { SetGeometryCommand } from './commands/SetGeometryCommand.js'; function GeometryParametersPanel( editor, object ) { var strings = editor.strings; var container = new UIRow(); var geometry = object.geometry; var parameters = geometry.parameters; var options = parameters.options; options.curveSegments = options.curveSegments != undefined ? options.curveSegments : 12; options.steps = options.steps != undefined ? options.steps : 1; options.depth = options.depth != undefined ? options.depth : 100; options.bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; options.bevelSize = options.bevelSize !== undefined ? options.bevelSize : 4; options.bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0; options.bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3; // curveSegments var curveSegmentsRow = new UIRow(); var curveSegments = new UIInteger( options.curveSegments ).onChange( update ).setRange( 1, Infinity ); curveSegmentsRow.add( new UIText( strings.getKey( 'sidebar/geometry/extrude_geometry/curveSegments' ) ).setWidth( '90px' ) ); curveSegmentsRow.add( curveSegments ); container.add( curveSegmentsRow ); // steps var stepsRow = new UIRow(); var steps = new UIInteger( options.steps ).onChange( update ).setRange( 1, Infinity ); stepsRow.add( new UIText( strings.getKey( 'sidebar/geometry/extrude_geometry/steps' ) ).setWidth( '90px' ) ); stepsRow.add( steps ); container.add( stepsRow ); // depth var depthRow = new UIRow(); var depth = new UINumber( options.depth ).onChange( update ).setRange( 1, Infinity ); depthRow.add( new UIText( strings.getKey( 'sidebar/geometry/extrude_geometry/depth' ) ).setWidth( '90px' ) ); depthRow.add( depth ); container.add( depthRow ); // enabled var enabledRow = new UIRow(); var enabled = new UICheckbox( options.bevelEnabled ).onChange( update ); enabledRow.add( new UIText( strings.getKey( 'sidebar/geometry/extrude_geometry/bevelEnabled' ) ).setWidth( '90px' ) ); enabledRow.add( enabled ); container.add( enabledRow ); if ( options.bevelEnabled === true ) { // thickness var thicknessRow = new UIRow(); var thickness = new UINumber( options.bevelThickness ).onChange( update ); thicknessRow.add( new UIText( strings.getKey( 'sidebar/geometry/extrude_geometry/bevelThickness' ) ).setWidth( '90px' ) ); thicknessRow.add( thickness ); container.add( thicknessRow ); // size var sizeRow = new UIRow(); var size = new UINumber( options.bevelSize ).onChange( update ); sizeRow.add( new UIText( strings.getKey( 'sidebar/geometry/extrude_geometry/bevelSize' ) ).setWidth( '90px' ) ); sizeRow.add( size ); container.add( sizeRow ); // offset var offsetRow = new UIRow(); var offset = new UINumber( options.bevelOffset ).onChange( update ); offsetRow.add( new UIText( strings.getKey( 'sidebar/geometry/extrude_geometry/bevelOffset' ) ).setWidth( '90px' ) ); offsetRow.add( offset ); container.add( offsetRow ); // segments var segmentsRow = new UIRow(); var segments = new UIInteger( options.bevelSegments ).onChange( update ).setRange( 0, Infinity ); segmentsRow.add( new UIText( strings.getKey( 'sidebar/geometry/extrude_geometry/bevelSegments' ) ).setWidth( '90px' ) ); segmentsRow.add( segments ); container.add( segmentsRow ); } var button = new UIButton( strings.getKey( 'sidebar/geometry/extrude_geometry/shape' ) ).onClick( toShape ).setWidth( '90px' ).setMarginLeft( '90px' ); container.add( button ); // function update() { editor.execute( new SetGeometryCommand( editor, object, new THREE.ExtrudeGeometry( parameters.shapes, { curveSegments: curveSegments.getValue(), steps: steps.getValue(), depth: depth.getValue(), bevelEnabled: enabled.getValue(), bevelThickness: thickness !== undefined ? thickness.getValue() : options.bevelThickness, bevelSize: size !== undefined ? size.getValue() : options.bevelSize, bevelOffset: offset !== undefined ? offset.getValue() : options.bevelOffset, bevelSegments: segments !== undefined ? segments.getValue() : options.bevelSegments } ) ) ); } function toShape() { editor.execute( new SetGeometryCommand( editor, object, new THREE.ShapeGeometry( parameters.shapes, options.curveSegments ) ) ); } return container; } export { GeometryParametersPanel };
var visit = require("./path-visitor").visit; var warnedAboutDeprecation = false; function traverseWithFullPathInfo(node, callback) { if (!warnedAboutDeprecation) { warnedAboutDeprecation = true; console.warn( "\033[33m", // yellow 'DEPRECATED(ast-types): Please use require("ast-types").visit ' + "instead of .traverse for syntax tree manipulation." + "\033[0m" // reset ); } return visit(node, { visitNode: function(path) { if (callback.call(path, path.value) !== false) { this.traverse(path); } return false; } }); } traverseWithFullPathInfo.fast = traverseWithFullPathInfo; module.exports = traverseWithFullPathInfo;
/** @license * @pnp/common v1.1.5-4 - pnp - provides shared functionality across all pnp libraries * MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE) * Copyright (c) 2018 Microsoft * docs: https://pnp.github.io/pnpjs/ * source: https:github.com/pnp/pnpjs * bugs: https://github.com/pnp/pnpjs/issues */ import { __extends } from 'tslib'; import { inject } from 'adal-angular/dist/adal.min.js'; var global$1 = (typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}); /** * Gets a callback function which will maintain context across async calls. * Allows for the calling pattern getCtxCallback(thisobj, method, methodarg1, methodarg2, ...) * * @param context The object that will be the 'this' value in the callback * @param method The method to which we will apply the context and parameters * @param params Optional, additional arguments to supply to the wrapped method when it is invoked */ function getCtxCallback(context, method) { var params = []; for (var _i = 2; _i < arguments.length; _i++) { params[_i - 2] = arguments[_i]; } return function () { method.apply(context, params); }; } /** * Adds a value to a date * * @param date The date to which we will add units, done in local time * @param interval The name of the interval to add, one of: ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second'] * @param units The amount to add to date of the given interval * * http://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object */ function dateAdd(date, interval, units) { var ret = new Date(date); // don't change original date switch (interval.toLowerCase()) { case "year": ret.setFullYear(ret.getFullYear() + units); break; case "quarter": ret.setMonth(ret.getMonth() + 3 * units); break; case "month": ret.setMonth(ret.getMonth() + units); break; case "week": ret.setDate(ret.getDate() + 7 * units); break; case "day": ret.setDate(ret.getDate() + units); break; case "hour": ret.setTime(ret.getTime() + units * 3600000); break; case "minute": ret.setTime(ret.getTime() + units * 60000); break; case "second": ret.setTime(ret.getTime() + units * 1000); break; default: ret = undefined; break; } return ret; } /** * Combines an arbitrary set of paths ensuring and normalizes the slashes * * @param paths 0 to n path parts to combine */ function combine() { var paths = []; for (var _i = 0; _i < arguments.length; _i++) { paths[_i] = arguments[_i]; } return paths .filter(function (path) { return !stringIsNullOrEmpty(path); }) .map(function (path) { return path.replace(/^[\\|\/]/, "").replace(/[\\|\/]$/, ""); }) .join("/") .replace(/\\/g, "/"); } /** * Gets a random string of chars length * * https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript * * @param chars The length of the random string to generate */ function getRandomString(chars) { var text = new Array(chars); var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < chars; i++) { text[i] = possible.charAt(Math.floor(Math.random() * possible.length)); } return text.join(""); } /** * Gets a random GUID value * * http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript */ /* tslint:disable no-bitwise */ function getGUID() { var d = new Date().getTime(); var guid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === "x" ? r : (r & 0x3 | 0x8)).toString(16); }); return guid; } /* tslint:enable */ /** * Determines if a given value is a function * * @param cf The thing to test for functionness */ function isFunc(cf) { return typeof cf === "function"; } /** * Determines if an object is both defined and not null * @param obj Object to test */ function objectDefinedNotNull(obj) { return obj !== undefined && obj !== null; } /** * @returns whether the provided parameter is a JavaScript Array or not. */ function isArray(array) { if (Array.isArray) { return Array.isArray(array); } return array && typeof array.length === "number" && array.constructor === Array; } /** * Provides functionality to extend the given object by doing a shallow copy * * @param target The object to which properties will be copied * @param source The source object from which properties will be copied * @param noOverwrite If true existing properties on the target are not overwritten from the source * @param filter If provided allows additional filtering on what properties are copied (propName: string) => boolean * */ function extend(target, source, noOverwrite, filter) { if (noOverwrite === void 0) { noOverwrite = false; } if (filter === void 0) { filter = function () { return true; }; } if (!objectDefinedNotNull(source)) { return target; } // ensure we don't overwrite things we don't want overwritten var check = noOverwrite ? function (o, i) { return !(i in o); } : function () { return true; }; // final filter we will use var f = function (v) { return check(target, v) && filter(v); }; return Object.getOwnPropertyNames(source) .filter(f) .reduce(function (t, v) { t[v] = source[v]; return t; }, target); } /** * Determines if a given url is absolute * * @param url The url to check to see if it is absolute */ function isUrlAbsolute(url) { return /^https?:\/\/|^\/\//i.test(url); } /** * Determines if a string is null or empty or undefined * * @param s The string to test */ function stringIsNullOrEmpty(s) { return s === undefined || s === null || s.length < 1; } /** * Gets an attribute value from an html/xml string block. NOTE: if the input attribute value has * RegEx special characters they will be escaped in the returned string * * @param html HTML to search * @param attrName The name of the attribute to find */ function getAttrValueFromString(html, attrName) { // make the input safe for regex html = html.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); var reg = new RegExp(attrName + "\\s*?=\\s*?(\"|')([^\\1]*?)\\1", "i"); var match = reg.exec(html); return match !== null && match.length > 0 ? match[2] : null; } /** * Ensures guid values are represented consistently as "ea123463-137d-4ae3-89b8-cf3fc578ca05" * * @param guid The candidate guid */ function sanitizeGuid(guid) { if (stringIsNullOrEmpty(guid)) { return guid; } var matches = /([0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})/i.exec(guid); return matches === null ? guid : matches[1]; } /** * Shorthand for oToS * * @param o Any type of object */ function jsS(o) { return JSON.stringify(o); } /** * Shorthand for Object.hasOwnProperty * * @param o Object to check for * @param p Name of the property */ function hOP(o, p) { return Object.hasOwnProperty.call(o, p); } function mergeHeaders(target, source) { if (source !== undefined && source !== null) { var temp = new Request("", { headers: source }); temp.headers.forEach(function (value, name) { target.append(name, value); }); } } function mergeOptions(target, source) { if (objectDefinedNotNull(source)) { var headers = extend(target.headers || {}, source.headers); target = extend(target, source); target.headers = headers; } } /** * Makes requests using the global/window fetch API */ var FetchClient = /** @class */ (function () { function FetchClient() { } FetchClient.prototype.fetch = function (url, options) { return global$1.fetch(url, options); }; return FetchClient; }()); /** * Makes requests using the fetch API adding the supplied token to the Authorization header */ var BearerTokenFetchClient = /** @class */ (function (_super) { __extends(BearerTokenFetchClient, _super); function BearerTokenFetchClient(_token) { var _this = _super.call(this) || this; _this._token = _token; return _this; } Object.defineProperty(BearerTokenFetchClient.prototype, "token", { get: function () { return this._token; }, set: function (token) { this._token = token; }, enumerable: true, configurable: true }); BearerTokenFetchClient.prototype.fetch = function (url, options) { if (options === void 0) { options = {}; } var headers = new Headers(); mergeHeaders(headers, options.headers); headers.set("Authorization", "Bearer " + this._token); options.headers = headers; return _super.prototype.fetch.call(this, url, options); }; return BearerTokenFetchClient; }(FetchClient)); /** * Azure AD Client for use in the browser */ var AdalClient = /** @class */ (function (_super) { __extends(AdalClient, _super); /** * Creates a new instance of AdalClient * @param clientId Azure App Id * @param tenant Office 365 tenant (Ex: {tenant}.onmicrosoft.com) * @param redirectUri The redirect url used to authenticate the */ function AdalClient(clientId, tenant, redirectUri) { var _this = _super.call(this, null) || this; _this.clientId = clientId; _this.tenant = tenant; _this.redirectUri = redirectUri; return _this; } /** * Creates a new AdalClient using the values of the supplied SPFx context * * @param spfxContext Current SPFx context * @param clientId Optional client id to use instead of the built-in SPFx id * @description Using this method and the default clientId requires that the features described in * this article https://docs.microsoft.com/en-us/sharepoint/dev/spfx/use-aadhttpclient are activated in the tenant. If not you can * creat your own app, grant permissions and use that clientId here along with the SPFx context */ AdalClient.fromSPFxContext = function (spfxContext, cliendId) { if (cliendId === void 0) { cliendId = "c58637bb-e2e1-4312-8a00-04b5ffcd3403"; } // this "magic" client id is the one to which permissions are granted behind the scenes // this redirectUrl is the page as used by spfx return new AdalClient(cliendId, spfxContext.pageContext.aadInfo.tenantId.toString(), combine(window.location.origin, "/_forms/spfxsinglesignon.aspx")); }; /** * Conducts the fetch opertation against the AAD secured resource * * @param url Absolute URL for the request * @param options Any fetch options passed to the underlying fetch implementation */ AdalClient.prototype.fetch = function (url, options) { var _this = this; if (!isUrlAbsolute(url)) { throw new Error("You must supply absolute urls to AdalClient.fetch."); } // the url we are calling is the resource return this.getToken(this.getResource(url)).then(function (token) { _this.token = token; return _super.prototype.fetch.call(_this, url, options); }); }; /** * Gets a token based on the current user * * @param resource The resource for which we are requesting a token */ AdalClient.prototype.getToken = function (resource) { var _this = this; return new Promise(function (resolve, reject) { _this.ensureAuthContext().then(function (_) { return _this.login(); }).then(function (_) { AdalClient._authContext.acquireToken(resource, function (message, token) { if (message) { return reject(new Error(message)); } resolve(token); }); }).catch(reject); }); }; /** * Ensures we have created and setup the adal AuthenticationContext instance */ AdalClient.prototype.ensureAuthContext = function () { var _this = this; return new Promise(function (resolve) { if (AdalClient._authContext === null) { AdalClient._authContext = inject({ clientId: _this.clientId, displayCall: function (url) { if (_this._displayCallback) { _this._displayCallback(url); } }, navigateToLoginRequestUrl: false, redirectUri: _this.redirectUri, tenant: _this.tenant, }); } resolve(); }); }; /** * Ensures the current user is logged in */ AdalClient.prototype.login = function () { var _this = this; if (this._loginPromise) { return this._loginPromise; } this._loginPromise = new Promise(function (resolve, reject) { if (AdalClient._authContext.getCachedUser()) { return resolve(); } _this._displayCallback = function (url) { var popupWindow = window.open(url, "login", "width=483, height=600"); if (!popupWindow) { return reject(new Error("Could not open pop-up window for auth. Likely pop-ups are blocked by the browser.")); } if (popupWindow && popupWindow.focus) { popupWindow.focus(); } var pollTimer = window.setInterval(function () { if (!popupWindow || popupWindow.closed || popupWindow.closed === undefined) { window.clearInterval(pollTimer); } try { if (popupWindow.document.URL.indexOf(_this.redirectUri) !== -1) { window.clearInterval(pollTimer); AdalClient._authContext.handleWindowCallback(popupWindow.location.hash); popupWindow.close(); resolve(); } } catch (e) { reject(e); } }, 30); }; // this triggers the login process _this.ensureAuthContext().then(function (_) { AdalClient._authContext._loginInProgress = false; AdalClient._authContext.login(); _this._displayCallback = null; }); }); return this._loginPromise; }; /** * Parses out the root of the request url to use as the resource when getting the token * * After: https://gist.github.com/jlong/2428561 * @param url The url to parse */ AdalClient.prototype.getResource = function (url) { var parser = document.createElement("a"); parser.href = url; return parser.protocol + "//" + parser.hostname; }; /** * Our auth context */ AdalClient._authContext = null; return AdalClient; }(BearerTokenFetchClient)); /** * Used to calculate the object properties, with polyfill if needed */ var objectEntries = isFunc(Object.entries) ? Object.entries : function (o) { return Object.keys(o).map(function (k) { return [k, o[k]]; }); }; /** * Converts the supplied object to a map * * @param o The object to map */ function objectToMap(o) { if (o !== undefined && o !== null) { return new Map(objectEntries(o)); } return new Map(); } /** * Merges to Map instances together, overwriting values in target with matching keys, last in wins * * @param target map into which the other maps are merged * @param maps One or more maps to merge into the target */ function mergeMaps(target) { var maps = []; for (var _i = 1; _i < arguments.length; _i++) { maps[_i - 1] = arguments[_i]; } for (var i = 0; i < maps.length; i++) { maps[i].forEach(function (v, k) { target.set(k, v); }); } return target; } function setup(config) { RuntimeConfig.extend(config); } // lable mapping for known config values var s = [ "defaultCachingStore", "defaultCachingTimeoutSeconds", "globalCacheDisable", "enableCacheExpiration", "cacheExpirationIntervalMilliseconds", "spfxContext", ]; var RuntimeConfigImpl = /** @class */ (function () { function RuntimeConfigImpl(_v) { if (_v === void 0) { _v = new Map(); } this._v = _v; // setup defaults this._v.set(s[0], "session"); this._v.set(s[1], 60); this._v.set(s[2], false); this._v.set(s[3], false); this._v.set(s[4], 750); this._v.set(s[5], null); } /** * * @param config The set of properties to add to the globa configuration instance */ RuntimeConfigImpl.prototype.extend = function (config) { this._v = mergeMaps(this._v, objectToMap(config)); }; RuntimeConfigImpl.prototype.get = function (key) { return this._v.get(key); }; Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingStore", { get: function () { return this.get(s[0]); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingTimeoutSeconds", { get: function () { return this.get(s[1]); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "globalCacheDisable", { get: function () { return this.get(s[2]); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "enableCacheExpiration", { get: function () { return this.get(s[3]); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "cacheExpirationIntervalMilliseconds", { get: function () { return this.get(s[4]); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "spfxContext", { get: function () { return this.get(s[5]); }, enumerable: true, configurable: true }); return RuntimeConfigImpl; }()); var _runtimeConfig = new RuntimeConfigImpl(); var RuntimeConfig = _runtimeConfig; /** * A wrapper class to provide a consistent interface to browser based storage * */ var PnPClientStorageWrapper = /** @class */ (function () { /** * Creates a new instance of the PnPClientStorageWrapper class * * @constructor */ function PnPClientStorageWrapper(store, defaultTimeoutMinutes) { if (defaultTimeoutMinutes === void 0) { defaultTimeoutMinutes = -1; } this.store = store; this.defaultTimeoutMinutes = defaultTimeoutMinutes; this.enabled = this.test(); // if the cache timeout is enabled call the handler // this will clear any expired items and set the timeout function if (RuntimeConfig.enableCacheExpiration) { this.cacheExpirationHandler(); } } /** * Get a value from storage, or null if that value does not exist * * @param key The key whose value we want to retrieve */ PnPClientStorageWrapper.prototype.get = function (key) { if (!this.enabled) { return null; } var o = this.store.getItem(key); if (o === undefined) { return null; } var persistable = JSON.parse(o); if (new Date(persistable.expiration) <= new Date()) { this.delete(key); return null; } else { return persistable.value; } }; /** * Adds a value to the underlying storage * * @param key The key to use when storing the provided value * @param o The value to store * @param expire Optional, if provided the expiration of the item, otherwise the default is used */ PnPClientStorageWrapper.prototype.put = function (key, o, expire) { if (this.enabled) { this.store.setItem(key, this.createPersistable(o, expire)); } }; /** * Deletes a value from the underlying storage * * @param key The key of the pair we want to remove from storage */ PnPClientStorageWrapper.prototype.delete = function (key) { if (this.enabled) { this.store.removeItem(key); } }; /** * Gets an item from the underlying storage, or adds it if it does not exist using the supplied getter function * * @param key The key to use when storing the provided value * @param getter A function which will upon execution provide the desired value * @param expire Optional, if provided the expiration of the item, otherwise the default is used */ PnPClientStorageWrapper.prototype.getOrPut = function (key, getter, expire) { var _this = this; if (!this.enabled) { return getter(); } return new Promise(function (resolve) { var o = _this.get(key); if (o == null) { getter().then(function (d) { _this.put(key, d, expire); resolve(d); }); } else { resolve(o); } }); }; /** * Deletes any expired items placed in the store by the pnp library, leaves other items untouched */ PnPClientStorageWrapper.prototype.deleteExpired = function () { var _this = this; return new Promise(function (resolve, reject) { if (!_this.enabled) { resolve(); } try { for (var i = 0; i < _this.store.length; i++) { var key = _this.store.key(i); if (key !== null) { // test the stored item to see if we stored it if (/["|']?pnp["|']? ?: ?1/i.test(_this.store.getItem(key))) { // get those items as get will delete from cache if they are expired _this.get(key); } } } resolve(); } catch (e) { reject(e); } }); }; /** * Used to determine if the wrapped storage is available currently */ PnPClientStorageWrapper.prototype.test = function () { var str = "t"; try { this.store.setItem(str, str); this.store.removeItem(str); return true; } catch (e) { return false; } }; /** * Creates the persistable to store */ PnPClientStorageWrapper.prototype.createPersistable = function (o, expire) { if (expire === undefined) { // ensure we are by default inline with the global library setting var defaultTimeout = RuntimeConfig.defaultCachingTimeoutSeconds; if (this.defaultTimeoutMinutes > 0) { defaultTimeout = this.defaultTimeoutMinutes * 60; } expire = dateAdd(new Date(), "second", defaultTimeout); } return jsS({ pnp: 1, expiration: expire, value: o }); }; /** * Deletes expired items added by this library in this.store and sets a timeout to call itself */ PnPClientStorageWrapper.prototype.cacheExpirationHandler = function () { var _this = this; this.deleteExpired().then(function (_) { // call ourself in the future setTimeout(getCtxCallback(_this, _this.cacheExpirationHandler), RuntimeConfig.cacheExpirationIntervalMilliseconds); }).catch(function (e) { console.error(e); }); }; return PnPClientStorageWrapper; }()); /** * A thin implementation of in-memory storage for use in nodejs */ var MemoryStorage = /** @class */ (function () { function MemoryStorage(_store) { if (_store === void 0) { _store = new Map(); } this._store = _store; } Object.defineProperty(MemoryStorage.prototype, "length", { get: function () { return this._store.size; }, enumerable: true, configurable: true }); MemoryStorage.prototype.clear = function () { this._store.clear(); }; MemoryStorage.prototype.getItem = function (key) { return this._store.get(key); }; MemoryStorage.prototype.key = function (index) { return Array.from(this._store)[index][0]; }; MemoryStorage.prototype.removeItem = function (key) { this._store.delete(key); }; MemoryStorage.prototype.setItem = function (key, data) { this._store.set(key, data); }; return MemoryStorage; }()); /** * A class that will establish wrappers for both local and session storage */ var PnPClientStorage = /** @class */ (function () { /** * Creates a new instance of the PnPClientStorage class * * @constructor */ function PnPClientStorage(_local, _session) { if (_local === void 0) { _local = null; } if (_session === void 0) { _session = null; } this._local = _local; this._session = _session; } Object.defineProperty(PnPClientStorage.prototype, "local", { /** * Provides access to the local storage of the browser */ get: function () { if (this._local === null) { this._local = this.getStore(localStorage); } return this._local; }, enumerable: true, configurable: true }); Object.defineProperty(PnPClientStorage.prototype, "session", { /** * Provides access to the session storage of the browser */ get: function () { if (this._session === null) { this._session = this.getStore(sessionStorage); } return this._session; }, enumerable: true, configurable: true }); PnPClientStorage.prototype.getStore = function (s) { return s !== undefined ? new PnPClientStorageWrapper(s) : new PnPClientStorageWrapper(new MemoryStorage()); }; return PnPClientStorage; }()); export { AdalClient, objectToMap, mergeMaps, setup, RuntimeConfigImpl, RuntimeConfig, mergeHeaders, mergeOptions, FetchClient, BearerTokenFetchClient, PnPClientStorageWrapper, PnPClientStorage, getCtxCallback, dateAdd, combine, getRandomString, getGUID, isFunc, objectDefinedNotNull, isArray, extend, isUrlAbsolute, stringIsNullOrEmpty, getAttrValueFromString, sanitizeGuid, jsS, hOP }; //# sourceMappingURL=common.es5.js.map
(function(){var c=document,d="length",e=" translation",f=" using Google Translate?",k=".",l="Google has automatically translated this page to: ",m="Powered by ",n="Translate",p="Translate everything to ",q="Translate this page to: ",r="Translated to: ",t="Turn off ",u="Turn off for: ",v="View this page in: ",w="var ",x=this;function y(a,z){var g=a.split(k),b=x;g[0]in b||!b.execScript||b.execScript(w+g[0]);for(var h;g[d]&&(h=g.shift());)g[d]||void 0===z?b[h]?b=b[h]:b=b[h]={}:b[h]=z};var A={0:n,1:"Cancel",2:"Close",3:function(a){return l+a},4:function(a){return r+a},5:"Error: The server could not complete your request. Try again later.",6:"Learn more",7:function(a){return m+a},8:n,9:"Translation in progress",10:function(a){return q+(a+f)},11:function(a){return v+a},12:"Show original",13:"The content of this local file will be sent to Google for translation using a secure connection.",14:"The content of this secure page will be sent to Google for translation using a secure connection.", 15:"The content of this intranet page will be sent to Google for translation using a secure connection.",16:"Select Language",17:function(a){return t+(a+e)},18:function(a){return u+a},19:"Always hide",20:"Original text:",21:"Contribute a better translation",22:"Contribute",23:"Translate all",24:"Restore all",25:"Cancel all",26:"Translate sections to my language",27:function(a){return p+a},28:"Show original languages",29:"Options",30:"Turn off translation for this site",31:null,32:"Show alternative translations", 33:"Click on words above to get alternative translations",34:"Use",35:"Drag with shift key to reorder",36:"Click for alternative translations",37:"Hold down the shift key, click, and drag the words above to reorder.",38:"Thank you for contributing your translation suggestion to Google Translate.",39:"Manage translation for this site",40:"Click a word for alternative translations, or double-click to edit directly",41:"Original text",42:n,43:n,44:"Your correction has been submitted.",45:"Error: The language of the webpage is not supported."};var B=window.google&&google.translate&&google.translate._const; if(B){var C;t:{for(var D=[],E=["25,0.01,20150123"],F=0;F<E[d];++F){var G=E[F].split(","),H=G[0];if(H){var I=Number(G[1]);if(!(!I||.1<I||0>I)){var J=Number(G[2]),K=new Date,L=1E4*K.getFullYear()+100*(K.getMonth()+1)+K.getDate();!J||J<L||D.push({version:H,a:I,b:J})}}}for(var M=0,N=window.location.href.match(/google\.translate\.element\.random=([\d\.]+)/),O=Number(N&&N[1])||Math.random(),F=0;F<D[d];++F){var P=D[F],M=M+P.a;if(1<=M)break;if(O<M){C=P.version;break t}}C="26"}var Q="/translate_static/js/element/%s/element_main.js".replace("%s", C);if("0"==C){var R=" translate_static js element %s element_main.js".split(" ");R[R[d]-1]="main.js";Q=R.join("/").replace("%s",C)}if(B._cjlc)B._cjlc(B._pas+B._pah+Q);else{var S=B._pas+B._pah+Q,T=c.createElement("script");T.type="text/javascript";T.charset="UTF-8";T.src=S;var U=c.getElementsByTagName("head")[0];U||(U=c.body.parentNode.appendChild(c.createElement("head")));U.appendChild(T)}y("google.translate.m",A);y("google.translate.v",C)};})()
import { DB_TYPES } from './dbTypes'; export const HOST = process.env.HOSTNAME || 'localhost'; export const PORT = process.env.PORT || '3000'; export const ENV = process.env.NODE_ENV || 'development'; export const DB_TYPE = process.env.DB_TYPE || DB_TYPES.MONGO; export const GOOGLE_ANALYTICS_ID = process.env.GOOGLE_ANALYTICS_ID || null;
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.dialog.add("textarea",function(b){return{title:b.lang.forms.textarea.title,minWidth:350,minHeight:220,onShow:function(){delete this.textarea;var a=this.getParentEditor().getSelection().getSelectedElement();a&&"textarea"==a.getName()&&(this.textarea=a,this.setupContent(a))},onOk:function(){var a,b=this.textarea,c=!b;c&&(a=this.getParentEditor(),b=a.document.createElement("textarea"));this.commitContent(b);c&&a.insertElement(b)},contents:[{id:"info",label:b.lang.forms.textarea.title,title:b.lang.forms.textarea.title, elements:[{id:"_cke_saved_name",type:"text",label:b.lang.common.name,"default":"",accessKey:"N",setup:function(a){this.setValue(a.data("cke-saved-name")||a.getAttribute("name")||"")},commit:function(a){this.getValue()?a.data("cke-saved-name",this.getValue()):(a.data("cke-saved-name",!1),a.removeAttribute("name"))}},{type:"hbox",widths:["50%","50%"],children:[{id:"cols",type:"text",label:b.lang.forms.textarea.cols,"default":"",accessKey:"C",style:"width:50px",validate:CKEDITOR.dialog.validate.integer(b.lang.common.validateNumberFailed), setup:function(a){this.setValue(a.hasAttribute("cols")&&a.getAttribute("cols")||"")},commit:function(a){this.getValue()?a.setAttribute("cols",this.getValue()):a.removeAttribute("cols")}},{id:"rows",type:"text",label:b.lang.forms.textarea.rows,"default":"",accessKey:"R",style:"width:50px",validate:CKEDITOR.dialog.validate.integer(b.lang.common.validateNumberFailed),setup:function(a){this.setValue(a.hasAttribute("rows")&&a.getAttribute("rows")||"")},commit:function(a){this.getValue()?a.setAttribute("rows", this.getValue()):a.removeAttribute("rows")}}]},{id:"value",type:"textarea",label:b.lang.forms.textfield.value,"default":"",setup:function(a){this.setValue(a.$.defaultValue)},commit:function(a){a.$.value=a.$.defaultValue=this.getValue()}}]}]}});
import React, {Component, PropTypes} from 'react'; import ReactDOM from 'react-dom'; import Events from '../utils/events'; import propTypes from '../utils/propTypes'; import Menu from '../Menu/Menu'; import Popover from '../Popover/Popover'; import warning from 'warning'; class IconMenu extends Component { static muiName = 'IconMenu'; static propTypes = { /** * This is the point on the icon where the menu * `targetOrigin` will attach. * Options: * vertical: [top, center, bottom] * horizontal: [left, middle, right]. */ anchorOrigin: propTypes.origin, /** * If true, the popover will apply transitions when * it gets added to the DOM. */ animated: PropTypes.bool, /** * Override the default animation component used. */ animation: PropTypes.func, /** * Should be used to pass `MenuItem` components. */ children: PropTypes.node, /** * The CSS class name of the root element. */ className: PropTypes.string, /** * This is the `IconButton` to render. This button will open the menu. */ iconButtonElement: PropTypes.element.isRequired, /** * Override the inline-styles of the underlying icon element. */ iconStyle: PropTypes.object, /** * Override the inline-styles of the underlying `List` element. */ listStyle: PropTypes.object, /** * Override the inline-styles of the menu element. */ menuStyle: PropTypes.object, /** * If true, the value can an be array and allow the menu to be a multi-select. */ multiple: PropTypes.bool, /** * Callback function fired when a menu item is selected with a touch-tap. * * @param {object} event TouchTap event targeting the selected menu item element. * @param {object} child The selected element. */ onItemTouchTap: PropTypes.func, /** * Callback function fired when the `IconButton` element is focused or blurred by the keyboard. * * @param {object} event `focus` or `blur` event targeting the `IconButton` element. * @param {boolean} keyboardFocused If true, the `IconButton` element is focused. */ onKeyboardFocus: PropTypes.func, /** @ignore */ onMouseDown: PropTypes.func, /** @ignore */ onMouseEnter: PropTypes.func, /** @ignore */ onMouseLeave: PropTypes.func, /** @ignore */ onMouseUp: PropTypes.func, /** * Callback function fired when the `open` state of the menu is requested to be changed. * * @param {boolean} open If true, the menu was requested to be opened. * @param {string} reason The reason for the open or close request. Possible values are * 'keyboard' and 'iconTap' for open requests; 'enter', 'escape', 'itemTap', and 'clickAway' * for close requests. */ onRequestChange: PropTypes.func, /** * Callback function fired when the `IconButton` element is touch-tapped. * * @param {object} event TouchTap event targeting the `IconButton` element. */ onTouchTap: PropTypes.func, /** * If true, the `IconMenu` is opened. */ open: PropTypes.bool, /** * Override the inline-styles of the root element. */ style: PropTypes.object, /** * This is the point on the menu which will stick to the menu * origin. * Options: * vertical: [top, center, bottom] * horizontal: [left, middle, right]. */ targetOrigin: propTypes.origin, /** * Sets the delay in milliseconds before closing the * menu when an item is clicked. * If set to 0 then the auto close functionality * will be disabled. */ touchTapCloseDelay: PropTypes.number, /** * If true, the popover will render on top of an invisible * layer, which will prevent clicks to the underlying elements. */ useLayerForClickAway: PropTypes.bool, }; static defaultProps = { anchorOrigin: { vertical: 'top', horizontal: 'left', }, animated: true, multiple: false, open: null, onItemTouchTap: () => {}, onKeyboardFocus: () => {}, onMouseDown: () => {}, onMouseLeave: () => {}, onMouseEnter: () => {}, onMouseUp: () => {}, onRequestChange: () => {}, onTouchTap: () => {}, targetOrigin: { vertical: 'top', horizontal: 'left', }, touchTapCloseDelay: 200, useLayerForClickAway: false, }; static contextTypes = { muiTheme: PropTypes.object.isRequired, }; state = { menuInitiallyKeyboardFocused: false, open: false, }; componentWillReceiveProps(nextProps) { if (nextProps.open != null) { this.setState({ open: nextProps.open, anchorEl: this.refs.iconMenuContainer, }); } } componentWillUnmount() { clearTimeout(this.timerCloseId); } isOpen() { return this.state.open; } close(reason, isKeyboard) { if (!this.state.open) { return; } if (this.props.open !== null) { this.props.onRequestChange(false, reason); } else { this.setState({open: false}, () => { // Set focus on the icon button when the menu close if (isKeyboard) { const iconButton = this.refs.iconButton; ReactDOM.findDOMNode(iconButton).focus(); iconButton.setKeyboardFocus(); } }); } } open(reason, event) { if (this.props.open !== null) { this.props.onRequestChange(true, reason); return this.setState({ menuInitiallyKeyboardFocused: Events.isKeyboard(event), anchorEl: event.currentTarget, }); } this.setState({ open: true, menuInitiallyKeyboardFocused: Events.isKeyboard(event), anchorEl: event.currentTarget, }); event.preventDefault(); } handleItemTouchTap = (event, child) => { if (this.props.touchTapCloseDelay !== 0 && !child.props.hasOwnProperty('menuItems')) { const isKeyboard = Events.isKeyboard(event); this.timerCloseId = setTimeout(() => { this.close(isKeyboard ? 'enter' : 'itemTap', isKeyboard); }, this.props.touchTapCloseDelay); } this.props.onItemTouchTap(event, child); }; handleRequestClose = (reason) => { this.close(reason); }; handleEscKeyDownMenu = (event) => { this.close('escape', event); }; render() { const { anchorOrigin, className, animated, animation, iconButtonElement, iconStyle, onItemTouchTap, // eslint-disable-line no-unused-vars onKeyboardFocus, onMouseDown, onMouseLeave, onMouseEnter, onMouseUp, onRequestChange, // eslint-disable-line no-unused-vars onTouchTap, listStyle, menuStyle, style, targetOrigin, touchTapCloseDelay, // eslint-disable-line no-unused-vars useLayerForClickAway, ...other } = this.props; const {prepareStyles} = this.context.muiTheme; const {open, anchorEl} = this.state; const styles = { root: { display: 'inline-block', position: 'relative', }, menu: { position: 'relative', }, }; const mergedRootStyles = Object.assign(styles.root, style); const mergedMenuStyles = Object.assign(styles.menu, menuStyle); warning(iconButtonElement.type.muiName !== 'SvgIcon', `Material-UI: You shoud not provide an <SvgIcon /> to the 'iconButtonElement' property of <IconMenu />. You should wrapped it with an <IconButton />.`); const iconButtonProps = { onKeyboardFocus: onKeyboardFocus, onTouchTap: (event) => { this.open(Events.isKeyboard(event) ? 'keyboard' : 'iconTap', event); if (iconButtonElement.props.onTouchTap) { iconButtonElement.props.onTouchTap(event); } }, ref: 'iconButton', }; if (iconStyle || iconButtonElement.props.iconStyle) { iconButtonProps.iconStyle = iconStyle ? Object.assign({}, iconStyle, iconButtonElement.props.iconStyle) : iconButtonElement.props.iconStyle; } const iconButton = React.cloneElement(iconButtonElement, iconButtonProps); const menu = ( <Menu {...other} initiallyKeyboardFocused={this.state.menuInitiallyKeyboardFocused} onEscKeyDown={this.handleEscKeyDownMenu} onItemTouchTap={this.handleItemTouchTap} style={mergedMenuStyles} listStyle={listStyle} > {this.props.children} </Menu> ); return ( <div ref="iconMenuContainer" className={className} onMouseDown={onMouseDown} onMouseLeave={onMouseLeave} onMouseEnter={onMouseEnter} onMouseUp={onMouseUp} onTouchTap={onTouchTap} style={prepareStyles(mergedRootStyles)} > {iconButton} <Popover anchorOrigin={anchorOrigin} targetOrigin={targetOrigin} open={open} anchorEl={anchorEl} childContextTypes={this.constructor.childContextTypes} useLayerForClickAway={useLayerForClickAway} onRequestClose={this.handleRequestClose} animated={animated} animation={animation} context={this.context} > {menu} </Popover> </div> ); } } export default IconMenu;
var openCenteredPopup = function(url, width, height) { var screenX = typeof window.screenX !== 'undefined' ? window.screenX : window.screenLeft; var screenY = typeof window.screenY !== 'undefined' ? window.screenY : window.screenTop; var outerWidth = typeof window.outerWidth !== 'undefined' ? window.outerWidth : document.body.clientWidth; var outerHeight = typeof window.outerHeight !== 'undefined' ? window.outerHeight : (document.body.clientHeight - 22); // XXX what is the 22? // Use `outerWidth - width` and `outerHeight - height` for help in // positioning the popup centered relative to the current window var left = screenX + (outerWidth - width) / 2; var top = screenY + (outerHeight - height) / 2; var features = ('width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',scrollbars=yes'); var newwindow = window.open(url, 'Login', features); if (newwindow.focus) { newwindow.focus(); } return newwindow; }; Meteor.loginWithCas = function(options, callback) { options = options || {}; var credentialToken = Random.id(); var login_url = RocketChat.settings.get('CAS_login_url'); var popup_width = RocketChat.settings.get('CAS_popup_width'); var popup_height = RocketChat.settings.get('CAS_popup_height'); if (!login_url) { return; } var loginUrl = login_url + '?service=' + Meteor.absoluteUrl('_cas/') + credentialToken; var popup = openCenteredPopup( loginUrl, popup_width || 800, popup_height || 600 ); var checkPopupOpen = setInterval(function() { var popupClosed; try { // Fix for #328 - added a second test criteria (popup.closed === undefined) // to humour this Android quirk: // http://code.google.com/p/android/issues/detail?id=21061 popupClosed = popup.closed || popup.closed === undefined; } catch (e) { // For some unknown reason, IE9 (and others?) sometimes (when // the popup closes too quickly?) throws "SCRIPT16386: No such // interface supported" when trying to read 'popup.closed'. Try // again in 100ms. return; } if (popupClosed) { clearInterval(checkPopupOpen); // check auth on server. Accounts.callLoginMethod({ methodArguments: [{ cas: { credentialToken: credentialToken } }], userCallback: callback }); } }, 100); };
declare class T {} declare class U {} declare var o1: {...{[string]:T},...{p:U}}; (o1: {p?:T|U,[string]:T}); // ok declare var o2: {...{p:T},...{[string]:U}}; (o2: {p?:T|U,[string]:U}); // ok declare var o3: {...{[string]:T},...{[string]:U}}; (o3: {[string]:T|U}); // ok declare var o4: {...{|[string]:T|},...{p:U}}; (o4: {p?:T|U,[string]:T}); // ok declare var o5: {...{|p:T|},...{[string]:U}}; (o5: {p:T|U,[string]:U}); // ok declare var o6: {...{|[string]:T|},...{[string]:U}}; (o6: {[string]:T|U}); // ok declare var o7: {...{[string]:T},...{|p:U|}}; (o7: {p:U,[string]:T}); // ok declare var o8: {...{p:T},...{|[string]:U|}}; (o8: {p?:T|U,[string]:U}); // ok declare var o9: {...{[string]:T},...{|[string]:U|}}; (o9: {[string]:T|U}); // ok declare var o10: {|...{|[string]:T|},...{|p:U|}|}; (o10: {|p:U,[string]:T|}); // ok declare var o11: {|...{|p :T|},...{|[string]:U|}|}; (o11: {|p:T|U,[string]:U|}); // ok declare var o12: {|...{|[string]:T|},...{|[string]:U|}|}; (o12: {|[string]:T|U|}); // ok
jest.dontMock('../src/date_input.jsx'); describe('DateInput', function() { var React, TestUtils, DateInput; beforeEach(function() { React = require('react/addons'); TestUtils = React.addons.TestUtils; DateInput = require('../src/date_input.jsx'); }); it('triggers an event handler when the Enter key is pressed', function() { var dateMock = { format: function(){} }; var handlerCalled = false; var enterHandler = function() { handlerCalled = true; }; runs(function(){ var dateInput = TestUtils.renderIntoDocument( <DateInput date={dateMock} handleEnter={enterHandler} /> ); TestUtils.Simulate.keyDown(dateInput.getDOMNode(), {key: "Enter"}); }); waitsFor(function(){ return handlerCalled; }, 'Enter handler is not called', 1000); }); });
import PageManager from '../page-manager'; import $ from 'jquery'; import nod from './common/nod'; import giftCertChecker from './common/gift-certificate-validator'; import formModel from './common/models/forms'; import { api } from '@bigcommerce/stencil-utils'; import { defaultModal } from './global/modal'; export default class GiftCertificate extends PageManager { constructor() { super(); const $certBalanceForm = $('#gift-certificate-balance'); const purchaseModel = { recipientName(val) { return val.length; }, recipientEmail(...args) { return formModel.email(...args); }, senderName(val) { return val.length; }, senderEmail(...args) { return formModel.email(...args); }, customAmount(value, min, max) { return value && value >= min && value <= max; }, setAmount(value, options) { let found = false; options.forEach((option) => { if (option === value) { found = true; return false; } }); return found; }, }; const $purchaseForm = $('#gift-certificate-form'); const $customAmounts = $purchaseForm.find('input[name="certificate_amount"]'); const purchaseValidator = nod({ submit: '#gift-certificate-form input[type="submit"]', delay: 300, }); if ($customAmounts.length) { const $element = $purchaseForm.find('input[name="certificate_amount"]'); const min = $element.data('min'); const minFormatted = $element.data('min-formatted'); const max = $element.data('max'); const maxFormatted = $element.data('max-formatted'); purchaseValidator.add({ selector: '#gift-certificate-form input[name="certificate_amount"]', validate: (cb, val) => { const numberVal = Number(val); if (!numberVal) { cb(false); } cb(numberVal >= min && numberVal <= max); }, errorMessage: `You must enter a certificate amount between ${minFormatted} and ${maxFormatted}.`, }); } purchaseValidator.add([ { selector: '#gift-certificate-form input[name="to_name"]', validate: (cb, val) => { const result = purchaseModel.recipientName(val); cb(result); }, errorMessage: 'You must enter a valid recipient name.', }, { selector: '#gift-certificate-form input[name="to_email"]', validate: (cb, val) => { const result = purchaseModel.recipientEmail(val); cb(result); }, errorMessage: 'You must enter a valid recipient email.', }, { selector: '#gift-certificate-form input[name="from_name"]', validate: (cb, val) => { const result = purchaseModel.senderName(val); cb(result); }, errorMessage: 'You must enter your name.', }, { selector: '#gift-certificate-form input[name="from_email"]', validate: (cb, val) => { const result = purchaseModel.senderEmail(val); cb(result); }, errorMessage: 'You must enter a valid email.', }, { selector: '#gift-certificate-form input[name="certificate_theme"]:first-of-type', triggeredBy: '#gift-certificate-form input[name="certificate_theme"]', validate: (cb) => { const val = $purchaseForm.find('input[name="certificate_theme"]:checked').val(); cb(typeof(val) === 'string'); }, errorMessage: 'You must select a gift certificate theme.', }, { selector: '#gift-certificate-form input[name="agree"]', validate: (cb) => { const val = $purchaseForm.find('input[name="agree"]').get(0).checked; cb(val); }, errorMessage: 'You must agree to these terms.', }, { selector: '#gift-certificate-form input[name="agree2"]', validate: (cb) => { const val = $purchaseForm.find('input[name="agree2"]').get(0).checked; cb(val); }, errorMessage: 'You must agree to these terms.', }, ]); if ($certBalanceForm.length) { const balanceVal = this.checkCertBalanceValidator($certBalanceForm); $certBalanceForm.submit(() => { balanceVal.performCheck(); if (!balanceVal.areAll('valid')) { return false; } }); } $purchaseForm.submit((event) => { purchaseValidator.performCheck(); if (!purchaseValidator.areAll('valid')) { return event.preventDefault(); } }); $('#gift-certificate-preview').click((event) => { event.preventDefault(); purchaseValidator.performCheck(); if (!purchaseValidator.areAll('valid')) { return; } const modal = defaultModal(); const previewUrl = `${$(event.currentTarget).data('preview-url')}&${$purchaseForm.serialize()}`; modal.open(); api.getPage(previewUrl, {}, (err, content) => { if (err) { return modal.updateContent(this.context.previewError); } modal.updateContent(content, { wrap: true }); }); }); } checkCertBalanceValidator($balanceForm) { const balanceValidator = nod({ submit: $balanceForm.find('input[type="submit"]'), }); balanceValidator.add({ selector: $balanceForm.find('input[name="giftcertificatecode"]'), validate(cb, val) { cb(giftCertChecker(val)); }, errorMessage: 'You must enter a certificate code.', }); return balanceValidator; } }
/* * Timepicker for Jeditable * * Copyright (c) 2008-2009 Mika Tuupola * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Project home: * http://www.appelsiini.net/projects/jeditable * * Revision: $Id$ * */ $.editable.addInputType('time', { /* Create input element. */ element : function(settings, original) { /* Create and pulldowns for hours and minutes. Append them to */ /* form which is accessible as variable this. */ var hourselect = $('<select id="hour_" />'); var minselect = $('<select id="min_" />'); for (var hour=0; hour <= 23; hour++) { if (hour < 10) { hour = '0' + hour; } var option = $('<option />').val(hour).append(hour); hourselect.append(option); } $(this).append(hourselect); for (var min=0; min <= 45; min = parseInt(min, 10) + 15) { if (min < 10) { min = '0' + min; } var option = $('<option />').val(min).append(min); minselect.append(option); } $(this).append(minselect); /* Last create an hidden input. This is returned to plugin. It will */ /* later hold the actual value which will be submitted to server. */ var hidden = $('<input type="hidden" />'); $(this).append(hidden); return(hidden); }, /* Set content / value of previously created input element. */ content : function(string, settings, original) { /* Select correct hour and minute in pulldowns. */ var hour = parseInt(string.substr(0,2), 10); var min = parseInt(string.substr(3,2), 10); $('#hour_', this).children().each(function() { if (hour == $(this).val()) { $(this).attr('selected', 'selected'); } }); $('#min_', this).children().each(function() { if (min == $(this).val()) { $(this).attr('selected', 'selected'); } }); }, /* Call before submit hook. */ submit: function (settings, original) { /* Take values from hour and minute pulldowns. Create string such as */ /* 13:45 from them. Set value of the hidden input field to this string. */ var value = $('#hour_').val() + ':' + $('#min_').val(); $('input', this).val(value); } });
/* This file is part of Ext JS 4.2 Copyright (c) 2011-2013 Sencha Inc Contact: http://www.sencha.com/contact Commercial Usage Licensees holding valid commercial licenses may use this file in accordance with the Commercial Software License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Sencha. If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact. Build date: 2013-09-18 17:18:59 (940c324ac822b840618a3a8b2b4b873f83a1a9b1) */ /** * The {@link Ext.direct.RemotingProvider RemotingProvider} exposes access to * server side methods on the client (a remote procedure call (RPC) type of * connection where the client can initiate a procedure on the server). * * This allows for code to be organized in a fashion that is maintainable, * while providing a clear path between client and server, something that is * not always apparent when using URLs. * * To accomplish this the server-side needs to describe what classes and methods * are available on the client-side. This configuration will typically be * outputted by the server-side Ext.Direct stack when the API description is built. */ Ext.define('Ext.direct.RemotingProvider', { extend: 'Ext.direct.JsonProvider', alias: 'direct.remotingprovider', requires: [ 'Ext.util.MixedCollection', 'Ext.util.DelayedTask', 'Ext.direct.Transaction', 'Ext.direct.RemotingMethod' ], /** * @cfg {Object} actions * * Object literal defining the server side actions and methods. For example, if * the Provider is configured with: * * // each property within the 'actions' object represents a server side Class * actions: { * TestAction: [ // array of methods within each server side Class to be * { // stubbed out on client * name: 'doEcho', // stub method will be TestAction.doEcho * len: 1 * }, { * name: 'multiply', // name of method * len: 2 // The number of parameters that will be used to create an * // array of data to send to the server side function. * }, { * name: 'doForm', * formHandler: true // tells the client that this method handles form calls * }], * * // These methods will be created in nested namespace TestAction.Foo * 'TestAction.Foo': [{ * name: 'ordered', // stub method will be TestAction.Foo.ordered * len: 1 * }, { * name: 'noParams', // this method does not accept any parameters * len: 0 * }, { * name: 'named', // stub method will be TestAction.Foo.named * params: ['foo', 'bar'] // parameters are passed by name * }] * } * * Note that starting with 4.2, dotted Action names will generate nested objects. * If you wish to reverse to previous behavior, set {@link #cfg-disableNestedActions} * to `true`. * * In the following example a *client side* handler is used to call the * server side method "multiply" in the server-side "TestAction" Class: * * TestAction.multiply( * // pass two arguments to server, so specify len=2 * 2, 4, * * // callback function after the server is called * // result: the result returned by the server * // e: Ext.direct.RemotingEvent object * // success: true or false * // options: options to be applied to method call and passed to callback * function (result, e, success, options) { * var t, action, method; * * t = e.getTransaction(); * action = t.action; // server side Class called * method = t.method; // server side method called * * if (e.status) { * var answer = Ext.encode(result); // 8 * } * else { * var msg = e.message; // failure message * } * }, * * // Scope to call the callback in (optional) * window, * * // Options to apply to this method call. This can include * // Ajax.request() options; only `timeout` is supported at this time. * // When timeout is set for a method call, it will be executed immediately * // without buffering. * // The same options object is passed to the callback so it's possible * // to "forward" some data when needed. * { * timeout: 60000, // milliseconds * foo: 'bar' * } * ); * * In the example above, the server side "multiply" function will be passed two * arguments (2 and 4). The "multiply" method should return the value 8 which will be * available as the `result` in the callback example above. */ /** * @cfg {Boolean} [disableNestedActions=false] * In versions prior to 4.2, using dotted Action names was not really meaningful, * because it generated flat {@link #cfg-namespace} object with dotted property names. * For example, take this API declaration: * * { * actions: { * TestAction: [{ * name: 'foo', * len: 1 * }], * 'TestAction.Foo' [{ * name: 'bar', * len: 1 * }] * }, * namespace: 'MyApp' * } * * Before 4.2, that would generate the following API object: * * window.MyApp = { * TestAction: { * foo: function() { ... } * }, * 'TestAction.Foo': { * bar: function() { ... } * } * } * * In Ext JS 4.2, we introduced new namespace handling behavior. Now the same API object * will be like this: * * window.MyApp = { * TestAction: { * foo: function() { ... }, * * Foo: { * bar: function() { ... } * } * } * } * * Instead of addressing Action methods array-style `MyApp['TestAction.Foo'].bar()`, * now it is possible to use object addressing: `MyApp.TestAction.Foo.bar()`. * * If you find this behavior undesirable, set this config option to `true`. */ /** * @cfg {String/Object} namespace * * Namespace for the Remoting Provider (defaults to `Ext.global`). * Explicitly specify the namespace Object, or specify a String to have a * {@link Ext#namespace namespace} created implicitly. */ /** * @cfg {String} url * * **Required**. The url to connect to the {@link Ext.direct.Manager} server-side router. */ /** * @cfg {String} [enableUrlEncode=data] * * Specify which param will hold the arguments for the method. */ /** * @cfg {Number/Boolean} [enableBuffer=10] * * `true` or `false` to enable or disable combining of method * calls. If a number is specified this is the amount of time in milliseconds * to wait before sending a batched request. * * Calls which are received within the specified timeframe will be * concatenated together and sent in a single request, optimizing the * application by reducing the amount of round trips that have to be made * to the server. To cancel buffering for some particular invocations, pass * `timeout` parameter in `options` object for that method call. */ enableBuffer: 10, /** * @cfg {Number} [maxRetries=1] * * Number of times to re-attempt delivery on failure of a call. */ maxRetries: 1, /** * @cfg {Number} [timeout] * * The timeout to use for each request. */ constructor: function(config) { var me = this; me.callParent(arguments); me.addEvents( /** * @event beforecall * @preventable * * Fires immediately before the client-side sends off the RPC call. By returning * `false` from an event handler you can prevent the call from being made. * * @param {Ext.direct.RemotingProvider} provider * @param {Ext.direct.Transaction} transaction * @param {Object} meta The meta data */ 'beforecall', /** * @event call * * Fires immediately after the request to the server-side is sent. This does * NOT fire after the response has come back from the call. * * @param {Ext.direct.RemotingProvider} provider * @param {Ext.direct.Transaction} transaction * @param {Object} meta The meta data */ 'call', /** * @event beforecallback * @preventable * * Fires before callback function is executed. By returning `false` from an event handler * you can prevent the callback from executing. * * @param {Ext.direct.RemotingProvider} provider * @param {Ext.direct.Transaction} transaction */ 'beforecallback' ); me.namespace = (Ext.isString(me.namespace)) ? Ext.ns(me.namespace) : me.namespace || Ext.global; me.transactions = new Ext.util.MixedCollection(); me.callBuffer = []; }, /** * Get nested namespace by property. * * @private */ getNamespace: function(root, action) { var parts, ns, i, l; root = root || Ext.global; parts = action.toString().split('.'); for (i = 0, l = parts.length; i < l; i++) { ns = parts[i]; root = root[ns]; if (typeof root === 'undefined') { return root; } } return root; }, /** * Create nested namespaces. Unlike {@link Ext#ns} this method supports * nested objects as root of the namespace, not only Ext.global (window). * * @private */ createNamespaces: function(root, action) { var parts, ns; root = root || Ext.global; parts = action.toString().split('.'); for ( var i = 0, l = parts.length; i < l; i++ ) { ns = parts[i]; root[ns] = root[ns] || {}; root = root[ns]; }; return root; }, /** * Initialize the API * * @private */ initAPI: function() { var me = this, actions = me.actions, namespace = me.namespace, action, cls, methods, i, len, method; for (action in actions) { if (actions.hasOwnProperty(action)) { if (me.disableNestedActions) { cls = namespace[action]; if (!cls) { cls = namespace[action] = {}; } } else { cls = me.getNamespace(namespace, action); if (!cls) { cls = me.createNamespaces(namespace, action); } } methods = actions[action]; for (i = 0, len = methods.length; i < len; ++i) { method = new Ext.direct.RemotingMethod(methods[i]); cls[method.name] = me.createHandler(action, method); } } } }, /** * Create a handler function for a direct call. * * @param {String} action The action the call is for * @param {Object} method The details of the method * * @return {Function} A JS function that will kick off the call * * @private */ createHandler: function(action, method) { var me = this, slice = Array.prototype.slice, handler; if (!method.formHandler) { handler = function() { me.configureRequest(action, method, slice.call(arguments, 0)); }; } else { handler = function(form, callback, scope) { me.configureFormRequest(action, method, form, callback, scope); }; } handler.directCfg = { action: action, method: method }; return handler; }, /** * @inheritdoc */ isConnected: function() { return !!this.connected; }, /** * @inheritdoc */ connect: function() { var me = this; if (me.url) { me.initAPI(); me.connected = true; me.fireEvent('connect', me); } //<debug> else if (!me.url) { Ext.Error.raise('Error initializing RemotingProvider "' + me.id + '", no url configured.'); } //</debug> }, /** * @inheritdoc */ disconnect: function() { var me = this; if (me.connected) { me.connected = false; me.fireEvent('disconnect', me); } }, /** * Run any callbacks related to the transaction. * * @param {Ext.direct.Transaction} transaction The transaction * @param {Ext.direct.Event} event The event * * @private */ runCallback: function(transaction, event) { var success = !!event.status, funcName = success ? 'success' : 'failure', callback, options, result; if (transaction && transaction.callback) { callback = transaction.callback; options = transaction.callbackOptions; result = typeof event.result !== 'undefined' ? event.result : event.data; if (Ext.isFunction(callback)) { callback(result, event, success, options); } else { Ext.callback(callback[funcName], callback.scope, [result, event, success, options]); Ext.callback(callback.callback, callback.scope, [result, event, success, options]); } } }, /** * React to the ajax request being completed * * @private */ onData: function(options, success, response) { var me = this, i, len, events, event, transaction, transactions; if (success) { events = me.createEvents(response); for (i = 0, len = events.length; i < len; ++i) { event = events[i]; transaction = me.getTransaction(event); me.fireEvent('data', me, event); if (transaction && me.fireEvent('beforecallback', me, event, transaction) !== false) { me.runCallback(transaction, event, true); Ext.direct.Manager.removeTransaction(transaction); } } } else { transactions = [].concat(options.transaction); for (i = 0, len = transactions.length; i < len; ++i) { transaction = me.getTransaction(transactions[i]); if (transaction && transaction.retryCount < me.maxRetries) { transaction.retry(); } else { event = new Ext.direct.ExceptionEvent({ data: null, transaction: transaction, code: Ext.direct.Manager.exceptions.TRANSPORT, message: 'Unable to connect to the server.', xhr: response }); me.fireEvent('data', me, event); if (transaction && me.fireEvent('beforecallback', me, transaction) !== false) { me.runCallback(transaction, event, false); Ext.direct.Manager.removeTransaction(transaction); } } } } }, /** * Get transaction from XHR options * * @param {Object} options The options sent to the Ajax request * * @return {Ext.direct.Transaction} The transaction, null if not found * * @private */ getTransaction: function(options) { return options && options.tid ? Ext.direct.Manager.getTransaction(options.tid) : null; }, /** * Configure a direct request * * @param {String} action The action being executed * @param {Object} method The being executed * * @private */ configureRequest: function(action, method, args) { var me = this, callData, data, callback, scope, opts, transaction, params; callData = method.getCallData(args); data = callData.data; callback = callData.callback; scope = callData.scope; opts = callData.options || {}; params = Ext.apply({}, { provider: me, args: args, action: action, method: method.name, data: data, callbackOptions: opts, callback: scope && Ext.isFunction(callback) ? Ext.Function.bind(callback, scope) : callback }); if (opts.timeout) { Ext.applyIf(params, { timeout: opts.timeout }); }; transaction = new Ext.direct.Transaction(params); if (me.fireEvent('beforecall', me, transaction, method) !== false) { Ext.direct.Manager.addTransaction(transaction); me.queueTransaction(transaction); me.fireEvent('call', me, transaction, method); } }, /** * Gets the Ajax call info for a transaction * * @param {Ext.direct.Transaction} transaction The transaction * * @return {Object} The call params * * @private */ getCallData: function(transaction) { return { action: transaction.action, method: transaction.method, data: transaction.data, type: 'rpc', tid: transaction.id }; }, /** * Sends a request to the server * * @param {Object/Array} data The data to send * * @private */ sendRequest: function(data) { var me = this, request, callData, params, enableUrlEncode = me.enableUrlEncode, i, len; request = { url: me.url, callback: me.onData, scope: me, transaction: data, timeout: me.timeout }; // Explicitly specified timeout for Ext.Direct call overrides defaults if (data.timeout) { request.timeout = data.timeout; } if (Ext.isArray(data)) { callData = []; for (i = 0, len = data.length; i < len; ++i) { callData.push(me.getCallData(data[i])); } } else { callData = me.getCallData(data); } if (enableUrlEncode) { params = {}; params[Ext.isString(enableUrlEncode) ? enableUrlEncode : 'data'] = Ext.encode(callData); request.params = params; } else { request.jsonData = callData; } Ext.Ajax.request(request); }, /** * Add a new transaction to the queue * * @param {Ext.direct.Transaction} transaction The transaction * * @private */ queueTransaction: function(transaction) { var me = this, enableBuffer = me.enableBuffer; if (transaction.form) { me.sendFormRequest(transaction); return; } if (enableBuffer === false || typeof transaction.timeout !== 'undefined') { me.sendRequest(transaction); return; } me.callBuffer.push(transaction); if (enableBuffer) { if (!me.callTask) { me.callTask = new Ext.util.DelayedTask(me.combineAndSend, me); } me.callTask.delay(Ext.isNumber(enableBuffer) ? enableBuffer : 10); } else { me.combineAndSend(); } }, /** * Combine any buffered requests and send them off * * @private */ combineAndSend : function() { var me = this, buffer = me.callBuffer, len = buffer.length; if (len > 0) { me.sendRequest(len == 1 ? buffer[0] : buffer); me.callBuffer = []; } }, /** * Configure a form submission request * * @param {String} action The action being executed * @param {Object} method The method being executed * @param {HTMLElement} form The form being submitted * @param {Function} [callback] A callback to run after the form submits * @param {Object} [scope] A scope to execute the callback in * * @private */ configureFormRequest: function(action, method, form, callback, scope) { var me = this, transaction, isUpload, params; transaction = new Ext.direct.Transaction({ provider: me, action: action, method: method.name, args: [form, callback, scope], callback: scope && Ext.isFunction(callback) ? Ext.Function.bind(callback, scope) : callback, isForm: true }); if (me.fireEvent('beforecall', me, transaction, method) !== false) { Ext.direct.Manager.addTransaction(transaction); isUpload = String(form.getAttribute("enctype")).toLowerCase() == 'multipart/form-data'; params = { extTID: transaction.id, extAction: action, extMethod: method.name, extType: 'rpc', extUpload: String(isUpload) }; // change made from typeof callback check to callback.params // to support addl param passing in DirectSubmit EAC 6/2 Ext.apply(transaction, { form: Ext.getDom(form), isUpload: isUpload, params: callback && Ext.isObject(callback.params) ? Ext.apply(params, callback.params) : params }); me.fireEvent('call', me, transaction, method); me.sendFormRequest(transaction); } }, /** * Sends a form request * * @param {Ext.direct.Transaction} transaction The transaction to send * * @private */ sendFormRequest: function(transaction) { var me = this; Ext.Ajax.request({ url: me.url, params: transaction.params, callback: me.onData, scope: me, form: transaction.form, isUpload: transaction.isUpload, transaction: transaction }); } });
/* YUI 3.5.0 (build 5089) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and * the core utilities for the library. * @module yui * @submodule yui-base */ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** The YUI global namespace object. If YUI is already defined, the existing YUI object will not be overwritten so that defined namespaces are preserved. It is the constructor for the object the end user interacts with. As indicated below, each instance has full custom event support, but only if the event system is available. This is a self-instantiable factory function. You can invoke it directly like this: YUI().use('*', function(Y) { // ready }); But it also works like this: var Y = YUI(); Configuring the YUI object: YUI({ debug: true, combine: false }).use('node', function(Y) { //Node is ready to use }); See the API docs for the <a href="config.html">Config</a> class for the complete list of supported configuration properties accepted by the YUI constuctor. @class YUI @constructor @global @uses EventTarget @param [o]* {Object} 0..n optional configuration objects. these values are store in Y.config. See <a href="config.html">Config</a> for the list of supported properties. */ /*global YUI*/ /*global YUI_config*/ var YUI = function() { var i = 0, Y = this, args = arguments, l = args.length, instanceOf = function(o, type) { return (o && o.hasOwnProperty && (o instanceof type)); }, gconf = (typeof YUI_config !== 'undefined') && YUI_config; if (!(instanceOf(Y, YUI))) { Y = new YUI(); } else { // set up the core environment Y._init(); /** YUI.GlobalConfig is a master configuration that might span multiple contexts in a non-browser environment. It is applied first to all instances in all contexts. @property GlobalConfig @type {Object} @global @static @example YUI.GlobalConfig = { filter: 'debug' }; YUI().use('node', function(Y) { //debug files used here }); YUI({ filter: 'min' }).use('node', function(Y) { //min files used here }); */ if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } /** YUI_config is a page-level config. It is applied to all instances created on the page. This is applied after YUI.GlobalConfig, and before the instance level configuration objects. @global @property YUI_config @type {Object} @example //Single global var to include before YUI seed file YUI_config = { filter: 'debug' }; YUI().use('node', function(Y) { //debug files used here }); YUI({ filter: 'min' }).use('node', function(Y) { //min files used here }); */ if (gconf) { Y.applyConfig(gconf); } // bind the specified additional modules for this instance if (!l) { Y._setup(); } } if (l) { // Each instance can accept one or more configuration objects. // These are applied after YUI.GlobalConfig and YUI_Config, // overriding values set in those config files if there is a ' // matching property. for (; i < l; i++) { Y.applyConfig(args[i]); } Y._setup(); } Y.instanceOf = instanceOf; return Y; }; (function() { var proto, prop, VERSION = '3.5.0', PERIOD = '.', BASE = 'http://yui.yahooapis.com/', DOC_LABEL = 'yui3-js-enabled', CSS_STAMP_EL = 'yui3-css-stamp', NOOP = function() {}, SLICE = Array.prototype.slice, APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo 'io.xdrResponse': 1, // can call. this should 'SWF.eventHandler': 1 }, // be done at build time hasWin = (typeof window != 'undefined'), win = (hasWin) ? window : null, doc = (hasWin) ? win.document : null, docEl = doc && doc.documentElement, docClass = docEl && docEl.className, instances = {}, time = new Date().getTime(), add = function(el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function(el, type, fn, capture) { if (el && el.removeEventListener) { // this can throw an uncaught exception in FF try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, handleLoad = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; if (hasWin) { remove(window, 'load', handleLoad); } }, getLoader = function(Y, o) { var loader = Y.Env._loader; if (loader) { //loader._config(Y.config); loader.ignoreRegistered = false; loader.onEnd = null; loader.data = null; loader.required = []; loader.loadType = null; } else { loader = new Y.Loader(Y.config); Y.Env._loader = loader; } YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, [ 'loader-base', 'loader-rollup', 'loader-yui3' ])); return loader; }, clobber = function(r, s) { for (var i in s) { if (s.hasOwnProperty(i)) { r[i] = s[i]; } } }, ALREADY_DONE = { success: true }; // Stamp the documentElement (HTML) with a class of "yui-loaded" to // enable styles that need to key off of JS being enabled. if (docEl && docClass.indexOf(DOC_LABEL) == -1) { if (docClass) { docClass += ' '; } docClass += DOC_LABEL; docEl.className = docClass; } if (VERSION.indexOf('@') > -1) { VERSION = '3.3.0'; // dev time hack for cdn test } proto = { /** * Applies a new configuration object to the YUI instance config. * This will merge new group/module definitions, and will also * update the loader cache if necessary. Updating Y.config directly * will not update the cache. * @method applyConfig * @param {Object} o the configuration object. * @since 3.2.0 */ applyConfig: function(o) { o = o || NOOP; var attr, name, // detail, config = this.config, mods = config.modules, groups = config.groups, aliases = config.aliases, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (aliases && name == 'aliases') { clobber(aliases, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (name == 'win') { config[name] = (attr && attr.contentWindow) || attr; config.doc = config[name] ? config[name].document : null; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, /** * Old way to apply a config to the instance (calls `applyConfig` under the hood) * @private * @method _config * @param {Object} o The config to apply */ _config: function(o) { this.applyConfig(o); }, /** * Initialize this YUI instance * @private * @method _init */ _init: function() { var filter, el, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** * The version number of the YUI instance. * @property version * @type string */ Y.version = VERSION; if (!Env) { Y.Env = { core: ['get','features','intl-base','yui-log','yui-later'], mods: {}, // flat module map versions: {}, // version module map base: BASE, cdn: BASE + VERSION + '/build/', // bootstrapped: false, _idx: 0, _used: {}, _attached: {}, _missed: [], _yidx: 0, _uidx: 0, _guidp: 'y', _loaded: {}, // serviced: {}, // Regex in English: // I'll start at the \b(simpleyui). // 1. Look in the test string for "simpleyui" or "yui" or // "yui-base" or "yui-davglass" or "yui-foobar" that comes after a word break. That is, it // can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string. // 2. After #1 must come a forward slash followed by the string matched in #1, so // "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants". // 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min", // so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt". // 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js" // 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string, // then capture the junk between the LAST "&" and the string in 1-4. So // "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-davglass/yui-davglass.js" // will capture "3.3.0/build/" // // Regex Exploded: // (?:\? Find a ? // (?:[^&]*&) followed by 0..n characters followed by an & // * in fact, find as many sets of characters followed by a & as you can // ([^&]*) capture the stuff after the last & in \1 // )? but it's ok if all this ?junk&more_junk stuff isn't even there // \b(simpleyui| after a word break find either the string "simpleyui" or // yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters // ) and store the simpleyui or yui-* string in \2 // \/\2 then comes a / followed by the simpleyui or yui-* string in \2 // (?:-(min|debug))? optionally followed by "-min" or "-debug" // .js and ending in ".js" _BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/, parseBasePath: function(src, pattern) { var match = src.match(pattern), path, filter; if (match) { path = RegExp.leftContext || src.slice(0, src.indexOf(match[0])); // this is to set up the path to the loader. The file // filter for loader should match the yui include. filter = match[3]; // extract correct path for mixed combo urls // http://yuilibrary.com/projects/yui3/ticket/2528423 if (match[1]) { path += '?' + match[1]; } path = { filter: filter, path: path } } return path; }, getBase: G_ENV && G_ENV.getBase || function(pattern) { var nodes = (doc && doc.getElementsByTagName('script')) || [], path = Env.cdn, parsed, i, len, src; for (i = 0, len = nodes.length; i < len; ++i) { src = nodes[i].src; if (src) { parsed = Y.Env.parseBasePath(src, pattern); if (parsed) { filter = parsed.filter; path = parsed.path; break; } } } // use CDN default return path; } }; Env = Y.Env; Env._loaded[VERSION] = {}; if (G_ENV && Y !== YUI) { Env._yidx = ++G_ENV._yidx; Env._guidp = ('yui_' + VERSION + '_' + Env._yidx + '_' + time).replace(/\./g, '_'); } else if (YUI._YUI) { G_ENV = YUI._YUI.Env; Env._yidx += G_ENV._yidx; Env._uidx += G_ENV._uidx; for (prop in G_ENV) { if (!(prop in Env)) { Env[prop] = G_ENV[prop]; } } delete YUI._YUI; } Y.id = Y.stamp(Y); instances[Y.id] = Y; } Y.constructor = YUI; // configuration defaults Y.config = Y.config || { bootstrap: true, cacheUse: true, debug: true, doc: doc, fetchCSS: true, throwFail: true, useBrowserConsole: true, useNativeES5: true, win: win }; //Register the CSS stamp element if (doc && !doc.getElementById(CSS_STAMP_EL)) { el = doc.createElement('div'); el.innerHTML = '<div id="' + CSS_STAMP_EL + '" style="position: absolute !important; visibility: hidden !important"></div>'; YUI.Env.cssStampEl = el.firstChild; docEl.insertBefore(YUI.Env.cssStampEl, docEl.firstChild); } Y.config.lang = Y.config.lang || 'en-US'; Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE); if (!filter || (!('mindebug').indexOf(filter))) { filter = 'min'; } filter = (filter) ? '-' + filter : filter; Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js'; }, /** * Finishes the instance setup. Attaches whatever modules were defined * when the yui modules was registered. * @method _setup * @private */ _setup: function(o) { var i, Y = this, core = [], mods = YUI.Env.mods, //extras = Y.config.core || ['get','features','intl-base','yui-log','yui-later']; extras = Y.config.core || [].concat(YUI.Env.core); //Clone it.. for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); if (Y.Loader) { getLoader(Y); } // Y.log(Y.id + ' initialized', 'info', 'yui'); }, /** * Executes a method on a YUI instance with * the specified id if the specified method is whitelisted. * @method applyTo * @param id {String} the YUI instance id. * @param method {String} the name of the method to exectute. * Ex: 'Object.keys'. * @param args {Array} the arguments to apply to the method. * @return {Object} the return value from the applied method or null. */ applyTo: function(id, method, args) { if (!(method in APPLY_TO_AUTH)) { this.log(method + ': applyTo not allowed', 'warn', 'yui'); return null; } var instance = instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i = 0; i < nest.length; i = i + 1) { m = m[nest[i]]; if (!m) { this.log('applyTo not found: ' + method, 'warn', 'yui'); } } return m && m.apply(instance, args); } return null; }, /** Registers a module with the YUI global. The easiest way to create a first-class YUI module is to use the YUI component build tool. http://yuilibrary.com/projects/builder The build system will produce the `YUI.add` wrapper for you module, along with any configuration info required for the module. @method add @param name {String} module name. @param fn {Function} entry point into the module that is used to bind module to the YUI instance. @param {YUI} fn.Y The YUI instance this module is executed in. @param {String} fn.name The name of the module @param version {String} version string. @param details {Object} optional config data: @param details.requires {Array} features that must be present before this module can be attached. @param details.optional {Array} optional features that should be present if loadOptional is defined. Note: modules are not often loaded this way in YUI 3, but this field is still useful to inform the user that certain features in the component will require additional dependencies. @param details.use {Array} features that are included within this module which need to be attached automatically when this module is attached. This supports the YUI 3 rollup system -- a module with submodules defined will need to have the submodules listed in the 'use' config. The YUI component build tool does this for you. @return {YUI} the YUI instance. @example YUI.add('davglass', function(Y, name) { Y.davglass = function() { alert('Dav was here!'); }; }, '3.4.0', { requires: ['yui-base', 'harley-davidson', 'mt-dew'] }); */ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, loader, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { loader = instances[i].Env._loader; if (loader) { if (!loader.moduleInfo[name] || loader.moduleInfo[name].temp) { loader.addModule(details, name); } } } } return this; }, /** * Executes the function associated with each required * module, binding the module to the YUI instance. * @param {Array} r The array of modules to attach * @param {Boolean} [moot=false] Don't throw a warning if the module is not attached * @method _attach * @private */ _attach: function(r, moot) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, aliases = YUI.Env.aliases, Y = this, j, loader = Y.Env._loader, done = Y.Env._attached, len = r.length, loader, c = []; //Check for conditional modules (in a second+ instance) and add their requirements //TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass for (i = 0; i < len; i++) { name = r[i]; mod = mods[name]; c.push(name); if (loader && loader.conditions[name]) { Y.Object.each(loader.conditions[name], function(def) { var go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y))); if (go) { c.push(def.name); } }); } } r = c; len = r.length; for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name]) { Y._attach(aliases[name]); continue; } if (!mod) { if (loader && loader.moduleInfo[name]) { mod = loader.moduleInfo[name]; moot = true; } // Y.log('no js def for: ' + name, 'info', 'yui'); //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot && name) { if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) { Y.Env._missed.push(name); Y.Env._missed = Y.Array.dedupe(Y.Env._missed); Y.message('NOT loaded: ' + name, 'warn', 'yui'); } } } else { done[name] = true; //Don't like this, but in case a mod was asked for once, then we fetch it //We need to remove it from the missed list ^davglass for (j = 0; j < Y.Env._missed.length; j++) { if (Y.Env._missed[j] === name) { Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui'); Y.Env._missed.splice(j, 1); } } details = mod.details; req = details.requires; use = details.use; after = details.after; if (req) { for (j = 0; j < req.length; j++) { if (!done[req[j]]) { if (!Y._attach(req)) { return false; } break; } } } if (after) { for (j = 0; j < after.length; j++) { if (!done[after[j]]) { if (!Y._attach(after, true)) { return false; } break; } } } if (mod.fn) { try { mod.fn(Y, name); } catch (e) { Y.error('Attach error: ' + name, e, name); return false; } } if (use) { for (j = 0; j < use.length; j++) { if (!done[use[j]]) { if (!Y._attach(use)) { return false; } break; } } } } } } return true; }, /** * Attaches one or more modules to the YUI instance. When this * is executed, the requirements are analyzed, and one of * several things can happen: * * * All requirements are available on the page -- The modules * are attached to the instance. If supplied, the use callback * is executed synchronously. * * * Modules are missing, the Get utility is not available OR * the 'bootstrap' config is false -- A warning is issued about * the missing modules and all available modules are attached. * * * Modules are missing, the Loader is not available but the Get * utility is and boostrap is not false -- The loader is bootstrapped * before doing the following.... * * * Modules are missing and the Loader is available -- The loader * expands the dependency tree and fetches missing modules. When * the loader is finshed the callback supplied to use is executed * asynchronously. * * @method use * @param modules* {String|Array} 1-n modules to bind (uses arguments array). * @param [callback] {Function} callback function executed when * the instance has the required functionality. If included, it * must be the last parameter. * @param callback.Y {YUI} The `YUI` instance created for this sandbox * @param callback.data {Object} Object data returned from `Loader`. * * @example * // loads and attaches dd and its dependencies * YUI().use('dd', function(Y) {}); * * // loads and attaches dd and node as well as all of their dependencies (since 3.4.0) * YUI().use(['dd', 'node'], function(Y) {}); * * // attaches all modules that are available on the page * YUI().use('*', function(Y) {}); * * // intrinsic YUI gallery support (since 3.1.0) * YUI().use('gallery-yql', function(Y) {}); * * // intrinsic YUI 2in3 support (since 3.1.0) * YUI().use('yui2-datatable', function(Y) {}); * * @return {YUI} the YUI instance. */ use: function() { var args = SLICE.call(arguments, 0), callback = args[args.length - 1], Y = this, i = 0, a = [], name, Env = Y.Env, provisioned = true; // The last argument supplied to use can be a load complete callback if (Y.Lang.isFunction(callback)) { args.pop(); } else { callback = null; } if (Y.Lang.isArray(args[0])) { args = args[0]; } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { Y.log('already provisioned: ' + args, 'info', 'yui'); } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y._loading) { Y._useQueue = Y._useQueue || new Y.Queue(); Y._useQueue.add([args, callback]); } else { Y._use(args, function(Y, response) { Y._notify(callback, response, args); }); } return Y; }, /** * Notify handler from Loader for attachment/load errors * @method _notify * @param callback {Function} The callback to pass to the `Y.config.loadErrorFn` * @param response {Object} The response returned from Loader * @param args {Array} The aruments passed from Loader * @private */ _notify: function(callback, response, args) { if (!response.success && this.config.loadErrorFn) { this.config.loadErrorFn.call(this, this, callback, response, args); } else if (callback) { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } }, /** * This private method is called from the `use` method queue. To ensure that only one set of loading * logic is performed at a time. * @method _use * @private * @param args* {String} 1-n modules to bind (uses arguments array). * @param *callback {Function} callback function executed when * the instance has the required functionality. If included, it * must be the last parameter. */ _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, handleRLS, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, aliases = G_ENV.aliases, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { var i = 0, a = []; if (!names.length) { return; } if (aliases) { for (i = 0; i < names.length; i++) { if (aliases[names[i]]) { a = [].concat(a, aliases[names[i]]); } else { a.push(names[i]); } } names = a; } YArray.each(names, function(name) { // add this module to full list of things to attach if (!skip) { r.push(name); } // only attach a module once if (used[name]) { return; } var m = mods[name], req, use; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has // been loaded if (!G_ENV._loaded[VERSION][name]) { missing.push(name); } else { used[name] = true; // probably css } } // make sure requirements are attached if (req && req.length) { process(req); } // make sure we grab the submodule dependencies too if (use && use.length) { process(use, 1); } }); }, handleLoader = function(fromLoader) { var response = fromLoader || { success: true, msg: 'not dynamic' }, redo, origMissing, ret = true, data = response.data; Y._loading = false; if (data) { origMissing = missing; missing = []; r = []; process(data); redo = missing.length; if (redo) { if (missing.sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = true; Y._use(missing, function() { Y.log('Nested use callback: ' + data, 'info', 'yui'); if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { // Y.log('attaching from loader: ' + data, 'info', 'yui'); ret = Y._attach(data); } if (ret) { Y._notify(callback, response, args); } } if (Y._useQueue && Y._useQueue.size() && !Y._loading) { Y._use.apply(Y, Y._useQueue.next()); } }; // Y.log(Y.id + ': use called: ' + a + ' :: ' + callback, 'info', 'yui'); // YUI().use('*'); // bind everything available if (firstArg === '*') { ret = Y._attach(Y.Object.keys(mods)); if (ret) { handleLoader(); } return Y; } if (mods['loader'] && !Y.Loader) { Y.log('Loader was found in meta, but it is not attached. Attaching..', 'info', 'yui'); Y._attach(['loader']); } // Y.log('before loader requirements: ' + args, 'info', 'yui'); // use loader to expand dependencies and sort the // requirements if it is available. if (boot && Y.Loader && args.length) { loader = getLoader(Y); loader.require(args); loader.ignoreRegistered = true; loader._boot = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; loader._boot = false; } // process each requirement and any additional requirements // the module metadata specifies process(args); len = missing.length; if (len) { missing = Y.Object.keys(YArray.hash(missing)); len = missing.length; Y.log('Modules missing: ' + missing + ', ' + missing.length, 'info', 'yui'); } // dynamic load if (boot && len && Y.Loader) { // Y.log('Using loader to fetch missing deps: ' + missing, 'info', 'yui'); Y.log('Using Loader', 'info', 'yui'); Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(args); loader.insert(null, (fetchCSS) ? null : 'js'); } else if (boot && len && Y.Get && !Env.bootstrapped) { Y._loading = true; handleBoot = function() { Y._loading = false; queue.running = false; Env.bootstrapped = true; G_ENV._bootstrapping = false; if (Y._attach(['loader'])) { Y._use(args, callback); } }; if (G_ENV._bootstrapping) { Y.log('Waiting for loader', 'info', 'yui'); queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.log('Fetching loader: ' + config.base + config.loaderPath, 'info', 'yui'); Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { Y.log('Attaching available dependencies: ' + args, 'info', 'yui'); ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** Adds a namespace object onto the YUI global if called statically. // creates YUI.your.namespace.here as nested objects YUI.namespace("your.namespace.here"); If called as a method on a YUI <em>instance</em>, it creates the namespace on the instance. // creates Y.property.package Y.namespace("property.package"); Dots in the input string cause `namespace` to create nested objects for each token. If any part of the requested namespace already exists, the current object will be left in place. This allows multiple calls to `namespace` to preserve existing namespaced properties. If the first token in the namespace string is "YAHOO", the token is discarded. Be careful with namespace tokens. Reserved words may work in some browsers and not others. For instance, the following will fail in some browsers because the supported version of JavaScript reserves the word "long": Y.namespace("really.long.nested.namespace"); <em>Note: If you pass multiple arguments to create multiple namespaces, only the last one created is returned from this function.</em> @method namespace @param {String} namespace* namespaces to create. @return {Object} A reference to the last namespace object created. **/ namespace: function() { var a = arguments, o, i = 0, j, d, arg; for (; i < a.length; i++) { o = this; //Reset base object per argument or it will get reused from the last arg = a[i]; if (arg.indexOf(PERIOD) > -1) { //Skip this if no "." is present d = arg.split(PERIOD); for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } else { o[arg] = o[arg] || {}; o = o[arg]; //Reset base object to the new object so it's returned } } return o; }, // this is replaced if the log module is included log: NOOP, message: NOOP, // this is replaced if the dump module is included dump: function (o) { return ''+o; }, /** * Report an error. The reporting mechanism is controlled by * the `throwFail` configuration attribute. If throwFail is * not specified, the message is written to the Logger, otherwise * a JS error is thrown. If an `errorFn` is specified in the config * it must return `true` to keep the error from being thrown. * @method error * @param msg {String} the error message. * @param e {Error|String} Optional JS error that was caught, or an error string. * @param src Optional additional info (passed to `Y.config.errorFn` and `Y.message`) * and `throwFail` is specified, this error will be re-thrown. * @return {YUI} this YUI instance. */ error: function(msg, e, src) { //TODO Add check for window.onerror here var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (Y.config.throwFail && !ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error', ''+src); // don't scrub this one } return Y; }, /** * Generate an id that is unique among all YUI instances * @method guid * @param pre {String} optional guid prefix. * @return {String} the guid. */ guid: function(pre) { var id = this.Env._guidp + '_' + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** * Returns a `guid` associated with an object. If the object * does not have one, a new one is created unless `readOnly` * is specified. * @method stamp * @param o {Object} The object to stamp. * @param readOnly {Boolean} if `true`, a valid guid will only * be returned if the object has one assigned to it. * @return {String} The object's guid or null. */ stamp: function(o, readOnly) { var uid; if (!o) { return o; } // IE generates its own unique ID for dom nodes // The uniqueID property of a document node returns a new ID if (o.uniqueID && o.nodeType && o.nodeType !== 9) { uid = o.uniqueID; } else { uid = (typeof o === 'string') ? o : o._yuid; } if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch (e) { uid = null; } } } return uid; }, /** * Destroys the YUI instance * @method destroy * @since 3.3.0 */ destroy: function() { var Y = this; if (Y.Event) { Y.Event._unload(); } delete instances[Y.id]; delete Y.Env; delete Y.config; } /** * instanceof check for objects that works around * memory leak in IE when the item tested is * window/document * @method instanceOf * @param o {Object} The object to check. * @param type {Object} The class to check against. * @since 3.3.0 */ }; YUI.prototype = proto; // inheritance utilities are not available yet for (prop in proto) { if (proto.hasOwnProperty(prop)) { YUI[prop] = proto[prop]; } } /** Static method on the Global YUI object to apply a config to all YUI instances. It's main use case is "mashups" where several third party scripts are trying to write to a global YUI config at the same time. This way they can all call `YUI.applyConfig({})` instead of overwriting other scripts configs. @static @since 3.5.0 @method applyConfig @param {Object} o the configuration object. @example YUI.applyConfig({ modules: { davglass: { fullpath: './davglass.js' } } }); YUI.applyConfig({ modules: { foo: { fullpath: './foo.js' } } }); YUI().use('davglass', function(Y) { //Module davglass will be available here.. }); */ YUI.applyConfig = function(o) { if (!o) { return; } //If there is a GlobalConfig, apply it first to set the defaults if (YUI.GlobalConfig) { this.prototype.applyConfig.call(this, YUI.GlobalConfig); } //Apply this config to it this.prototype.applyConfig.call(this, o); //Reset GlobalConfig to the combined config YUI.GlobalConfig = this.config; }; // set up the environment YUI._init(); if (hasWin) { // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', handleLoad); } else { handleLoad(); } YUI.Env.add = add; YUI.Env.remove = remove; /*global exports*/ // Support the CommonJS method for exporting our single global if (typeof exports == 'object') { exports.YUI = YUI; } }()); /** * The config object contains all of the configuration options for * the `YUI` instance. This object is supplied by the implementer * when instantiating a `YUI` instance. Some properties have default * values if they are not supplied by the implementer. This should * not be updated directly because some values are cached. Use * `applyConfig()` to update the config object on a YUI instance that * has already been configured. * * @class config * @static */ /** * Allows the YUI seed file to fetch the loader component and library * metadata to dynamically load additional dependencies. * * @property bootstrap * @type boolean * @default true */ /** * Turns on writing Ylog messages to the browser console. * * @property debug * @type boolean * @default true */ /** * Log to the browser console if debug is on and the browser has a * supported console. * * @property useBrowserConsole * @type boolean * @default true */ /** * A hash of log sources that should be logged. If specified, only * log messages from these sources will be logged. * * @property logInclude * @type object */ /** * A hash of log sources that should be not be logged. If specified, * all sources are logged if not on this list. * * @property logExclude * @type object */ /** * Set to true if the yui seed file was dynamically loaded in * order to bootstrap components relying on the window load event * and the `domready` custom event. * * @property injected * @type boolean * @default false */ /** * If `throwFail` is set, `Y.error` will generate or re-throw a JS Error. * Otherwise the failure is logged. * * @property throwFail * @type boolean * @default true */ /** * The window/frame that this instance should operate in. * * @property win * @type Window * @default the window hosting YUI */ /** * The document associated with the 'win' configuration. * * @property doc * @type Document * @default the document hosting YUI */ /** * A list of modules that defines the YUI core (overrides the default list). * * @property core * @type Array * @default [ get,features,intl-base,yui-log,yui-later,loader-base, loader-rollup, loader-yui3 ] */ /** * A list of languages in order of preference. This list is matched against * the list of available languages in modules that the YUI instance uses to * determine the best possible localization of language sensitive modules. * Languages are represented using BCP 47 language tags, such as "en-GB" for * English as used in the United Kingdom, or "zh-Hans-CN" for simplified * Chinese as used in China. The list can be provided as a comma-separated * list or as an array. * * @property lang * @type string|string[] */ /** * The default date format * @property dateFormat * @type string * @deprecated use configuration in `DataType.Date.format()` instead. */ /** * The default locale * @property locale * @type string * @deprecated use `config.lang` instead. */ /** * The default interval when polling in milliseconds. * @property pollInterval * @type int * @default 20 */ /** * The number of dynamic nodes to insert by default before * automatically removing them. This applies to script nodes * because removing the node will not make the evaluated script * unavailable. Dynamic CSS is not auto purged, because removing * a linked style sheet will also remove the style definitions. * @property purgethreshold * @type int * @default 20 */ /** * The default interval when polling in milliseconds. * @property windowResizeDelay * @type int * @default 40 */ /** * Base directory for dynamic loading * @property base * @type string */ /* * The secure base dir (not implemented) * For dynamic loading. * @property secureBase * @type string */ /** * The YUI combo service base dir. Ex: `http://yui.yahooapis.com/combo?` * For dynamic loading. * @property comboBase * @type string */ /** * The root path to prepend to module path for the combo service. * Ex: 3.0.0b1/build/ * For dynamic loading. * @property root * @type string */ /** * A filter to apply to result urls. This filter will modify the default * path for all modules. The default path for the YUI library is the * minified version of the files (e.g., event-min.js). The filter property * can be a predefined filter or a custom filter. The valid predefined * filters are: * <dl> * <dt>DEBUG</dt> * <dd>Selects the debug versions of the library (e.g., event-debug.js). * This option will automatically include the Logger widget</dd> * <dt>RAW</dt> * <dd>Selects the non-minified version of the library (e.g., event.js).</dd> * </dl> * You can also define a custom filter, which must be an object literal * containing a search expression and a replace string: * * myFilter: { * 'searchExp': "-min\\.js", * 'replaceStr': "-debug.js" * } * * For dynamic loading. * * @property filter * @type string|object */ /** * The `skin` config let's you configure application level skin * customizations. It contains the following attributes which * can be specified to override the defaults: * * // The default skin, which is automatically applied if not * // overriden by a component-specific skin definition. * // Change this in to apply a different skin globally * defaultSkin: 'sam', * * // This is combined with the loader base property to get * // the default root directory for a skin. * base: 'assets/skins/', * * // Any component-specific overrides can be specified here, * // making it possible to load different skins for different * // components. It is possible to load more than one skin * // for a given component as well. * overrides: { * slider: ['capsule', 'round'] * } * * For dynamic loading. * * @property skin */ /** * Hash of per-component filter specification. If specified for a given * component, this overrides the filter config. * * For dynamic loading. * * @property filters */ /** * Use the YUI combo service to reduce the number of http connections * required to load your dependencies. Turning this off will * disable combo handling for YUI and all module groups configured * with a combo service. * * For dynamic loading. * * @property combine * @type boolean * @default true if 'base' is not supplied, false if it is. */ /** * A list of modules that should never be dynamically loaded * * @property ignore * @type string[] */ /** * A list of modules that should always be loaded when required, even if already * present on the page. * * @property force * @type string[] */ /** * Node or id for a node that should be used as the insertion point for new * nodes. For dynamic loading. * * @property insertBefore * @type string */ /** * Object literal containing attributes to add to dynamically loaded script * nodes. * @property jsAttributes * @type string */ /** * Object literal containing attributes to add to dynamically loaded link * nodes. * @property cssAttributes * @type string */ /** * Number of milliseconds before a timeout occurs when dynamically * loading nodes. If not set, there is no timeout. * @property timeout * @type int */ /** * Callback for the 'CSSComplete' event. When dynamically loading YUI * components with CSS, this property fires when the CSS is finished * loading but script loading is still ongoing. This provides an * opportunity to enhance the presentation of a loading page a little * bit before the entire loading process is done. * * @property onCSS * @type function */ /** * A hash of module definitions to add to the list of YUI components. * These components can then be dynamically loaded side by side with * YUI via the `use()` method. This is a hash, the key is the module * name, and the value is an object literal specifying the metdata * for the module. See `Loader.addModule` for the supported module * metadata fields. Also see groups, which provides a way to * configure the base and combo spec for a set of modules. * * modules: { * mymod1: { * requires: ['node'], * fullpath: '/mymod1/mymod1.js' * }, * mymod2: { * requires: ['mymod1'], * fullpath: '/mymod2/mymod2.js' * }, * mymod3: '/js/mymod3.js', * mycssmod: '/css/mycssmod.css' * } * * * @property modules * @type object */ /** * Aliases are dynamic groups of modules that can be used as * shortcuts. * * YUI({ * aliases: { * davglass: [ 'node', 'yql', 'dd' ], * mine: [ 'davglass', 'autocomplete'] * } * }).use('mine', function(Y) { * //Node, YQL, DD &amp; AutoComplete available here.. * }); * * @property aliases * @type object */ /** * A hash of module group definitions. It for each group you * can specify a list of modules and the base path and * combo spec to use when dynamically loading the modules. * * groups: { * yui2: { * // specify whether or not this group has a combo service * combine: true, * * // The comboSeperator to use with this group's combo handler * comboSep: ';', * * // The maxURLLength for this server * maxURLLength: 500, * * // the base path for non-combo paths * base: 'http://yui.yahooapis.com/2.8.0r4/build/', * * // the path to the combo service * comboBase: 'http://yui.yahooapis.com/combo?', * * // a fragment to prepend to the path attribute when * // when building combo urls * root: '2.8.0r4/build/', * * // the module definitions * modules: { * yui2_yde: { * path: "yahoo-dom-event/yahoo-dom-event.js" * }, * yui2_anim: { * path: "animation/animation.js", * requires: ['yui2_yde'] * } * } * } * } * * @property groups * @type object */ /** * The loader 'path' attribute to the loader itself. This is combined * with the 'base' attribute to dynamically load the loader component * when boostrapping with the get utility alone. * * @property loaderPath * @type string * @default loader/loader-min.js */ /** * Specifies whether or not YUI().use(...) will attempt to load CSS * resources at all. Any truthy value will cause CSS dependencies * to load when fetching script. The special value 'force' will * cause CSS dependencies to be loaded even if no script is needed. * * @property fetchCSS * @type boolean|string * @default true */ /** * The default gallery version to build gallery module urls * @property gallery * @type string * @since 3.1.0 */ /** * The default YUI 2 version to build yui2 module urls. This is for * intrinsic YUI 2 support via the 2in3 project. Also see the '2in3' * config for pulling different revisions of the wrapped YUI 2 * modules. * @since 3.1.0 * @property yui2 * @type string * @default 2.9.0 */ /** * The 2in3 project is a deployment of the various versions of YUI 2 * deployed as first-class YUI 3 modules. Eventually, the wrapper * for the modules will change (but the underlying YUI 2 code will * be the same), and you can select a particular version of * the wrapper modules via this config. * @since 3.1.0 * @property 2in3 * @type string * @default 4 */ /** * Alternative console log function for use in environments without * a supported native console. The function is executed in the * YUI instance context. * @since 3.1.0 * @property logFn * @type Function */ /** * A callback to execute when Y.error is called. It receives the * error message and an javascript error object if Y.error was * executed because a javascript error was caught. The function * is executed in the YUI instance context. Returning `true` from this * function will stop the Error from being thrown. * * @since 3.2.0 * @property errorFn * @type Function */ /** * A callback to execute when the loader fails to load one or * more resource. This could be because of a script load * failure. It can also fail if a javascript module fails * to register itself, but only when the 'requireRegistration' * is true. If this function is defined, the use() callback will * only be called when the loader succeeds, otherwise it always * executes unless there was a javascript error when attaching * a module. * * @since 3.3.0 * @property loadErrorFn * @type Function */ /** * When set to true, the YUI loader will expect that all modules * it is responsible for loading will be first-class YUI modules * that register themselves with the YUI global. If this is * set to true, loader will fail if the module registration fails * to happen after the script is loaded. * * @since 3.3.0 * @property requireRegistration * @type boolean * @default false */ /** * Cache serviced use() requests. * @since 3.3.0 * @property cacheUse * @type boolean * @default true * @deprecated no longer used */ /** * Whether or not YUI should use native ES5 functionality when available for * features like `Y.Array.each()`, `Y.Object()`, etc. When `false`, YUI will * always use its own fallback implementations instead of relying on ES5 * functionality, even when it's available. * * @method useNativeES5 * @type Boolean * @default true * @since 3.5.0 */ YUI.add('yui-base', function(Y) { /* * YUI stub * @module yui * @submodule yui-base */ /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Provides core language utilites and extensions used throughout YUI. * * @class Lang * @static */ var L = Y.Lang || (Y.Lang = {}), STRING_PROTO = String.prototype, TOSTRING = Object.prototype.toString, TYPES = { 'undefined' : 'undefined', 'number' : 'number', 'boolean' : 'boolean', 'string' : 'string', '[object Function]': 'function', '[object RegExp]' : 'regexp', '[object Array]' : 'array', '[object Date]' : 'date', '[object Error]' : 'error' }, SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g, TRIMREGEX = /^\s+|\s+$/g, NATIVE_FN_REGEX = /\{\s*\[(?:native code|function)\]\s*\}/i; // -- Protected Methods -------------------------------------------------------- /** Returns `true` if the given function appears to be implemented in native code, `false` otherwise. Will always return `false` -- even in ES5-capable browsers -- if the `useNativeES5` YUI config option is set to `false`. This isn't guaranteed to be 100% accurate and won't work for anything other than functions, but it can be useful for determining whether a function like `Array.prototype.forEach` is native or a JS shim provided by another library. There's a great article by @kangax discussing certain flaws with this technique: <http://perfectionkills.com/detecting-built-in-host-methods/> While his points are valid, it's still possible to benefit from this function as long as it's used carefully and sparingly, and in such a way that false negatives have minimal consequences. It's used internally to avoid using potentially broken non-native ES5 shims that have been added to the page by other libraries. @method _isNative @param {Function} fn Function to test. @return {Boolean} `true` if _fn_ appears to be native, `false` otherwise. @static @protected @since 3.5.0 **/ L._isNative = function (fn) { return !!(Y.config.useNativeES5 && fn && NATIVE_FN_REGEX.test(fn)); }; // -- Public Methods ----------------------------------------------------------- /** * Determines whether or not the provided item is an array. * * Returns `false` for array-like collections such as the function `arguments` * collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to * test for an array-like collection. * * @method isArray * @param o The object to test. * @return {boolean} true if o is an array. * @static */ L.isArray = L._isNative(Array.isArray) ? Array.isArray : function (o) { return L.type(o) === 'array'; }; /** * Determines whether or not the provided item is a boolean. * @method isBoolean * @static * @param o The object to test. * @return {boolean} true if o is a boolean. */ L.isBoolean = function(o) { return typeof o === 'boolean'; }; /** * Determines whether or not the supplied item is a date instance. * @method isDate * @static * @param o The object to test. * @return {boolean} true if o is a date. */ L.isDate = function(o) { return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o); }; /** * <p> * Determines whether or not the provided item is a function. * Note: Internet Explorer thinks certain functions are objects: * </p> * * <pre> * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * &nbsp; * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * </pre> * * <p> * You will have to implement additional tests if these functions * matter to you. * </p> * * @method isFunction * @static * @param o The object to test. * @return {boolean} true if o is a function. */ L.isFunction = function(o) { return L.type(o) === 'function'; }; /** * Determines whether or not the provided item is null. * @method isNull * @static * @param o The object to test. * @return {boolean} true if o is null. */ L.isNull = function(o) { return o === null; }; /** * Determines whether or not the provided item is a legal number. * @method isNumber * @static * @param o The object to test. * @return {boolean} true if o is a number. */ L.isNumber = function(o) { return typeof o === 'number' && isFinite(o); }; /** * Determines whether or not the provided item is of type object * or function. Note that arrays are also objects, so * <code>Y.Lang.isObject([]) === true</code>. * @method isObject * @static * @param o The object to test. * @param failfn {boolean} fail if the input is a function. * @return {boolean} true if o is an object. * @see isPlainObject */ L.isObject = function(o, failfn) { var t = typeof o; return (o && (t === 'object' || (!failfn && (t === 'function' || L.isFunction(o))))) || false; }; /** * Determines whether or not the provided item is a string. * @method isString * @static * @param o The object to test. * @return {boolean} true if o is a string. */ L.isString = function(o) { return typeof o === 'string'; }; /** * Determines whether or not the provided item is undefined. * @method isUndefined * @static * @param o The object to test. * @return {boolean} true if o is undefined. */ L.isUndefined = function(o) { return typeof o === 'undefined'; }; /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @static * @param o The item to test. * @return {boolean} true if it is not null/undefined/NaN || false. */ L.isValue = function(o) { var t = L.type(o); switch (t) { case 'number': return isFinite(o); case 'null': // fallthru case 'undefined': return false; default: return !!t; } }; /** * Returns the current time in milliseconds. * * @method now * @return {Number} Current time in milliseconds. * @static * @since 3.3.0 */ L.now = Date.now || function () { return new Date().getTime(); }; /** * Lightweight version of <code>Y.substitute</code>. Uses the same template * structure as <code>Y.substitute</code>, but doesn't support recursion, * auto-object coersion, or formats. * @method sub * @param {string} s String to be modified. * @param {object} o Object containing replacement values. * @return {string} the substitute result. * @static * @since 3.2.0 */ L.sub = function(s, o) { return s.replace ? s.replace(SUBREGEX, function (match, key) { return L.isUndefined(o[key]) ? match : o[key]; }) : s; }; /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trim = STRING_PROTO.trim ? function(s) { return s && s.trim ? s.trim() : s; } : function (s) { try { return s.replace(TRIMREGEX, ''); } catch (e) { return s; } }; /** * Returns a string without any leading whitespace. * @method trimLeft * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimLeft = STRING_PROTO.trimLeft ? function (s) { return s.trimLeft(); } : function (s) { return s.replace(/^\s+/, ''); }; /** * Returns a string without any trailing whitespace. * @method trimRight * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimRight = STRING_PROTO.trimRight ? function (s) { return s.trimRight(); } : function (s) { return s.replace(/\s+$/, ''); }; /** Returns one of the following strings, representing the type of the item passed in: * "array" * "boolean" * "date" * "error" * "function" * "null" * "number" * "object" * "regexp" * "string" * "undefined" Known issues: * `typeof HTMLElementCollection` returns function in Safari, but `Y.Lang.type()` reports "object", which could be a good thing -- but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. @method type @param o the item to test. @return {string} the detected type. @static **/ L.type = function(o) { return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null'); }; /** @module yui @submodule yui-base */ var Lang = Y.Lang, Native = Array.prototype, hasOwn = Object.prototype.hasOwnProperty; /** Provides utility methods for working with arrays. Additional array helpers can be found in the `collection` and `array-extras` modules. `Y.Array(thing)` returns a native array created from _thing_. Depending on _thing_'s type, one of the following will happen: * Arrays are returned unmodified unless a non-zero _startIndex_ is specified. * Array-like collections (see `Array.test()`) are converted to arrays. * For everything else, a new array is created with _thing_ as the sole item. Note: elements that are also collections, such as `<form>` and `<select>` elements, are not automatically converted to arrays. To force a conversion, pass `true` as the value of the _force_ parameter. @class Array @constructor @param {Any} thing The thing to arrayify. @param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like collection, a subset of items starting at the specified index will be returned. @param {Boolean} [force=false] If `true`, _thing_ will be treated as an array-like collection no matter what. @return {Array} A native array created from _thing_, according to the rules described above. **/ function YArray(thing, startIndex, force) { var len, result; startIndex || (startIndex = 0); if (force || YArray.test(thing)) { // IE throws when trying to slice HTMLElement collections. try { return Native.slice.call(thing, startIndex); } catch (ex) { result = []; for (len = thing.length; startIndex < len; ++startIndex) { result.push(thing[startIndex]); } return result; } } return [thing]; } Y.Array = YArray; /** Dedupes an array of strings, returning an array that's guaranteed to contain only one copy of a given string. This method differs from `Array.unique()` in that it's optimized for use only with strings, whereas `unique` may be used with other types (but is slower). Using `dedupe()` with non-string values may result in unexpected behavior. @method dedupe @param {String[]} array Array of strings to dedupe. @return {Array} Deduped copy of _array_. @static @since 3.4.0 **/ YArray.dedupe = function (array) { var hash = {}, results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hasOwn.call(hash, item)) { hash[item] = 1; results.push(item); } } return results; }; /** Executes the supplied function on each item in the array. This method wraps the native ES5 `Array.forEach()` method if available. @method each @param {Array} array Array to iterate. @param {Function} fn Function to execute on each item in the array. The function will receive the following arguments: @param {Any} fn.item Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {YUI} The YUI instance. @static **/ YArray.each = YArray.forEach = Lang._isNative(Native.forEach) ? function (array, fn, thisObj) { Native.forEach.call(array || [], fn, thisObj || Y); return Y; } : function (array, fn, thisObj) { for (var i = 0, len = (array && array.length) || 0; i < len; ++i) { if (i in array) { fn.call(thisObj || Y, array[i], i, array); } } return Y; }; /** Alias for `each()`. @method forEach @static **/ /** Returns an object using the first array as keys and the second as values. If the second array is not provided, or if it doesn't contain the same number of values as the first array, then `true` will be used in place of the missing values. @example Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']); // => {a: 'foo', b: 'bar', c: true} @method hash @param {String[]} keys Array of strings to use as keys. @param {Array} [values] Array to use as values. @return {Object} Hash using the first array as keys and the second as values. @static **/ YArray.hash = function (keys, values) { var hash = {}, vlen = (values && values.length) || 0, i, len; for (i = 0, len = keys.length; i < len; ++i) { if (i in keys) { hash[keys[i]] = vlen > i && i in values ? values[i] : true; } } return hash; }; /** Returns the index of the first item in the array that's equal (using a strict equality check) to the specified _value_, or `-1` if the value isn't found. This method wraps the native ES5 `Array.indexOf()` method if available. @method indexOf @param {Array} array Array to search. @param {Any} value Value to search for. @param {Number} [from=0] The index at which to begin the search. @return {Number} Index of the item strictly equal to _value_, or `-1` if not found. @static **/ YArray.indexOf = Lang._isNative(Native.indexOf) ? function (array, value, from) { return Native.indexOf.call(array, value, from); } : function (array, value, from) { // http://es5.github.com/#x15.4.4.14 var len = array.length; from = +from || 0; from = (from > 0 || -1) * Math.floor(Math.abs(from)); if (from < 0) { from += len; if (from < 0) { from = 0; } } for (; from < len; ++from) { if (from in array && array[from] === value) { return from; } } return -1; }; /** Numeric sort convenience function. The native `Array.prototype.sort()` function converts values to strings and sorts them in lexicographic order, which is unsuitable for sorting numeric values. Provide `Array.numericSort` as a custom sort function when you want to sort values in numeric order. @example [42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort); // => [4, 8, 15, 16, 23, 42] @method numericSort @param {Number} a First value to compare. @param {Number} b Second value to compare. @return {Number} Difference between _a_ and _b_. @static **/ YArray.numericSort = function (a, b) { return a - b; }; /** Executes the supplied function on each item in the array. Returning a truthy value from the function will stop the processing of remaining items. @method some @param {Array} array Array to iterate over. @param {Function} fn Function to execute on each item. The function will receive the following arguments: @param {Any} fn.value Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated over. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {Boolean} `true` if the function returns a truthy value on any of the items in the array; `false` otherwise. @static **/ YArray.some = Lang._isNative(Native.some) ? function (array, fn, thisObj) { return Native.some.call(array, fn, thisObj); } : function (array, fn, thisObj) { for (var i = 0, len = array.length; i < len; ++i) { if (i in array && fn.call(thisObj, array[i], i, array)) { return true; } } return false; }; /** Evaluates _obj_ to determine if it's an array, an array-like collection, or something else. This is useful when working with the function `arguments` collection and `HTMLElement` collections. Note: This implementation doesn't consider elements that are also collections, such as `<form>` and `<select>`, to be array-like. @method test @param {Object} obj Object to test. @return {Number} A number indicating the results of the test: * 0: Neither an array nor an array-like collection. * 1: Real array. * 2: Array-like collection. @static **/ YArray.test = function (obj) { var result = 0; if (Lang.isArray(obj)) { result = 1; } else if (Lang.isObject(obj)) { try { // indexed, but no tagName (element) or alert (window), // or functions without apply/call (Safari // HTMLElementCollection bug). if ('length' in obj && !obj.tagName && !obj.alert && !obj.apply) { result = 2; } } catch (ex) {} } return result; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * A simple FIFO queue. Items are added to the Queue with add(1..n items) and * removed using next(). * * @class Queue * @constructor * @param {MIXED} item* 0..n items to seed the queue. */ function Queue() { this._init(); this.add.apply(this, arguments); } Queue.prototype = { /** * Initialize the queue * * @method _init * @protected */ _init: function() { /** * The collection of enqueued items * * @property _q * @type Array * @protected */ this._q = []; }, /** * Get the next item in the queue. FIFO support * * @method next * @return {MIXED} the next item in the queue. */ next: function() { return this._q.shift(); }, /** * Get the last in the queue. LIFO support. * * @method last * @return {MIXED} the last item in the queue. */ last: function() { return this._q.pop(); }, /** * Add 0..n items to the end of the queue. * * @method add * @param {MIXED} item* 0..n items. * @return {object} this queue. */ add: function() { this._q.push.apply(this._q, arguments); return this; }, /** * Returns the current number of queued items. * * @method size * @return {Number} The size. */ size: function() { return this._q.length; } }; Y.Queue = Queue; YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue(); /** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @submodule yui-base **/ var CACHED_DELIMITER = '__', hasOwn = Object.prototype.hasOwnProperty, isObject = Y.Lang.isObject; /** Returns a wrapper for a function which caches the return value of that function, keyed off of the combined string representation of the argument values provided when the wrapper is called. Calling this function again with the same arguments will return the cached value rather than executing the wrapped function. Note that since the cache is keyed off of the string representation of arguments passed to the wrapper function, arguments that aren't strings and don't provide a meaningful `toString()` method may result in unexpected caching behavior. For example, the objects `{}` and `{foo: 'bar'}` would both be converted to the string `[object Object]` when used as a cache key. @method cached @param {Function} source The function to memoize. @param {Object} [cache={}] Object in which to store cached values. You may seed this object with pre-existing cached values if desired. @param {any} [refetch] If supplied, this value is compared with the cached value using a `==` comparison. If the values are equal, the wrapped function is executed again even though a cached value exists. @return {Function} Wrapped function. @for YUI **/ Y.cached = function (source, cache, refetch) { cache || (cache = {}); return function (arg) { var key = arguments.length > 1 ? Array.prototype.join.call(arguments, CACHED_DELIMITER) : String(arg); if (!(key in cache) || (refetch && cache[key] == refetch)) { cache[key] = source.apply(source, arguments); } return cache[key]; }; }; /** Returns the `location` object from the window/frame in which this YUI instance operates, or `undefined` when executing in a non-browser environment (e.g. Node.js). It is _not_ recommended to hold references to the `window.location` object outside of the scope of a function in which its properties are being accessed or its methods are being called. This is because of a nasty bug/issue that exists in both Safari and MobileSafari browsers: [WebKit Bug 34679](https://bugs.webkit.org/show_bug.cgi?id=34679). @method getLocation @return {location} The `location` object from the window/frame in which this YUI instance operates. @since 3.5.0 **/ Y.getLocation = function () { // It is safer to look this up every time because yui-base is attached to a // YUI instance before a user's config is applied; i.e. `Y.config.win` does // not point the correct window object when this file is loaded. var win = Y.config.win; // It is not safe to hold a reference to the `location` object outside the // scope in which it is being used. The WebKit engine used in Safari and // MobileSafari will "disconnect" the `location` object from the `window` // when a page is restored from back/forward history cache. return win && win.location; }; /** Returns a new object containing all of the properties of all the supplied objects. The properties from later objects will overwrite those in earlier objects. Passing in a single object will create a shallow copy of it. For a deep copy, use `clone()`. @method merge @param {Object} objects* One or more objects to merge. @return {Object} A new merged object. **/ Y.merge = function () { var args = arguments, i = 0, len = args.length, result = {}; for (; i < len; ++i) { Y.mix(result, args[i], true); } return result; }; /** Mixes _supplier_'s properties into _receiver_. Properties on _receiver_ or _receiver_'s prototype will not be overwritten or shadowed unless the _overwrite_ parameter is `true`, and will not be merged unless the _merge_ parameter is `true`. In the default mode (0), only properties the supplier owns are copied (prototype properties are not copied). The following copying modes are available: * `0`: _Default_. Object to object. * `1`: Prototype to prototype. * `2`: Prototype to prototype and object to object. * `3`: Prototype to object. * `4`: Object to prototype. @method mix @param {Function|Object} receiver The object or function to receive the mixed properties. @param {Function|Object} supplier The object or function supplying the properties to be mixed. @param {Boolean} [overwrite=false] If `true`, properties that already exist on the receiver will be overwritten with properties from the supplier. @param {String[]} [whitelist] An array of property names to copy. If specified, only the whitelisted properties will be copied, and all others will be ignored. @param {Number} [mode=0] Mix mode to use. See above for available modes. @param {Boolean} [merge=false] If `true`, objects and arrays that already exist on the receiver will have the corresponding object/array from the supplier merged into them, rather than being skipped or overwritten. When both _overwrite_ and _merge_ are `true`, _merge_ takes precedence. @return {Function|Object|YUI} The receiver, or the YUI instance if the specified receiver is falsy. **/ Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) { var alwaysOverwrite, exists, from, i, key, len, to; // If no supplier is given, we return the receiver. If no receiver is given, // we return Y. Returning Y doesn't make much sense to me, but it's // grandfathered in for backcompat reasons. if (!receiver || !supplier) { return receiver || Y; } if (mode) { // In mode 2 (prototype to prototype and object to object), we recurse // once to do the proto to proto mix. The object to object mix will be // handled later on. if (mode === 2) { Y.mix(receiver.prototype, supplier.prototype, overwrite, whitelist, 0, merge); } // Depending on which mode is specified, we may be copying from or to // the prototypes of the supplier and receiver. from = mode === 1 || mode === 3 ? supplier.prototype : supplier; to = mode === 1 || mode === 4 ? receiver.prototype : receiver; // If either the supplier or receiver doesn't actually have a // prototype property, then we could end up with an undefined `from` // or `to`. If that happens, we abort and return the receiver. if (!from || !to) { return receiver; } } else { from = supplier; to = receiver; } // If `overwrite` is truthy and `merge` is falsy, then we can skip a // property existence check on each iteration and save some time. alwaysOverwrite = overwrite && !merge; if (whitelist) { for (i = 0, len = whitelist.length; i < len; ++i) { key = whitelist[i]; // We call `Object.prototype.hasOwnProperty` instead of calling // `hasOwnProperty` on the object itself, since the object's // `hasOwnProperty` method may have been overridden or removed. // Also, some native objects don't implement a `hasOwnProperty` // method. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { // If we're in merge mode, and the key is present on both // objects, and the value on both objects is either an object or // an array (but not a function), then we recurse to merge the // `from` value into the `to` value instead of overwriting it. // // Note: It's intentional that the whitelist isn't passed to the // recursive call here. This is legacy behavior that lots of // code still depends on. Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { // We're not in merge mode, so we'll only copy the `from` value // to the `to` value if we're in overwrite mode or if the // current key doesn't exist on the `to` object. to[key] = from[key]; } } } else { for (key in from) { // The code duplication here is for runtime performance reasons. // Combining whitelist and non-whitelist operations into a single // loop or breaking the shared logic out into a function both result // in worse performance, and Y.mix is critical enough that the byte // tradeoff is worth it. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { to[key] = from[key]; } } // If this is an IE browser with the JScript enumeration bug, force // enumeration of the buggy properties by making a recursive call with // the buggy properties as the whitelist. if (Y.Object._hasEnumBug) { Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge); } } return receiver; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Adds utilities to the YUI instance for working with objects. * * @class Object */ var Lang = Y.Lang, hasOwn = Object.prototype.hasOwnProperty, UNDEFINED, // <-- Note the comma. We're still declaring vars. /** * Returns a new object that uses _obj_ as its prototype. This method wraps the * native ES5 `Object.create()` method if available, but doesn't currently * pass through `Object.create()`'s second argument (properties) in order to * ensure compatibility with older browsers. * * @method () * @param {Object} obj Prototype object. * @return {Object} New object using _obj_ as its prototype. * @static */ O = Y.Object = Lang._isNative(Object.create) ? function (obj) { // We currently wrap the native Object.create instead of simply aliasing it // to ensure consistency with our fallback shim, which currently doesn't // support Object.create()'s second argument (properties). Once we have a // safe fallback for the properties arg, we can stop wrapping // Object.create(). return Object.create(obj); } : (function () { // Reusable constructor function for the Object.create() shim. function F() {} // The actual shim. return function (obj) { F.prototype = obj; return new F(); }; }()), /** * Property names that IE doesn't enumerate in for..in loops, even when they * should be enumerable. When `_hasEnumBug` is `true`, it's necessary to * manually enumerate these properties. * * @property _forceEnum * @type String[] * @protected * @static */ forceEnum = O._forceEnum = [ 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'toLocaleString', 'valueOf' ], /** * `true` if this browser has the JScript enumeration bug that prevents * enumeration of the properties named in the `_forceEnum` array, `false` * otherwise. * * See: * - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug> * - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation> * * @property _hasEnumBug * @type Boolean * @protected * @static */ hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'), /** * `true` if this browser incorrectly considers the `prototype` property of * functions to be enumerable. Currently known to affect Opera 11.50. * * @property _hasProtoEnumBug * @type Boolean * @protected * @static */ hasProtoEnumBug = O._hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'), /** * Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or * exists only on _obj_'s prototype. This is essentially a safer version of * `obj.hasOwnProperty()`. * * @method owns * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ owns = O.owns = function (obj, key) { return !!obj && hasOwn.call(obj, key); }; // <-- End of var declarations. /** * Alias for `owns()`. * * @method hasKey * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ O.hasKey = owns; /** * Returns an array containing the object's enumerable keys. Does not include * prototype keys or non-enumerable keys. * * Note that keys are returned in enumeration order (that is, in the same order * that they would be enumerated by a `for-in` loop), which may not be the same * as the order in which they were defined. * * This method is an alias for the native ES5 `Object.keys()` method if * available. * * @example * * Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'}); * // => ['a', 'b', 'c'] * * @method keys * @param {Object} obj An object. * @return {String[]} Array of keys. * @static */ O.keys = Lang._isNative(Object.keys) ? Object.keys : function (obj) { if (!Lang.isObject(obj)) { throw new TypeError('Object.keys called on a non-object'); } var keys = [], i, key, len; if (hasProtoEnumBug && typeof obj === 'function') { for (key in obj) { if (owns(obj, key) && key !== 'prototype') { keys.push(key); } } } else { for (key in obj) { if (owns(obj, key)) { keys.push(key); } } } if (hasEnumBug) { for (i = 0, len = forceEnum.length; i < len; ++i) { key = forceEnum[i]; if (owns(obj, key)) { keys.push(key); } } } return keys; }; /** * Returns an array containing the values of the object's enumerable keys. * * Note that values are returned in enumeration order (that is, in the same * order that they would be enumerated by a `for-in` loop), which may not be the * same as the order in which they were defined. * * @example * * Y.Object.values({a: 'foo', b: 'bar', c: 'baz'}); * // => ['foo', 'bar', 'baz'] * * @method values * @param {Object} obj An object. * @return {Array} Array of values. * @static */ O.values = function (obj) { var keys = O.keys(obj), i = 0, len = keys.length, values = []; for (; i < len; ++i) { values.push(obj[keys[i]]); } return values; }; /** * Returns the number of enumerable keys owned by an object. * * @method size * @param {Object} obj An object. * @return {Number} The object's size. * @static */ O.size = function (obj) { try { return O.keys(obj).length; } catch (ex) { return 0; // Legacy behavior for non-objects. } }; /** * Returns `true` if the object owns an enumerable property with the specified * value. * * @method hasValue * @param {Object} obj An object. * @param {any} value The value to search for. * @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise. * @static */ O.hasValue = function (obj, value) { return Y.Array.indexOf(O.values(obj), value) > -1; }; /** * Executes a function on each enumerable property in _obj_. The function * receives the value, the key, and the object itself as parameters (in that * order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method each * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {YUI} the YUI instance. * @chainable * @static */ O.each = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { fn.call(thisObj || Y, obj[key], key, obj); } } return Y; }; /** * Executes a function on each enumerable property in _obj_, but halts if the * function returns a truthy value. The function receives the value, the key, * and the object itself as paramters (in that order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method some * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {Boolean} `true` if any execution of _fn_ returns a truthy value, * `false` otherwise. * @static */ O.some = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { if (fn.call(thisObj || Y, obj[key], key, obj)) { return true; } } } return false; }; /** * Retrieves the sub value at the provided path, * from the value object provided. * * @method getValue * @static * @param o The object from which to extract the property value. * @param path {Array} A path array, specifying the object traversal path * from which to obtain the sub value. * @return {Any} The value stored in the path, undefined if not found, * undefined if the source is not an object. Returns the source object * if an empty path is provided. */ O.getValue = function(o, path) { if (!Lang.isObject(o)) { return UNDEFINED; } var i, p = Y.Array(path), l = p.length; for (i = 0; o !== UNDEFINED && i < l; i++) { o = o[p[i]]; } return o; }; /** * Sets the sub-attribute value at the provided path on the * value object. Returns the modified value object, or * undefined if the path is invalid. * * @method setValue * @static * @param o The object on which to set the sub value. * @param path {Array} A path array, specifying the object traversal path * at which to set the sub value. * @param val {Any} The new value for the sub-attribute. * @return {Object} The modified object, with the new sub value set, or * undefined, if the path was invalid. */ O.setValue = function(o, path, val) { var i, p = Y.Array(path), leafIdx = p.length - 1, ref = o; if (leafIdx >= 0) { for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) { ref = ref[p[i]]; } if (ref !== UNDEFINED) { ref[p[i]] = val; } else { return UNDEFINED; } } return o; }; /** * Returns `true` if the object has no enumerable properties of its own. * * @method isEmpty * @param {Object} obj An object. * @return {Boolean} `true` if the object is empty. * @static * @since 3.2.0 */ O.isEmpty = function (obj) { return !O.keys(Object(obj)).length; }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ /** * YUI user agent detection. * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. For all fields listed * as @type float, UA stores a version number for the browser engine, * 0 otherwise. This value may or may not map to the version number of * the browser using the engine. The value is presented as a float so * that it can easily be used for boolean evaluation as well as for * looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost. The fields that * are @type string default to null. The API docs list the values that * these fields can have. * @class UA * @static */ /** * Static method on `YUI.Env` for parsing a UA string. Called at instantiation * to populate `Y.UA`. * * @static * @method parseUA * @param {String} [subUA=navigator.userAgent] UA string to parse * @return {Object} The Y.UA object */ YUI.Env.parseUA = function(subUA) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ == 1) ? '' : '.'; })); }, win = Y.config.win, nav = win && win.navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81 * Firefox 3.0 <-- 1.9 * Firefox 3.5 <-- 1.91 * </pre> * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native * SVG and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic * update from 2.x via the 10.4.11 OS patch. * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Safari will be detected as webkit, but this property will also * be populated with the Safari version number * @property safari * @type float * @static */ safari: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @default null * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type float * @default null * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Kindle Silk * @property silk * @type float * @static */ silk: 0, /** * Detects Kindle Silk Acceleration * @property accel * @type Boolean * @static */ accel: false, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @default null * @static */ os: null, /** * The Nodejs Version * @property nodejs * @type float * @default 0 * @static */ nodejs: 0 }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; /** * The User Agent string that was parsed * @property userAgent * @type String * @static */ o.userAgent = ua; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh|mac_powerpc/i).test(ua)) { o.os = 'macintosh'; } else if ((/android/i).test(ua)) { o.os = 'android'; } else if ((/symbos/i).test(ua)) { o.os = 'symbos'; } else if ((/linux/i).test(ua)) { o.os = 'linux'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } if ((/IEMobile|XBLWP7/).test(ua)) { o.mobile = 'windows'; } if ((/Fennec/).test(ua)) { o.mobile = 'gecko'; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); o.safari = o.webkit; // Mobile browser check if (/ Mobile\//.test(ua) || (/iPad|iPod|iPhone/).test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.os = 'ios'; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/); if (m) { // Nokia N-series, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { if (/Mobile/.test(ua)) { o.mobile = 'Android'; } m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } if (/Silk/.test(ua)) { m = ua.match(/Silk\/([^\s]*)\)/); if (m && m[1]) { o.silk = numberify(m[1]); } if (!o.android) { o.android = 2.34; //Hack for desktop mode in Kindle o.os = 'Android'; } if (/Accelerated=true/.test(ua)) { o.accel = true; } } } m = ua.match(/(Chrome|CrMo)\/([^\s]*)/); if (m && m[1] && m[2]) { o.chrome = numberify(m[2]); // Chrome o.safari = 0; //Reset safari back to 0 if (m[1] === 'CrMo') { o.mobile = 'chrome'; } } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) if (/Opera/.test(ua)) { m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } if (/Opera Mobi/.test(ua)) { o.mobile = 'opera'; m = ua.replace('Opera Mobi', '').match(/Opera ([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE\s([^;]*)/); if (m && m[1]) { o.ie = numberify(m[1]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); } } } } } } //It was a parsed UA, do not assign the global value. if (!subUA) { if (typeof process == 'object') { if (process.versions && process.versions.node) { //NodeJS o.os = process.platform; o.nodejs = process.versions.node; } } YUI.Env.UA = o; } return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); YUI.Env.aliases = { "anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"], "app": ["app-base","app-transitions","model","model-list","router","view"], "attribute": ["attribute-base","attribute-complex"], "autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"], "base": ["base-base","base-pluginhost","base-build"], "cache": ["cache-base","cache-offline","cache-plugin"], "collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"], "controller": ["router"], "dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"], "datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"], "datatable": ["datatable-core","datatable-head","datatable-body","datatable-base","datatable-column-widths","datatable-message","datatable-mutable","datatable-sort","datatable-datasource"], "datatable-deprecated": ["datatable-base-deprecated","datatable-datasource-deprecated","datatable-sort-deprecated","datatable-scroll-deprecated"], "datatype": ["datatype-number","datatype-date","datatype-xml"], "datatype-date": ["datatype-date-parse","datatype-date-format"], "datatype-number": ["datatype-number-parse","datatype-number-format"], "datatype-xml": ["datatype-xml-parse","datatype-xml-format"], "dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"], "dom": ["dom-base","dom-screen","dom-style","selector-native","selector"], "editor": ["frame","editor-selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"], "event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside","event-touch","event-move","event-flick","event-valuechange"], "event-custom": ["event-custom-base","event-custom-complex"], "event-gestures": ["event-flick","event-move"], "handlebars": ["handlebars-compiler"], "highlight": ["highlight-base","highlight-accentfold"], "history": ["history-base","history-hash","history-hash-ie","history-html5"], "io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"], "json": ["json-parse","json-stringify"], "loader": ["loader-base","loader-rollup","loader-yui3"], "node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"], "pluginhost": ["pluginhost-base","pluginhost-config"], "querystring": ["querystring-parse","querystring-stringify"], "recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"], "resize": ["resize-base","resize-proxy","resize-constrain"], "slider": ["slider-base","slider-value-range","clickable-rail","range-slider"], "text": ["text-accentfold","text-wordbreak"], "widget": ["widget-base","widget-htmlparser","widget-skin","widget-uievents"] }; }, '3.5.0' ); YUI.add('get', function(Y) { /*jslint boss:true, expr:true, laxbreak: true */ /** Provides dynamic loading of remote JavaScript and CSS resources. @module get @class Get @static **/ var Lang = Y.Lang, CUSTOM_ATTRS, // defined lazily in Y.Get.Transaction._createNode() Get, Transaction; Y.Get = Get = { // -- Public Properties ---------------------------------------------------- /** Default options for CSS requests. Options specified here will override global defaults for CSS requests. See the `options` property for all available options. @property cssOptions @type Object @static @since 3.5.0 **/ cssOptions: { attributes: { rel: 'stylesheet' }, doc : Y.config.linkDoc || Y.config.doc, pollInterval: 50 }, /** Default options for JS requests. Options specified here will override global defaults for JS requests. See the `options` property for all available options. @property jsOptions @type Object @static @since 3.5.0 **/ jsOptions: { autopurge: true, doc : Y.config.scriptDoc || Y.config.doc }, /** Default options to use for all requests. Note that while all available options are documented here for ease of discovery, some options (like callback functions) only make sense at the transaction level. Callback functions specified via the options object or the `options` parameter of the `css()`, `js()`, or `load()` methods will receive the transaction object as a parameter. See `Y.Get.Transaction` for details on the properties and methods available on transactions. @static @since 3.5.0 @property {Object} options @property {Boolean} [options.async=false] Whether or not to load scripts asynchronously, meaning they're requested in parallel and execution order is not guaranteed. Has no effect on CSS, since CSS is always loaded asynchronously. @property {Object} [options.attributes] HTML attribute name/value pairs that should be added to inserted nodes. By default, the `charset` attribute will be set to "utf-8" and nodes will be given an auto-generated `id` attribute, but you can override these with your own values if desired. @property {Boolean} [options.autopurge] Whether or not to automatically purge inserted nodes after the purge threshold is reached. This is `true` by default for JavaScript, but `false` for CSS since purging a CSS node will also remove any styling applied by the referenced file. @property {Object} [options.context] `this` object to use when calling callback functions. Defaults to the transaction object. @property {Mixed} [options.data] Arbitrary data object to pass to "on*" callbacks. @property {Document} [options.doc] Document into which nodes should be inserted. By default, the current document is used. @property {HTMLElement|String} [options.insertBefore] HTML element or id string of an element before which all generated nodes should be inserted. If not specified, Get will automatically determine the best place to insert nodes for maximum compatibility. @property {Function} [options.onEnd] Callback to execute after a transaction is complete, regardless of whether it succeeded or failed. @property {Function} [options.onFailure] Callback to execute after a transaction fails, times out, or is aborted. @property {Function} [options.onProgress] Callback to execute after each individual request in a transaction either succeeds or fails. @property {Function} [options.onSuccess] Callback to execute after a transaction completes successfully with no errors. Note that in browsers that don't support the `error` event on CSS `<link>` nodes, a failed CSS request may still be reported as a success because in these browsers it can be difficult or impossible to distinguish between success and failure for CSS resources. @property {Function} [options.onTimeout] Callback to execute after a transaction times out. @property {Number} [options.pollInterval=50] Polling interval (in milliseconds) for detecting CSS load completion in browsers that don't support the `load` event on `<link>` nodes. This isn't used for JavaScript. @property {Number} [options.purgethreshold=20] Number of nodes to insert before triggering an automatic purge when `autopurge` is `true`. @property {Number} [options.timeout] Number of milliseconds to wait before aborting a transaction. When a timeout occurs, the `onTimeout` callback is called, followed by `onFailure` and finally `onEnd`. By default, there is no timeout. @property {String} [options.type] Resource type ("css" or "js"). This option is set automatically by the `css()` and `js()` functions and will be ignored there, but may be useful when using the `load()` function. If not specified, the type will be inferred from the URL, defaulting to "js" if the URL doesn't contain a recognizable file extension. **/ options: { attributes: { charset: 'utf-8' }, purgethreshold: 20 }, // -- Protected Properties ------------------------------------------------- /** Regex that matches a CSS URL. Used to guess the file type when it's not specified. @property REGEX_CSS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_CSS: /\.css(?:[?;].*)?$/i, /** Regex that matches a JS URL. Used to guess the file type when it's not specified. @property REGEX_JS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_JS : /\.js(?:[?;].*)?$/i, /** Contains information about the current environment, such as what script and link injection features it supports. This object is created and populated the first time the `_getEnv()` method is called. @property _env @type Object @protected @static @since 3.5.0 **/ /** Mapping of document _yuid strings to <head> or <base> node references so we don't have to look the node up each time we want to insert a request node. @property _insertCache @type Object @protected @static @since 3.5.0 **/ _insertCache: {}, /** Information about the currently pending transaction, if any. This is actually an object with two properties: `callback`, containing the optional callback passed to `css()`, `load()`, or `js()`; and `transaction`, containing the actual transaction instance. @property _pending @type Object @protected @static @since 3.5.0 **/ _pending: null, /** HTML nodes eligible to be purged next time autopurge is triggered. @property _purgeNodes @type HTMLElement[] @protected @static @since 3.5.0 **/ _purgeNodes: [], /** Queued transactions and associated callbacks. @property _queue @type Object[] @protected @static @since 3.5.0 **/ _queue: [], // -- Public Methods ------------------------------------------------------- /** Aborts the specified transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). *Note:* This method is deprecated as of 3.5.0, and will be removed in a future version of YUI. Use the transaction-level `abort()` method instead. @method abort @param {Get.Transaction} transaction Transaction to abort. @deprecated Use the `abort()` method on the transaction instead. @static **/ abort: function (transaction) { var i, id, item, len, pending; Y.log('`Y.Get.abort()` is deprecated as of 3.5.0. Use the `abort()` method on the transaction instead.', 'warn', 'get'); if (!transaction.abort) { id = transaction; pending = this._pending; transaction = null; if (pending && pending.transaction.id === id) { transaction = pending.transaction; this._pending = null; } else { for (i = 0, len = this._queue.length; i < len; ++i) { item = this._queue[i].transaction; if (item.id === id) { transaction = item; this._queue.splice(i, 1); break; } } } } transaction && transaction.abort(); }, /** Loads one or more CSS files. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. @example // Load a single CSS file and log a message on completion. Y.Get.css('foo.css', function (err) { if (err) { Y.log('foo.css failed to load!'); } else { Y.log('foo.css was loaded successfully'); } }); // Load multiple CSS files and log a message when all have finished // loading. var urls = ['foo.css', 'http://example.com/bar.css', 'baz/quux.css']; Y.Get.css(urls, function (err) { if (err) { Y.log('one or more files failed to load!'); } else { Y.log('all files loaded successfully'); } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.css(urls, { attributes: {'class': 'my-css'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.css([ {url: 'foo.css', attributes: {id: 'foo'}}, {url: 'bar.css', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method css @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @static **/ css: function (urls, options, callback) { return this._load('css', urls, options, callback); }, /** Loads one or more JavaScript resources. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. Scripts will be executed in the order they're specified unless the `async` option is `true`, in which case they'll be loaded in parallel and executed in whatever order they finish loading. @example // Load a single JS file and log a message on completion. Y.Get.js('foo.js', function (err) { if (err) { Y.log('foo.js failed to load!'); } else { Y.log('foo.js was loaded successfully'); } }); // Load multiple JS files, execute them in order, and log a message when // all have finished loading. var urls = ['foo.js', 'http://example.com/bar.js', 'baz/quux.js']; Y.Get.js(urls, function (err) { if (err) { Y.log('one or more files failed to load!'); } else { Y.log('all files loaded successfully'); } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.js(urls, { attributes: {'class': 'my-js'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.js([ {url: 'foo.js', attributes: {id: 'foo'}}, {url: 'bar.js', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method js @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ js: function (urls, options, callback) { return this._load('js', urls, options, callback); }, /** Loads one or more CSS and/or JavaScript resources in the same transaction. Use this method when you want to load both CSS and JavaScript in a single transaction and be notified when all requested URLs have finished loading, regardless of type. Behavior and options are the same as for the `css()` and `js()` methods. If a resource type isn't specified in per-request options or transaction-level options, Get will guess the file type based on the URL's extension (`.css` or `.js`, with or without a following query string). If the file type can't be guessed from the URL, a warning will be logged and Get will assume the URL is a JavaScript resource. @example // Load both CSS and JS files in a single transaction, and log a message // when all files have finished loading. Y.Get.load(['foo.css', 'bar.js', 'baz.css'], function (err) { if (err) { Y.log('one or more files failed to load!'); } else { Y.log('all files loaded successfully'); } }); @method load @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ load: function (urls, options, callback) { return this._load(null, urls, options, callback); }, // -- Protected Methods ---------------------------------------------------- /** Triggers an automatic purge if the purge threshold has been reached. @method _autoPurge @param {Number} threshold Purge threshold to use, in milliseconds. @protected @since 3.5.0 @static **/ _autoPurge: function (threshold) { if (threshold && this._purgeNodes.length >= threshold) { Y.log('autopurge triggered after ' + this._purgeNodes.length + ' nodes', 'info', 'get'); this._purge(this._purgeNodes); } }, /** Populates the `_env` property with information about the current environment. @method _getEnv @return {Object} Environment information. @protected @since 3.5.0 @static **/ _getEnv: function () { var doc = Y.config.doc, ua = Y.UA; // Note: some of these checks require browser sniffs since it's not // feasible to load test files on every pageview just to perform a // feature test. I'm sorry if this makes you sad. return (this._env = { // True if this is a browser that supports disabling async mode on // dynamically created script nodes. See // https://developer.mozilla.org/En/HTML/Element/Script#Attributes async: doc && doc.createElement('script').async === true, // True if this browser fires an event when a dynamically injected // link node fails to load. This is currently true for Firefox 9+ // and WebKit 535.24+. cssFail: ua.gecko >= 9 || ua.webkit >= 535.24, // True if this browser fires an event when a dynamically injected // link node finishes loading. This is currently true for IE, Opera, // Firefox 9+, and WebKit 535.24+. Note that IE versions <9 fire the // DOM 0 "onload" event, but not "load". All versions of IE fire // "onload". // davglass: Seems that Chrome on Android needs this to be false. cssLoad: ((!ua.gecko && !ua.webkit) || ua.gecko >= 9 || ua.webkit >= 535.24) && !(ua.chrome && ua.chrome <=18), // True if this browser preserves script execution order while // loading scripts in parallel as long as the script node's `async` // attribute is set to false to explicitly disable async execution. preservesScriptOrder: !!(ua.gecko || ua.opera) }); }, _getTransaction: function (urls, options) { var requests = [], i, len, req, url; if (!Lang.isArray(urls)) { urls = [urls]; } options = Y.merge(this.options, options); // Clone the attributes object so we don't end up modifying it by ref. options.attributes = Y.merge(this.options.attributes, options.attributes); for (i = 0, len = urls.length; i < len; ++i) { url = urls[i]; req = {attributes: {}}; // If `url` is a string, we create a URL object for it, then mix in // global options and request-specific options. If it's an object // with a "url" property, we assume it's a request object containing // URL-specific options. if (typeof url === 'string') { req.url = url; } else if (url.url) { // URL-specific options override both global defaults and // request-specific options. Y.mix(req, url, false, null, 0, true); url = url.url; // Make url a string so we can use it later. } else { Y.log('URL must be a string or an object with a `url` property.', 'error', 'get'); continue; } Y.mix(req, options, false, null, 0, true); // If we didn't get an explicit type for this URL either in the // request options or the URL-specific options, try to determine // one from the file extension. if (!req.type) { if (this.REGEX_CSS.test(url)) { req.type = 'css'; } else { if (!this.REGEX_JS.test(url)) { Y.log("Can't guess file type from URL. Assuming JS: " + url, 'warn', 'get'); } req.type = 'js'; } } // Mix in type-specific default options, but don't overwrite any // options that have already been set. Y.mix(req, req.type === 'js' ? this.jsOptions : this.cssOptions, false, null, 0, true); // Give the node an id attribute if it doesn't already have one. req.attributes.id || (req.attributes.id = Y.guid()); // Backcompat for <3.5.0 behavior. if (req.win) { Y.log('The `win` option is deprecated as of 3.5.0. Use `doc` instead.', 'warn', 'get'); req.doc = req.win.document; } else { req.win = req.doc.defaultView || req.doc.parentWindow; } if (req.charset) { Y.log('The `charset` option is deprecated as of 3.5.0. Set `attributes.charset` instead.', 'warn', 'get'); req.attributes.charset = req.charset; } requests.push(req); } return new Transaction(requests, options); }, _load: function (type, urls, options, callback) { var transaction; // Allow callback as third param. if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); options.type = type; if (!this._env) { this._getEnv(); } transaction = this._getTransaction(urls, options); this._queue.push({ callback : callback, transaction: transaction }); this._next(); return transaction; }, _next: function () { var item; if (this._pending) { return; } item = this._queue.shift(); if (item) { this._pending = item; item.transaction.execute(function () { item.callback && item.callback.apply(this, arguments); Get._pending = null; Get._next(); }); } }, _purge: function (nodes) { var purgeNodes = this._purgeNodes, isTransaction = nodes !== purgeNodes, index, node; while (node = nodes.pop()) { // assignment // Don't purge nodes that haven't finished loading (or errored out), // since this can hang the transaction. if (!node._yuiget_finished) { continue; } node.parentNode && node.parentNode.removeChild(node); // If this is a transaction-level purge and this node also exists in // the Get-level _purgeNodes array, we need to remove it from // _purgeNodes to avoid creating a memory leak. The indexOf lookup // sucks, but until we get WeakMaps, this is the least troublesome // way to do this (we can't just hold onto node ids because they may // not be in the same document). if (isTransaction) { index = Y.Array.indexOf(purgeNodes, node); if (index > -1) { purgeNodes.splice(index, 1); } } } } }; /** Alias for `js()`. @method script @static **/ Get.script = Get.js; /** Represents a Get transaction, which may contain requests for one or more JS or CSS files. This class should not be instantiated manually. Instances will be created and returned as needed by Y.Get's `css()`, `js()`, and `load()` methods. @class Get.Transaction @constructor @since 3.5.0 **/ Get.Transaction = Transaction = function (requests, options) { var self = this; self.id = Transaction._lastId += 1; self.data = options.data; self.errors = []; self.nodes = []; self.options = options; self.requests = requests; self._callbacks = []; // callbacks to call after execution finishes self._queue = []; self._waiting = 0; // Deprecated pre-3.5.0 properties. self.tId = self.id; // Use `id` instead. self.win = options.win || Y.config.win; }; /** Arbitrary data object associated with this transaction. This object comes from the options passed to `Get.css()`, `Get.js()`, or `Get.load()`, and will be `undefined` if no data object was specified. @property {Object} data **/ /** Array of errors that have occurred during this transaction, if any. @since 3.5.0 @property {Object[]} errors @property {String} errors.error Error message. @property {Object} errors.request Request object related to the error. **/ /** Numeric id for this transaction, unique among all transactions within the same YUI sandbox in the current pageview. @property {Number} id @since 3.5.0 **/ /** HTMLElement nodes (native ones, not YUI Node instances) that have been inserted during the current transaction. @property {HTMLElement[]} nodes **/ /** Options associated with this transaction. See `Get.options` for the full list of available options. @property {Object} options @since 3.5.0 **/ /** Request objects contained in this transaction. Each request object represents one CSS or JS URL that will be (or has been) requested and loaded into the page. @property {Object} requests @since 3.5.0 **/ /** Id of the most recent transaction. @property _lastId @type Number @protected @static **/ Transaction._lastId = 0; Transaction.prototype = { // -- Public Properties ---------------------------------------------------- /** Current state of this transaction. One of "new", "executing", or "done". @property _state @type String @protected **/ _state: 'new', // "new", "executing", or "done" // -- Public Methods ------------------------------------------------------- /** Aborts this transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). @method abort @param {String} [msg="Aborted."] Optional message to use in the `errors` array describing why the transaction was aborted. **/ abort: function (msg) { this._pending = null; this._pendingCSS = null; this._pollTimer = clearTimeout(this._pollTimer); this._queue = []; this._waiting = 0; this.errors.push({error: msg || 'Aborted'}); this._finish(); }, /** Begins execting the transaction. There's usually no reason to call this manually, since Get will call it automatically when other pending transactions have finished. If you really want to execute your transaction before Get does, you can, but be aware that this transaction's scripts may end up executing before the scripts in other pending transactions. If the transaction is already executing, the specified callback (if any) will be queued and called after execution finishes. If the transaction has already finished, the callback will be called immediately (the transaction will not be executed again). @method execute @param {Function} callback Callback function to execute after all requests in the transaction are complete, or after the transaction is aborted. **/ execute: function (callback) { var self = this, requests = self.requests, state = self._state, i, len, queue, req; if (state === 'done') { callback && callback(self.errors.length ? self.errors : null, self); return; } else { callback && self._callbacks.push(callback); if (state === 'executing') { return; } } self._state = 'executing'; self._queue = queue = []; if (self.options.timeout) { self._timeout = setTimeout(function () { self.abort('Timeout'); }, self.options.timeout); } for (i = 0, len = requests.length; i < len; ++i) { req = self.requests[i]; if (req.async || req.type === 'css') { // No need to queue CSS or fully async JS. self._insert(req); } else { queue.push(req); } } self._next(); }, /** Manually purges any `<script>` or `<link>` nodes this transaction has created. Be careful when purging a transaction that contains CSS requests, since removing `<link>` nodes will also remove any styles they applied. @method purge **/ purge: function () { Get._purge(this.nodes); }, // -- Protected Methods ---------------------------------------------------- _createNode: function (name, attrs, doc) { var node = doc.createElement(name), attr, testEl; if (!CUSTOM_ATTRS) { // IE6 and IE7 expect property names rather than attribute names for // certain attributes. Rather than sniffing, we do a quick feature // test the first time _createNode() runs to determine whether we // need to provide a workaround. testEl = doc.createElement('div'); testEl.setAttribute('class', 'a'); CUSTOM_ATTRS = testEl.className === 'a' ? {} : { 'for' : 'htmlFor', 'class': 'className' }; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { node.setAttribute(CUSTOM_ATTRS[attr] || attr, attrs[attr]); } } return node; }, _finish: function () { var errors = this.errors.length ? this.errors : null, options = this.options, thisObj = options.context || this, data, i, len; if (this._state === 'done') { return; } this._state = 'done'; for (i = 0, len = this._callbacks.length; i < len; ++i) { this._callbacks[i].call(thisObj, errors, this); } data = this._getEventData(); if (errors) { if (options.onTimeout && errors[errors.length - 1].error === 'Timeout') { options.onTimeout.call(thisObj, data); } if (options.onFailure) { options.onFailure.call(thisObj, data); } } else if (options.onSuccess) { options.onSuccess.call(thisObj, data); } if (options.onEnd) { options.onEnd.call(thisObj, data); } }, _getEventData: function (req) { if (req) { // This merge is necessary for backcompat. I hate it. return Y.merge(this, { abort : this.abort, // have to copy these because the prototype isn't preserved purge : this.purge, request: req, url : req.url, win : req.win }); } else { return this; } }, _getInsertBefore: function (req) { var doc = req.doc, el = req.insertBefore, cache, cachedNode, docStamp; if (el) { return typeof el === 'string' ? doc.getElementById(el) : el; } cache = Get._insertCache; docStamp = Y.stamp(doc); if ((el = cache[docStamp])) { // assignment return el; } // Inserting before a <base> tag apparently works around an IE bug // (according to a comment from pre-3.5.0 Y.Get), but I'm not sure what // bug that is, exactly. Better safe than sorry? if ((el = doc.getElementsByTagName('base')[0])) { // assignment return (cache[docStamp] = el); } // Look for a <head> element. el = doc.head || doc.getElementsByTagName('head')[0]; if (el) { // Create a marker node at the end of <head> to use as an insertion // point. Inserting before this node will ensure that all our CSS // gets inserted in the correct order, to maintain style precedence. el.appendChild(doc.createTextNode('')); return (cache[docStamp] = el.lastChild); } // If all else fails, just insert before the first script node on the // page, which is virtually guaranteed to exist. return (cache[docStamp] = doc.getElementsByTagName('script')[0]); }, _insert: function (req) { var env = Get._env, insertBefore = this._getInsertBefore(req), isScript = req.type === 'js', node = req.node, self = this, ua = Y.UA, cssTimeout, nodeType; if (!node) { if (isScript) { nodeType = 'script'; } else if (!env.cssLoad && ua.gecko) { nodeType = 'style'; } else { nodeType = 'link'; } node = req.node = this._createNode(nodeType, req.attributes, req.doc); } function onError() { self._progress('Failed to load ' + req.url, req); } function onLoad() { if (cssTimeout) { clearTimeout(cssTimeout); } self._progress(null, req); } // Deal with script asynchronicity. if (isScript) { node.setAttribute('src', req.url); if (req.async) { // Explicitly indicate that we want the browser to execute this // script asynchronously. This is necessary for older browsers // like Firefox <4. node.async = true; } else { if (env.async) { // This browser treats injected scripts as async by default // (standard HTML5 behavior) but asynchronous loading isn't // desired, so tell the browser not to mark this script as // async. node.async = false; } // If this browser doesn't preserve script execution order based // on insertion order, we'll need to avoid inserting other // scripts until this one finishes loading. if (!env.preservesScriptOrder) { this._pending = req; } } } else { if (!env.cssLoad && ua.gecko) { // In Firefox <9, we can import the requested URL into a <style> // node and poll for the existence of node.sheet.cssRules. This // gives us a reliable way to determine CSS load completion that // also works for cross-domain stylesheets. // // Props to Zach Leatherman for calling my attention to this // technique. node.innerHTML = (req.attributes.charset ? '@charset "' + req.attributes.charset + '";' : '') + '@import "' + req.url + '";'; } else { node.setAttribute('href', req.url); } } // Inject the node. if (isScript && ua.ie && ua.ie < 9) { // Script on IE6, 7, and 8. node.onreadystatechange = function () { if (/loaded|complete/.test(node.readyState)) { node.onreadystatechange = null; onLoad(); } }; } else if (!isScript && !env.cssLoad) { // CSS on Firefox <9 or WebKit. this._poll(req); } else { // Script or CSS on everything else. Using DOM 0 events because that // evens the playing field with older IEs. node.onerror = onError; node.onload = onLoad; // If this browser doesn't fire an event when CSS fails to load, // fail after a timeout to avoid blocking the transaction queue. if (!env.cssFail && !isScript) { cssTimeout = setTimeout(onError, req.timeout || 3000); } } this._waiting += 1; this.nodes.push(node); insertBefore.parentNode.insertBefore(node, insertBefore); }, _next: function () { if (this._pending) { return; } // If there are requests in the queue, insert the next queued request. // Otherwise, if we're waiting on already-inserted requests to finish, // wait longer. If there are no queued requests and we're not waiting // for anything to load, then we're done! if (this._queue.length) { this._insert(this._queue.shift()); } else if (!this._waiting) { this._finish(); } }, _poll: function (newReq) { var self = this, pendingCSS = self._pendingCSS, isWebKit = Y.UA.webkit, i, hasRules, j, nodeHref, req, sheets; if (newReq) { pendingCSS || (pendingCSS = self._pendingCSS = []); pendingCSS.push(newReq); if (self._pollTimer) { // A poll timeout is already pending, so no need to create a // new one. return; } } self._pollTimer = null; // Note: in both the WebKit and Gecko hacks below, a CSS URL that 404s // will still be treated as a success. There's no good workaround for // this. for (i = 0; i < pendingCSS.length; ++i) { req = pendingCSS[i]; if (isWebKit) { // Look for a stylesheet matching the pending URL. sheets = req.doc.styleSheets; j = sheets.length; nodeHref = req.node.href; while (--j >= 0) { if (sheets[j].href === nodeHref) { pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); break; } } } else { // Many thanks to Zach Leatherman for calling my attention to // the @import-based cross-domain technique used here, and to // Oleg Slobodskoi for an earlier same-domain implementation. // // See Zach's blog for more details: // http://www.zachleat.com/web/2010/07/29/load-css-dynamically/ try { // We don't really need to store this value since we never // use it again, but if we don't store it, Closure Compiler // assumes the code is useless and removes it. hasRules = !!req.node.sheet.cssRules; // If we get here, the stylesheet has loaded. pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); } catch (ex) { // An exception means the stylesheet is still loading. } } } if (pendingCSS.length) { self._pollTimer = setTimeout(function () { self._poll.call(self); }, self.options.pollInterval); } }, _progress: function (err, req) { var options = this.options; if (err) { req.error = err; this.errors.push({ error : err, request: req }); Y.log(err, 'error', 'get'); } req.node._yuiget_finished = req.finished = true; if (options.onProgress) { options.onProgress.call(options.context || this, this._getEventData(req)); } if (req.autopurge) { // Pre-3.5.0 Get always excludes the most recent node from an // autopurge. I find this odd, but I'm keeping that behavior for // the sake of backcompat. Get._autoPurge(this.options.purgethreshold); Get._purgeNodes.push(req.node); } if (this._pending === req) { this._pending = null; } this._waiting -= 1; this._next(); } }; }, '3.5.0' ,{requires:['yui-base']}); YUI.add('features', function(Y) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { Y.log('Feature test ' + cat + ', ' + name + ' not found'); } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by src/loader/scripts/meta_join.py */ var add = Y.Features.add; // io-nodejs add('load', '0', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // graphics-canvas-default add('load', '1', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // autocomplete-list-keys add('load', '2', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // graphics-svg add('load', '3', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // graphics-vml-default add('load', '5', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-svg-default add('load', '6', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // history-hash-ie add('load', '7', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // transition-timer add('load', '8', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style); } return ret; }, "trigger": "transition" }); // dom-style-ie add('load', '9', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // selector-css2 add('load', '10', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // widget-base-ie add('load', '11', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // event-base-ie add('load', '12', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // dd-gestures add('load', '13', { "name": "dd-gestures", "test": function(Y) { return ((Y.config.win && ("ontouchstart" in Y.config.win)) && !(Y.UA.chrome && Y.UA.chrome < 6)); }, "trigger": "dd-drag" }); // scrollview-base-ie add('load', '14', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // app-transitions-native add('load', '15', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style); } return false; }, "trigger": "app-transitions" }); // graphics-canvas add('load', '16', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-vml add('load', '17', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); }, '3.5.0' ,{requires:['yui-base']}); YUI.add('intl-base', function(Y) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, '3.5.0' ,{requires:['yui-base']}); YUI.add('yui-log', function(Y) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 1, warn: 1, error: 1 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters if (src) { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console != UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera != UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher == Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '3.5.0' ,{requires:['yui-base']}); YUI.add('yui-later', function(Y) { /** * Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-later */ var NO_ARGS = []; /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @for YUI * @method later * @param when {int} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This * accepts either a single item or an array. If an array is provided, * the function is executed with one parameter for each array item. * If you need to pass a single array parameter, it needs to be wrapped * in an array [myarray]. * * Note: native methods in IE may not have the call and apply methods. * In this case, it will work, but you are limited to four arguments. * * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this * object to stop the timer. */ Y.later = function(when, o, fn, data, periodic) { when = when || 0; data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS; o = o || Y.config.win || Y; var cancelled = false, method = (o && Y.Lang.isString(fn)) ? o[fn] : fn, wrapper = function() { // IE 8- may execute a setInterval callback one last time // after clearInterval was called, so in order to preserve // the cancel() === no more runny-run, we have to jump through // an extra hoop. if (!cancelled) { if (!method.apply) { method(data[0], data[1], data[2], data[3]); } else { method.apply(o, data || NO_ARGS); } } }, id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when); return { id: id, interval: periodic, cancel: function() { cancelled = true; if (this.interval) { clearInterval(id); } else { clearTimeout(id); } } }; }; Y.Lang.later = Y.later; }, '3.5.0' ,{requires:['yui-base']}); YUI.add('yui', function(Y){}, '3.5.0' ,{use:['yui-base','get','features','intl-base','yui-log','yui-later']});
import { Dictionary, PnPClientStorage, RuntimeConfig, Util, mergeOptions } from '@pnp/common'; import { LogLevel, Logger } from '@pnp/logging'; import { __decorate } from 'tslib'; class CachingOptions { constructor(key) { this.key = key; this.expiration = Util.dateAdd(new Date(), "second", RuntimeConfig.defaultCachingTimeoutSeconds); this.storeName = RuntimeConfig.defaultCachingStore; } get store() { if (this.storeName === "local") { return CachingOptions.storage.local; } else { return CachingOptions.storage.session; } } } CachingOptions.storage = new PnPClientStorage(); class CachingParserWrapper { constructor(_parser, _cacheOptions) { this._parser = _parser; this._cacheOptions = _cacheOptions; } parse(response) { // add this to the cache based on the options return this._parser.parse(response).then(data => { if (this._cacheOptions.store !== null) { this._cacheOptions.store.put(this._cacheOptions.key, data, this._cacheOptions.expiration); } return data; }); } } /** * Represents an exception with an HttpClient request * */ class ProcessHttpClientResponseException extends Error { constructor(status, statusText, data) { super(`Error making HttpClient request in queryable: [${status}] ${statusText}`); this.status = status; this.statusText = statusText; this.data = data; this.name = "ProcessHttpClientResponseException"; Logger.log({ data: this.data, level: LogLevel.Error, message: this.message }); } } class AlreadyInBatchException extends Error { constructor(msg = "This query is already part of a batch.") { super(msg); this.name = "AlreadyInBatchException"; Logger.log({ data: {}, level: LogLevel.Error, message: `[${this.name}]::${this.message}` }); } } class ODataParserBase { parse(r) { return new Promise((resolve, reject) => { if (this.handleError(r, reject)) { if ((r.headers.has("Content-Length") && parseFloat(r.headers.get("Content-Length") || "-1") === 0) || r.status === 204) { resolve({}); } else { // patch to handle cases of 200 response with no or whitespace only bodies (#487 & #545) r.text() .then(txt => txt.replace(/\s/ig, "").length > 0 ? JSON.parse(txt) : {}) .then(json => resolve(this.parseODataJSON(json))) .catch(e => reject(e)); } } }); } handleError(r, reject) { if (!r.ok) { r.json().then(json => { // include the headers as they contain diagnostic information const data = { responseBody: json, responseHeaders: r.headers, }; reject(new ProcessHttpClientResponseException(r.status, r.statusText, data)); }).catch(e => { // we failed to read the body - possibly it is empty. Let's report the original status that caused // the request to fail and log the error with parsing the body if anyone needs it for debugging Logger.log({ data: e, level: LogLevel.Warning, message: "There was an error parsing the error response body. See data for details.", }); // include the headers as they contain diagnostic information const data = { responseBody: "[[body not available]]", responseHeaders: r.headers, }; reject(new ProcessHttpClientResponseException(r.status, r.statusText, data)); }); } return r.ok; } parseODataJSON(json) { let result = json; if (json.hasOwnProperty("d")) { if (json.d.hasOwnProperty("results")) { result = json.d.results; } else { result = json.d; } } else if (json.hasOwnProperty("value")) { result = json.value; } return result; } } class ODataDefaultParser extends ODataParserBase { } class ODataValueParserImpl extends ODataParserBase { parse(r) { return super.parse(r).then(d => d); } } function ODataValue() { return new ODataValueParserImpl(); } class ODataRawParserImpl { parse(r) { return r.json(); } } let ODataRaw = new ODataRawParserImpl(); class TextFileParser { parse(r) { return r.text(); } } class BlobFileParser { parse(r) { return r.blob(); } } class JSONFileParser { parse(r) { return r.json(); } } class BufferFileParser { parse(r) { if (Util.isFunction(r.arrayBuffer)) { return r.arrayBuffer(); } return r.buffer(); } } /** * Resolves the context's result value * * @param context The current context */ function returnResult(context) { Logger.log({ data: context.result, level: LogLevel.Verbose, message: `[${context.requestId}] (${(new Date()).getTime()}) Returning result, see data property for value.`, }); return Promise.resolve(context.result || null); } /** * Sets the result on the context */ function setResult(context, value) { return new Promise((resolve) => { context.result = value; context.hasResult = true; resolve(context); }); } /** * Invokes the next method in the provided context's pipeline * * @param c The current request context */ function next(c) { const _next = c.pipeline.shift(); if (typeof _next !== "undefined") { return _next(c); } else { return Promise.resolve(c); } } /** * Executes the current request context's pipeline * * @param context Current context */ function pipe(context) { return next(context) .then(ctx => returnResult(ctx)) .catch((e) => { Logger.log({ data: e, level: LogLevel.Error, message: `Error in request pipeline: ${e.message}`, }); throw e; }); } /** * decorator factory applied to methods in the pipeline to control behavior */ function requestPipelineMethod(alwaysRun = false) { return (target, propertyKey, descriptor) => { const method = descriptor.value; descriptor.value = function (...args) { // if we have a result already in the pipeline, pass it along and don't call the tagged method if (!alwaysRun && args.length > 0 && args[0].hasOwnProperty("hasResult") && args[0].hasResult) { Logger.write(`[${args[0].requestId}] (${(new Date()).getTime()}) Skipping request pipeline method ${propertyKey}, existing result in pipeline.`, LogLevel.Verbose); return Promise.resolve(args[0]); } // apply the tagged method Logger.write(`[${args[0].requestId}] (${(new Date()).getTime()}) Calling request pipeline method ${propertyKey}.`, LogLevel.Verbose); // then chain the next method in the context's pipeline - allows for dynamic pipeline return method.apply(target, args).then((ctx) => next(ctx)); }; }; } /** * Contains the methods used within the request pipeline */ class PipelineMethods { /** * Logs the start of the request */ static logStart(context) { return new Promise(resolve => { Logger.log({ data: Logger.activeLogLevel === LogLevel.Info ? {} : context, level: LogLevel.Info, message: `[${context.requestId}] (${(new Date()).getTime()}) Beginning ${context.verb} request (${context.requestAbsoluteUrl})`, }); resolve(context); }); } /** * Handles caching of the request */ static caching(context) { return new Promise(resolve => { // handle caching, if applicable if (context.verb === "GET" && context.isCached) { Logger.write(`[${context.requestId}] (${(new Date()).getTime()}) Caching is enabled for request, checking cache...`, LogLevel.Info); let cacheOptions = new CachingOptions(context.requestAbsoluteUrl.toLowerCase()); if (typeof context.cachingOptions !== "undefined") { cacheOptions = Util.extend(cacheOptions, context.cachingOptions); } // we may not have a valid store if (cacheOptions.store !== null) { // check if we have the data in cache and if so resolve the promise and return const data = cacheOptions.store.get(cacheOptions.key); if (data !== null) { // ensure we clear any help batch dependency we are resolving from the cache Logger.log({ data: Logger.activeLogLevel === LogLevel.Info ? {} : data, level: LogLevel.Info, message: `[${context.requestId}] (${(new Date()).getTime()}) Value returned from cache.`, }); context.batchDependency(); return setResult(context, data).then(ctx => resolve(ctx)); } } Logger.write(`[${context.requestId}] (${(new Date()).getTime()}) Value not found in cache.`, LogLevel.Info); // if we don't then wrap the supplied parser in the caching parser wrapper // and send things on their way context.parser = new CachingParserWrapper(context.parser, cacheOptions); } return resolve(context); }); } /** * Sends the request */ static send(context) { return new Promise((resolve, reject) => { // send or batch the request if (context.isBatched) { // we are in a batch, so add to batch, remove dependency, and resolve with the batch's promise const p = context.batch.add(context.requestAbsoluteUrl, context.verb, context.options, context.parser); // we release the dependency here to ensure the batch does not execute until the request is added to the batch context.batchDependency(); Logger.write(`[${context.requestId}] (${(new Date()).getTime()}) Batching request in batch ${context.batch.batchId}.`, LogLevel.Info); // we set the result as the promise which will be resolved by the batch's execution resolve(setResult(context, p)); } else { Logger.write(`[${context.requestId}] (${(new Date()).getTime()}) Sending request.`, LogLevel.Info); // we are not part of a batch, so proceed as normal const client = context.clientFactory(); const opts = Util.extend(context.options || {}, { method: context.verb }); client.fetch(context.requestAbsoluteUrl, opts) .then(response => context.parser.parse(response)) .then(result => setResult(context, result)) .then(ctx => resolve(ctx)) .catch(e => reject(e)); } }); } /** * Logs the end of the request */ static logEnd(context) { return new Promise(resolve => { if (context.isBatched) { Logger.log({ data: Logger.activeLogLevel === LogLevel.Info ? {} : context, level: LogLevel.Info, message: `[${context.requestId}] (${(new Date()).getTime()}) ${context.verb} request will complete in batch ${context.batch.batchId}.`, }); } else { Logger.log({ data: Logger.activeLogLevel === LogLevel.Info ? {} : context, level: LogLevel.Info, message: `[${context.requestId}] (${(new Date()).getTime()}) Completing ${context.verb} request.`, }); } resolve(context); }); } static get default() { return [ PipelineMethods.logStart, PipelineMethods.caching, PipelineMethods.send, PipelineMethods.logEnd, ]; } } __decorate([ requestPipelineMethod(true) ], PipelineMethods, "logStart", null); __decorate([ requestPipelineMethod() ], PipelineMethods, "caching", null); __decorate([ requestPipelineMethod() ], PipelineMethods, "send", null); __decorate([ requestPipelineMethod(true) ], PipelineMethods, "logEnd", null); class ODataQueryable { constructor() { this._batch = null; this._query = new Dictionary(); this._options = {}; this._url = ""; this._parentUrl = ""; this._useCaching = false; this._cachingOptions = null; } /** * Directly concatonates the supplied string to the current url, not normalizing "/" chars * * @param pathPart The string to concatonate to the url */ concat(pathPart) { this._url += pathPart; return this; } /** * Provides access to the query builder for this url * */ get query() { return this._query; } /** * Sets custom options for current object and all derived objects accessible via chaining * * @param options custom options */ configure(options) { mergeOptions(this._options, options); return this; } /** * Enables caching for this request * * @param options Defines the options used when caching this request */ usingCaching(options) { if (!RuntimeConfig.globalCacheDisable) { this._useCaching = true; if (typeof options !== "undefined") { this._cachingOptions = options; } } return this; } /** * Adds this query to the supplied batch * * @example * ``` * * let b = pnp.sp.createBatch(); * pnp.sp.web.inBatch(b).get().then(...); * b.execute().then(...) * ``` */ inBatch(batch) { if (this.batch !== null) { throw new AlreadyInBatchException(); } this._batch = batch; return this; } /** * Gets the currentl url, made absolute based on the availability of the _spPageContextInfo object * */ toUrl() { return this._url; } /** * Executes the currently built request * * @param parser Allows you to specify a parser to handle the result * @param getOptions The options used for this request */ get(parser = new ODataDefaultParser(), options = {}) { return this.toRequestContext("GET", options, parser, PipelineMethods.default).then(context => pipe(context)); } getAs(parser = new ODataDefaultParser(), options = {}) { return this.toRequestContext("GET", options, parser, PipelineMethods.default).then(context => pipe(context)); } postCore(options = {}, parser = new ODataDefaultParser()) { return this.toRequestContext("POST", options, parser, PipelineMethods.default).then(context => pipe(context)); } postAsCore(options = {}, parser = new ODataDefaultParser()) { return this.toRequestContext("POST", options, parser, PipelineMethods.default).then(context => pipe(context)); } patchCore(options = {}, parser = new ODataDefaultParser()) { return this.toRequestContext("PATCH", options, parser, PipelineMethods.default).then(context => pipe(context)); } deleteCore(options = {}, parser = new ODataDefaultParser()) { return this.toRequestContext("DELETE", options, parser, PipelineMethods.default).then(context => pipe(context)); } /** * Blocks a batch call from occuring, MUST be cleared by calling the returned function */ addBatchDependency() { if (this._batch !== null) { return this._batch.addDependency(); } return () => null; } /** * Indicates if the current query has a batch associated * */ get hasBatch() { return Util.objectDefinedNotNull(this._batch); } /** * The batch currently associated with this query or null * */ get batch() { return this.hasBatch ? this._batch : null; } /** * Appends the given string and normalizes "/" chars * * @param pathPart The string to append */ append(pathPart) { this._url = Util.combinePaths(this._url, pathPart); } /** * Gets the parent url used when creating this instance * */ get parentUrl() { return this._parentUrl; } } class ODataBatch { constructor(_batchId = Util.getGUID()) { this._batchId = _batchId; this._requests = []; this._dependencies = []; } get batchId() { return this._batchId; } /** * The requests contained in this batch */ get requests() { return this._requests; } /** * * @param url Request url * @param method Request method (GET, POST, etc) * @param options Any request options * @param parser The parser used to handle the eventual return from the query */ add(url, method, options, parser) { const info = { method: method.toUpperCase(), options: options, parser: parser, reject: null, resolve: null, url: url, }; const p = new Promise((resolve, reject) => { info.resolve = resolve; info.reject = reject; }); this._requests.push(info); return p; } /** * Adds a dependency insuring that some set of actions will occur before a batch is processed. * MUST be cleared using the returned resolve delegate to allow batches to run */ addDependency() { let resolver = () => void (0); const promise = new Promise((resolve) => { resolver = resolve; }); this._dependencies.push(promise); return resolver; } /** * Execute the current batch and resolve the associated promises * * @returns A promise which will be resolved once all of the batch's child promises have resolved */ execute() { // we need to check the dependencies twice due to how different engines handle things. // We can get a second set of promises added after the first set resolve return Promise.all(this._dependencies).then(() => Promise.all(this._dependencies)).then(() => this.executeImpl()); } } export { CachingOptions, CachingParserWrapper, ODataParserBase, ProcessHttpClientResponseException, AlreadyInBatchException, ODataDefaultParser, ODataValue, ODataRawParserImpl, ODataRaw, TextFileParser, BlobFileParser, JSONFileParser, BufferFileParser, setResult, pipe, requestPipelineMethod, PipelineMethods, ODataQueryable, ODataBatch }; //# sourceMappingURL=odata.js.map
/** @license * @pnp/common v1.0.4-3 - pnp - provides shared functionality across all pnp libraries * MIT (https://github.com/pnp/pnp/blob/master/LICENSE) * Copyright (c) 2018 Microsoft * docs: https://pnp.github.io/pnp/ * source: https://github.com/pnp/pnp * bugs: https://github.com/pnp/pnp/issues */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('tslib'), require('adal-angular'), require('@pnp/logging')) : typeof define === 'function' && define.amd ? define(['exports', 'tslib', 'adal-angular', '@pnp/logging'], factory) : (factory((global.pnp = global.pnp || {}, global.pnp.common = {}),global.tslib_1,global.adal,global.pnp.logging)); }(this, (function (exports,tslib_1,adal,logging) { 'use strict'; /** * Gets a callback function which will maintain context across async calls. * Allows for the calling pattern getCtxCallback(thisobj, method, methodarg1, methodarg2, ...) * * @param context The object that will be the 'this' value in the callback * @param method The method to which we will apply the context and parameters * @param params Optional, additional arguments to supply to the wrapped method when it is invoked */ function getCtxCallback(context, method) { var params = []; for (var _i = 2; _i < arguments.length; _i++) { params[_i - 2] = arguments[_i]; } return function () { method.apply(context, params); }; } /** * Adds a value to a date * * @param date The date to which we will add units, done in local time * @param interval The name of the interval to add, one of: ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second'] * @param units The amount to add to date of the given interval * * http://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object */ function dateAdd(date, interval, units) { var ret = new Date(date); // don't change original date switch (interval.toLowerCase()) { case "year": ret.setFullYear(ret.getFullYear() + units); break; case "quarter": ret.setMonth(ret.getMonth() + 3 * units); break; case "month": ret.setMonth(ret.getMonth() + units); break; case "week": ret.setDate(ret.getDate() + 7 * units); break; case "day": ret.setDate(ret.getDate() + units); break; case "hour": ret.setTime(ret.getTime() + units * 3600000); break; case "minute": ret.setTime(ret.getTime() + units * 60000); break; case "second": ret.setTime(ret.getTime() + units * 1000); break; default: ret = undefined; break; } return ret; } /** * Combines an arbitrary set of paths ensuring and normalizes the slashes * * @param paths 0 to n path parts to combine */ function combinePaths() { var paths = []; for (var _i = 0; _i < arguments.length; _i++) { paths[_i] = arguments[_i]; } return paths .filter(function (path) { return !stringIsNullOrEmpty(path); }) .map(function (path) { return path.replace(/^[\\|\/]/, "").replace(/[\\|\/]$/, ""); }) .join("/") .replace(/\\/g, "/"); } /** * Gets a random string of chars length * * https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript * * @param chars The length of the random string to generate */ function getRandomString(chars) { var text = new Array(chars); var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i < chars; i++) { text[i] = possible.charAt(Math.floor(Math.random() * possible.length)); } return text.join(""); } /** * Gets a random GUID value * * http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript */ /* tslint:disable no-bitwise */ function getGUID() { var d = new Date().getTime(); var guid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === "x" ? r : (r & 0x3 | 0x8)).toString(16); }); return guid; } /* tslint:enable */ /** * Determines if a given value is a function * * @param cf The thing to test for functionness */ function isFunc(cf) { return typeof cf === "function"; } /** * Determines if an object is both defined and not null * @param obj Object to test */ function objectDefinedNotNull(obj) { return typeof obj !== "undefined" && obj !== null; } /** * @returns whether the provided parameter is a JavaScript Array or not. */ function isArray(array) { if (Array.isArray) { return Array.isArray(array); } return array && typeof array.length === "number" && array.constructor === Array; } /** * Provides functionality to extend the given object by doing a shallow copy * * @param target The object to which properties will be copied * @param source The source object from which properties will be copied * @param noOverwrite If true existing properties on the target are not overwritten from the source * */ function extend(target, source, noOverwrite) { if (noOverwrite === void 0) { noOverwrite = false; } if (!objectDefinedNotNull(source)) { return target; } // ensure we don't overwrite things we don't want overwritten var check = noOverwrite ? function (o, i) { return !(i in o); } : function () { return true; }; return Object.getOwnPropertyNames(source) .filter(function (v) { return check(target, v); }) .reduce(function (t, v) { t[v] = source[v]; return t; }, target); } /** * Determines if a given url is absolute * * @param url The url to check to see if it is absolute */ function isUrlAbsolute(url) { return /^https?:\/\/|^\/\//i.test(url); } /** * Determines if a string is null or empty or undefined * * @param s The string to test */ function stringIsNullOrEmpty(s) { return typeof s === "undefined" || s === null || s.length < 1; } var Util = /** @class */ (function () { function Util() { } /** * Gets a callback function which will maintain context across async calls. * Allows for the calling pattern getCtxCallback(thisobj, method, methodarg1, methodarg2, ...) * * @param context The object that will be the 'this' value in the callback * @param method The method to which we will apply the context and parameters * @param params Optional, additional arguments to supply to the wrapped method when it is invoked */ Util.getCtxCallback = getCtxCallback; /** * Adds a value to a date * * @param date The date to which we will add units, done in local time * @param interval The name of the interval to add, one of: ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second'] * @param units The amount to add to date of the given interval * * http://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object */ Util.dateAdd = dateAdd; /** * Combines an arbitrary set of paths ensuring and normalizes the slashes * * @param paths 0 to n path parts to combine */ Util.combinePaths = combinePaths; /** * Gets a random string of chars length * * @param chars The length of the random string to generate */ Util.getRandomString = getRandomString; /** * Gets a random GUID value * * http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript */ Util.getGUID = getGUID; /** * Determines if a given value is a function * * @param cf The thing to test for functionness */ Util.isFunc = isFunc; /** * Determines if an object is both defined and not null * @param obj Object to test */ Util.objectDefinedNotNull = objectDefinedNotNull; /** * @returns whether the provided parameter is a JavaScript Array or not. */ Util.isArray = isArray; /** * Provides functionality to extend the given object by doing a shallow copy * * @param target The object to which properties will be copied * @param source The source object from which properties will be copied * @param noOverwrite If true existing properties on the target are not overwritten from the source * */ Util.extend = extend; /** * Determines if a given url is absolute * * @param url The url to check to see if it is absolute */ Util.isUrlAbsolute = isUrlAbsolute; /** * Determines if a string is null or empty or undefined * * @param s The string to test */ Util.stringIsNullOrEmpty = stringIsNullOrEmpty; return Util; }()); function mergeHeaders(target, source) { if (typeof source !== "undefined" && source !== null) { var temp = new Request("", { headers: source }); temp.headers.forEach(function (value, name) { target.append(name, value); }); } } function mergeOptions(target, source) { if (objectDefinedNotNull(source)) { var headers = extend(target.headers || {}, source.headers); target = extend(target, source); target.headers = headers; } } /** * Makes requests using the global/window fetch API */ var FetchClient = /** @class */ (function () { function FetchClient() { } FetchClient.prototype.fetch = function (url, options) { return global.fetch(url, options); }; return FetchClient; }()); /** * Makes requests using the fetch API adding the supplied token to the Authorization header */ var BearerTokenFetchClient = /** @class */ (function (_super) { tslib_1.__extends(BearerTokenFetchClient, _super); function BearerTokenFetchClient(_token) { var _this = _super.call(this) || this; _this._token = _token; return _this; } Object.defineProperty(BearerTokenFetchClient.prototype, "token", { get: function () { return this._token; }, set: function (token) { this._token = token; }, enumerable: true, configurable: true }); BearerTokenFetchClient.prototype.fetch = function (url, options) { if (options === void 0) { options = {}; } var headers = new Headers(); mergeHeaders(headers, options.headers); headers.set("Authorization", "Bearer " + this._token); options.headers = headers; return _super.prototype.fetch.call(this, url, options); }; return BearerTokenFetchClient; }(FetchClient)); /** * Azure AD Client for use in the browser */ var AdalClient = /** @class */ (function (_super) { tslib_1.__extends(AdalClient, _super); /** * Creates a new instance of AdalClient * @param clientId Azure App Id * @param tenant Office 365 tenant (Ex: {tenant}.onmicrosoft.com) * @param redirectUri The redirect url used to authenticate the */ function AdalClient(clientId, tenant, redirectUri) { var _this = _super.call(this, null) || this; _this.clientId = clientId; _this.tenant = tenant; _this.redirectUri = redirectUri; return _this; } /** * Creates a new AdalClient using the values of the supplied SPFx context * * @param spfxContext Current SPFx context * @param clientId Optional client id to use instead of the built-in SPFx id * @description Using this method and the default clientId requires that the features described in * this article https://docs.microsoft.com/en-us/sharepoint/dev/spfx/use-aadhttpclient are activated in the tenant. If not you can * creat your own app, grant permissions and use that clientId here along with the SPFx context */ AdalClient.fromSPFxContext = function (spfxContext, cliendId) { if (cliendId === void 0) { cliendId = "c58637bb-e2e1-4312-8a00-04b5ffcd3403"; } // this "magic" client id is the one to which permissions are granted behind the scenes // this redirectUrl is the page as used by spfx return new AdalClient(cliendId, spfxContext.pageContext.aadInfo.tenantId.toString(), combinePaths(window.location.origin, "/_forms/spfxsinglesignon.aspx")); }; /** * Conducts the fetch opertation against the AAD secured resource * * @param url Absolute URL for the request * @param options Any fetch options passed to the underlying fetch implementation */ AdalClient.prototype.fetch = function (url, options) { var _this = this; if (!isUrlAbsolute(url)) { throw new Error("You must supply absolute urls to AdalClient.fetch."); } // the url we are calling is the resource return this.getToken(this.getResource(url)).then(function (token) { _this.token = token; return _super.prototype.fetch.call(_this, url, options); }); }; /** * Gets a token based on the current user * * @param resource The resource for which we are requesting a token */ AdalClient.prototype.getToken = function (resource) { var _this = this; return new Promise(function (resolve, reject) { _this.ensureAuthContext().then(function (_) { return _this.login(); }).then(function (_) { AdalClient._authContext.acquireToken(resource, function (message, token) { if (message) { return reject(new Error(message)); } resolve(token); }); }).catch(reject); }); }; /** * Ensures we have created and setup the adal AuthenticationContext instance */ AdalClient.prototype.ensureAuthContext = function () { var _this = this; return new Promise(function (resolve) { if (AdalClient._authContext === null) { AdalClient._authContext = adal.inject({ clientId: _this.clientId, displayCall: function (url) { if (_this._displayCallback) { _this._displayCallback(url); } }, navigateToLoginRequestUrl: false, redirectUri: _this.redirectUri, tenant: _this.tenant, }); } resolve(); }); }; /** * Ensures the current user is logged in */ AdalClient.prototype.login = function () { var _this = this; if (this._loginPromise) { return this._loginPromise; } this._loginPromise = new Promise(function (resolve, reject) { if (AdalClient._authContext.getCachedUser()) { return resolve(); } _this._displayCallback = function (url) { var popupWindow = window.open(url, "login", "width=483, height=600"); if (!popupWindow) { return reject(new Error("Could not open pop-up window for auth. Likely pop-ups are blocked by the browser.")); } if (popupWindow && popupWindow.focus) { popupWindow.focus(); } var pollTimer = window.setInterval(function () { if (!popupWindow || popupWindow.closed || popupWindow.closed === undefined) { window.clearInterval(pollTimer); } try { if (popupWindow.document.URL.indexOf(_this.redirectUri) !== -1) { window.clearInterval(pollTimer); AdalClient._authContext.handleWindowCallback(popupWindow.location.hash); popupWindow.close(); resolve(); } } catch (e) { reject(e); } }, 30); }; // this triggers the login process _this.ensureAuthContext().then(function (_) { AdalClient._authContext._loginInProgress = false; AdalClient._authContext.login(); _this._displayCallback = null; }); }); return this._loginPromise; }; /** * Parses out the root of the request url to use as the resource when getting the token * * After: https://gist.github.com/jlong/2428561 * @param url The url to parse */ AdalClient.prototype.getResource = function (url) { var parser = document.createElement("a"); parser.href = url; return parser.protocol + "//" + parser.hostname; }; /** * Our auth context */ AdalClient._authContext = null; return AdalClient; }(BearerTokenFetchClient)); /** * Reads a blob as text * * @param blob The data to read */ function readBlobAsText(blob) { return readBlobAs(blob, "string"); } /** * Reads a blob into an array buffer * * @param blob The data to read */ function readBlobAsArrayBuffer(blob) { return readBlobAs(blob, "buffer"); } /** * Generic method to read blob's content * * @param blob The data to read * @param mode The read mode */ function readBlobAs(blob, mode) { return new Promise(function (resolve, reject) { try { var reader = new FileReader(); reader.onload = function (e) { resolve(e.target.result); }; switch (mode) { case "string": reader.readAsText(blob); break; case "buffer": reader.readAsArrayBuffer(blob); break; } } catch (e) { reject(e); } }); } /** * Generic dictionary */ var Dictionary = /** @class */ (function () { /** * Creates a new instance of the Dictionary<T> class * * @constructor */ function Dictionary(keys, values) { if (keys === void 0) { keys = []; } if (values === void 0) { values = []; } this.keys = keys; this.values = values; } /** * Gets a value from the collection using the specified key * * @param key The key whose value we want to return, returns null if the key does not exist */ Dictionary.prototype.get = function (key) { var index = this.keys.indexOf(key); if (index < 0) { return null; } return this.values[index]; }; /** * Adds the supplied key and value to the dictionary * * @param key The key to add * @param o The value to add */ Dictionary.prototype.add = function (key, o) { var index = this.keys.indexOf(key); if (index > -1) { if (o === null) { this.remove(key); } else { this.values[index] = o; } } else { if (o !== null) { this.keys.push(key); this.values.push(o); } } }; /** * Merges the supplied typed hash into this dictionary instance. Existing values are updated and new ones are created as appropriate. */ Dictionary.prototype.merge = function (source) { var _this = this; if ("getKeys" in source) { var sourceAsDictionary_1 = source; sourceAsDictionary_1.getKeys().map(function (key) { _this.add(key, sourceAsDictionary_1.get(key)); }); } else { var sourceAsHash = source; for (var key in sourceAsHash) { if (sourceAsHash.hasOwnProperty(key)) { this.add(key, sourceAsHash[key]); } } } }; /** * Removes a value from the dictionary * * @param key The key of the key/value pair to remove. Returns null if the key was not found. */ Dictionary.prototype.remove = function (key) { var index = this.keys.indexOf(key); if (index < 0) { return null; } var val = this.values[index]; this.keys.splice(index, 1); this.values.splice(index, 1); return val; }; /** * Returns all the keys currently in the dictionary as an array */ Dictionary.prototype.getKeys = function () { return this.keys; }; /** * Returns all the values currently in the dictionary as an array */ Dictionary.prototype.getValues = function () { return this.values; }; /** * Clears the current dictionary */ Dictionary.prototype.clear = function () { this.keys = []; this.values = []; }; Object.defineProperty(Dictionary.prototype, "count", { /** * Gets a count of the items currently in the dictionary */ get: function () { return this.keys.length; }, enumerable: true, configurable: true }); return Dictionary; }()); function deprecated(deprecationVersion, message) { return function (target, propertyKey, descriptor) { var method = descriptor.value; descriptor.value = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } logging.Logger.log({ data: { descriptor: descriptor, propertyKey: propertyKey, target: target, }, level: 2 /* Warning */, message: "(" + deprecationVersion + ") " + message, }); return method.apply(this, args); }; }; } function beta(message) { if (message === void 0) { message = "This feature is flagged as beta and is subject to change."; } return function (target, propertyKey, descriptor) { var method = descriptor.value; descriptor.value = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } logging.Logger.log({ data: { descriptor: descriptor, propertyKey: propertyKey, target: target, }, level: 2 /* Warning */, message: message, }); return method.apply(this, args); }; }; } var UrlException = /** @class */ (function (_super) { tslib_1.__extends(UrlException, _super); function UrlException(msg) { var _this = _super.call(this, msg) || this; _this.name = "UrlException"; logging.Logger.log({ data: {}, level: 3 /* Error */, message: "[" + _this.name + "]::" + _this.message }); return _this; } return UrlException; }(Error)); function setup(config) { RuntimeConfig.extend(config); } var RuntimeConfigImpl = /** @class */ (function () { function RuntimeConfigImpl() { this._v = new Dictionary(); // setup defaults this._v.add("defaultCachingStore", "session"); this._v.add("defaultCachingTimeoutSeconds", 60); this._v.add("globalCacheDisable", false); this._v.add("enableCacheExpiration", false); this._v.add("cacheExpirationIntervalMilliseconds", 750); this._v.add("spfxContext", null); } /** * * @param config The set of properties to add to the globa configuration instance */ RuntimeConfigImpl.prototype.extend = function (config) { var _this = this; Object.keys(config).forEach(function (key) { _this._v.add(key, config[key]); }); }; RuntimeConfigImpl.prototype.get = function (key) { return this._v.get(key); }; Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingStore", { get: function () { return this.get("defaultCachingStore"); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingTimeoutSeconds", { get: function () { return this.get("defaultCachingTimeoutSeconds"); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "globalCacheDisable", { get: function () { return this.get("globalCacheDisable"); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "enableCacheExpiration", { get: function () { return this.get("enableCacheExpiration"); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "cacheExpirationIntervalMilliseconds", { get: function () { return this.get("cacheExpirationIntervalMilliseconds"); }, enumerable: true, configurable: true }); Object.defineProperty(RuntimeConfigImpl.prototype, "spfxContext", { get: function () { return this.get("spfxContext"); }, enumerable: true, configurable: true }); return RuntimeConfigImpl; }()); var _runtimeConfig = new RuntimeConfigImpl(); var RuntimeConfig = _runtimeConfig; /** * A wrapper class to provide a consistent interface to browser based storage * */ var PnPClientStorageWrapper = /** @class */ (function () { /** * Creates a new instance of the PnPClientStorageWrapper class * * @constructor */ function PnPClientStorageWrapper(store, defaultTimeoutMinutes) { if (defaultTimeoutMinutes === void 0) { defaultTimeoutMinutes = -1; } this.store = store; this.defaultTimeoutMinutes = defaultTimeoutMinutes; this.enabled = this.test(); // if the cache timeout is enabled call the handler // this will clear any expired items and set the timeout function if (RuntimeConfig.enableCacheExpiration) { logging.Logger.write("Enabling cache expiration.", 1 /* Info */); this.cacheExpirationHandler(); } } /** * Get a value from storage, or null if that value does not exist * * @param key The key whose value we want to retrieve */ PnPClientStorageWrapper.prototype.get = function (key) { if (!this.enabled) { return null; } var o = this.store.getItem(key); if (o == null) { return null; } var persistable = JSON.parse(o); if (new Date(persistable.expiration) <= new Date()) { logging.Logger.write("Removing item with key '" + key + "' from cache due to expiration.", 1 /* Info */); this.delete(key); return null; } else { return persistable.value; } }; /** * Adds a value to the underlying storage * * @param key The key to use when storing the provided value * @param o The value to store * @param expire Optional, if provided the expiration of the item, otherwise the default is used */ PnPClientStorageWrapper.prototype.put = function (key, o, expire) { if (this.enabled) { this.store.setItem(key, this.createPersistable(o, expire)); } }; /** * Deletes a value from the underlying storage * * @param key The key of the pair we want to remove from storage */ PnPClientStorageWrapper.prototype.delete = function (key) { if (this.enabled) { this.store.removeItem(key); } }; /** * Gets an item from the underlying storage, or adds it if it does not exist using the supplied getter function * * @param key The key to use when storing the provided value * @param getter A function which will upon execution provide the desired value * @param expire Optional, if provided the expiration of the item, otherwise the default is used */ PnPClientStorageWrapper.prototype.getOrPut = function (key, getter, expire) { var _this = this; if (!this.enabled) { return getter(); } return new Promise(function (resolve) { var o = _this.get(key); if (o == null) { getter().then(function (d) { _this.put(key, d, expire); resolve(d); }); } else { resolve(o); } }); }; /** * Deletes any expired items placed in the store by the pnp library, leaves other items untouched */ PnPClientStorageWrapper.prototype.deleteExpired = function () { var _this = this; return new Promise(function (resolve, reject) { if (!_this.enabled) { resolve(); } try { for (var i = 0; i < _this.store.length; i++) { var key = _this.store.key(i); if (key !== null) { // test the stored item to see if we stored it if (/["|']?pnp["|']? ?: ?1/i.test(_this.store.getItem(key))) { // get those items as get will delete from cache if they are expired _this.get(key); } } } resolve(); } catch (e) { reject(e); } }); }; /** * Used to determine if the wrapped storage is available currently */ PnPClientStorageWrapper.prototype.test = function () { var str = "test"; try { this.store.setItem(str, str); this.store.removeItem(str); return true; } catch (e) { return false; } }; /** * Creates the persistable to store */ PnPClientStorageWrapper.prototype.createPersistable = function (o, expire) { if (typeof expire === "undefined") { // ensure we are by default inline with the global library setting var defaultTimeout = RuntimeConfig.defaultCachingTimeoutSeconds; if (this.defaultTimeoutMinutes > 0) { defaultTimeout = this.defaultTimeoutMinutes * 60; } expire = dateAdd(new Date(), "second", defaultTimeout); } return JSON.stringify({ pnp: 1, expiration: expire, value: o }); }; /** * Deletes expired items added by this library in this.store and sets a timeout to call itself */ PnPClientStorageWrapper.prototype.cacheExpirationHandler = function () { var _this = this; logging.Logger.write("Called cache expiration handler.", 0 /* Verbose */); this.deleteExpired().then(function (_) { // call ourself in the future setTimeout(getCtxCallback(_this, _this.cacheExpirationHandler), RuntimeConfig.cacheExpirationIntervalMilliseconds); }).catch(function (e) { // we've got some error - so just stop the loop and report the error logging.Logger.log({ data: e, level: 3 /* Error */, message: "Error deleting expired cache entries, see data for details. Timeout not reset.", }); }); }; return PnPClientStorageWrapper; }()); /** * A thin implementation of in-memory storage for use in nodejs */ var MemoryStorage = /** @class */ (function () { function MemoryStorage(_store) { if (_store === void 0) { _store = new Dictionary(); } this._store = _store; } Object.defineProperty(MemoryStorage.prototype, "length", { get: function () { return this._store.count; }, enumerable: true, configurable: true }); MemoryStorage.prototype.clear = function () { this._store.clear(); }; MemoryStorage.prototype.getItem = function (key) { return this._store.get(key); }; MemoryStorage.prototype.key = function (index) { return this._store.getKeys()[index]; }; MemoryStorage.prototype.removeItem = function (key) { this._store.remove(key); }; MemoryStorage.prototype.setItem = function (key, data) { this._store.add(key, data); }; return MemoryStorage; }()); /** * A class that will establish wrappers for both local and session storage */ var PnPClientStorage = /** @class */ (function () { /** * Creates a new instance of the PnPClientStorage class * * @constructor */ function PnPClientStorage(_local, _session) { if (_local === void 0) { _local = null; } if (_session === void 0) { _session = null; } this._local = _local; this._session = _session; } Object.defineProperty(PnPClientStorage.prototype, "local", { /** * Provides access to the local storage of the browser */ get: function () { if (this._local === null) { this._local = typeof localStorage !== "undefined" ? new PnPClientStorageWrapper(localStorage) : new PnPClientStorageWrapper(new MemoryStorage()); } return this._local; }, enumerable: true, configurable: true }); Object.defineProperty(PnPClientStorage.prototype, "session", { /** * Provides access to the session storage of the browser */ get: function () { if (this._session === null) { this._session = typeof sessionStorage !== "undefined" ? new PnPClientStorageWrapper(sessionStorage) : new PnPClientStorageWrapper(new MemoryStorage()); } return this._session; }, enumerable: true, configurable: true }); return PnPClientStorage; }()); exports.AdalClient = AdalClient; exports.readBlobAsText = readBlobAsText; exports.readBlobAsArrayBuffer = readBlobAsArrayBuffer; exports.Dictionary = Dictionary; exports.deprecated = deprecated; exports.beta = beta; exports.UrlException = UrlException; exports.setup = setup; exports.RuntimeConfigImpl = RuntimeConfigImpl; exports.RuntimeConfig = RuntimeConfig; exports.mergeHeaders = mergeHeaders; exports.mergeOptions = mergeOptions; exports.FetchClient = FetchClient; exports.BearerTokenFetchClient = BearerTokenFetchClient; exports.PnPClientStorageWrapper = PnPClientStorageWrapper; exports.PnPClientStorage = PnPClientStorage; exports.getCtxCallback = getCtxCallback; exports.dateAdd = dateAdd; exports.combinePaths = combinePaths; exports.getRandomString = getRandomString; exports.getGUID = getGUID; exports.isFunc = isFunc; exports.objectDefinedNotNull = objectDefinedNotNull; exports.isArray = isArray; exports.extend = extend; exports.isUrlAbsolute = isUrlAbsolute; exports.stringIsNullOrEmpty = stringIsNullOrEmpty; exports.Util = Util; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=common.es5.umd.js.map
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("a11yhelp","ug",{title:"قوشۇمچە چۈشەندۈرۈش",contents:"ياردەم مەزمۇنى. بۇ سۆزلەشكۈنى ياپماقچى بولسىڭىز ESC نى بېسىڭ.",legend:[{name:"ئادەتتىكى",items:[{name:"قورال بالداق تەھرىر",legend:"${toolbarFocus} بېسىلسا قورال بالداققا يېتەكلەيدۇ، TAB ياكى SHIFT+TAB ئارقىلىق قورال بالداق گۇرۇپپىسى تاللىنىدۇ، ئوڭ سول يا ئوقتا توپچا تاللىنىدۇ، بوشلۇق ياكى Enter كۇنۇپكىسىدا تاللانغان توپچىنى قوللىنىدۇ."},{name:"تەھرىرلىگۈچ سۆزلەشكۈسى",legend:"Inside a dialog, press TAB to navigate to the next dialog element, press SHIFT+TAB to move to the previous dialog element, press ENTER to submit the dialog, press ESC to cancel the dialog. When a dialog has multiple tabs, the tab list can be reached either with ALT+F10 or with TAB as part of the dialog tabbing order. With tab list focused, move to the next and previous tab with RIGHT and LEFT ARROW, respectively."}, {name:"تەھرىرلىگۈچ تىل مۇھىت تىزىملىكى",legend:"${contextMenu} ياكى ئەپ كۇنۇپكىسىدا تىل مۇھىت تىزىملىكىنى ئاچىدۇ. ئاندىن TAB ياكى ئاستى يا ئوق كۇنۇپكىسىدا كېيىنكى تىزىملىك تۈرىگە يۆتكەيدۇ؛ SHIFT+TAB ياكى ئۈستى يا ئوق كۇنۇپكىسىدا ئالدىنقى تىزىملىك تۈرىگە يۆتكەيدۇ. بوشلۇق ياكى ENTER كۇنۇپكىسىدا تىزىملىك تۈرىنى تاللايدۇ. بوشلۇق، ENTER ياكى ئوڭ يا ئوق كۇنۇپكىسىدا تارماق تىزىملىكنى ئاچىدۇ. قايتىش تىزىملىكىگە ESC ياكى سول يا ئوق كۇنۇپكىسى ئىشلىتىلىدۇ. ESC كۇنۇپكىسىدا تىل مۇھىت تىزىملىكى تاقىلىدۇ."},{name:"تەھرىرلىگۈچ تىزىمى", legend:"تىزىم قۇتىسىدا، كېيىنكى تىزىم تۈرىگە يۆتكەشتە TAB ياكى ئاستى يا ئوق كۇنۇپكىسى ئىشلىتىلىدۇ. ئالدىنقى تىزىم تۈرىگە يۆتكەشتە SHIFT+TAB ياكى ئۈستى يا ئوق كۇنۇپكىسى ئىشلىتىلىدۇ. بوشلۇق ياكى ENTER كۇنۇپكىسىدا تىزىم تۈرىنى تاللايدۇ.ESC كۇنۇپكىسىدا تىزىم قۇتىسىنى يىغىدۇ."},{name:"تەھرىرلىگۈچ ئېلېمېنت يول بالداق",legend:"${elementsPathFocus} بېسىلسا ئېلېمېنت يول بالداققا يېتەكلەيدۇ، TAB ياكى ئوڭ يا ئوقتا كېيىنكى ئېلېمېنت تاللىنىدۇ، SHIFT+TAB ياكى سول يا ئوقتا ئالدىنقى ئېلېمېنت تاللىنىدۇ، بوشلۇق ياكى Enter كۇنۇپكىسىدا تەھرىرلىگۈچتىكى ئېلېمېنت تاللىنىدۇ."}]}, {name:"بۇيرۇق",items:[{name:"بۇيرۇقتىن يېنىۋال",legend:"${undo} نى بېسىڭ"},{name:"قايتىلاش بۇيرۇقى",legend:"${redo} نى بېسىڭ"},{name:"توملىتىش بۇيرۇقى",legend:"${bold} نى بېسىڭ"},{name:"يانتۇ بۇيرۇقى",legend:"${italic} نى بېسىڭ"},{name:"ئاستى سىزىق بۇيرۇقى",legend:"${underline} نى بېسىڭ"},{name:"ئۇلانما بۇيرۇقى",legend:"${link} نى بېسىڭ"},{name:"قورال بالداق قاتلاش بۇيرۇقى",legend:"${toolbarCollapse} نى بېسىڭ"},{name:"ئالدىنقى فوكۇس نۇقتىسىنى زىيارەت قىلىدىغان بۇيرۇق",legend:"${accessPreviousSpace} بېسىپ ^ بەلگىسىگە ئەڭ يېقىن زىيارەت قىلغىلى بولمايدىغان فوكۇس نۇقتا رايونىنىڭ ئالدىنى زىيارەت قىلىدۇ، مەسىلەن: ئۆز ئارا قوشنا ئىككى HR ئېلېمېنت. بۇ بىرىكمە كۇنۇپكا تەكرارلانسا يىراقتىكى فوكۇس نۇقتا رايونىغا يەتكىلى بولىدۇ."}, {name:"كېيىنكى فوكۇس نۇقتىسىنى زىيارەت قىلىدىغان بۇيرۇق",legend:"${accessNextSpace} بېسىپ ^ بەلگىسىگە ئەڭ يېقىن زىيارەت قىلغىلى بولمايدىغان فوكۇس نۇقتا رايونىنىڭ كەينىنى زىيارەت قىلىدۇ، مەسىلەن: ئۆز ئارا قوشنا ئىككى HR ئېلېمېنت. بۇ بىرىكمە كۇنۇپكا تەكرارلانسا يىراقتىكى فوكۇس نۇقتا رايونىغا يەتكىلى بولىدۇ."},{name:"توسالغۇسىز لايىھە چۈشەندۈرۈشى",legend:"${a11yHelp} نى بېسىڭ"}]}],backspace:"Backspace",tab:"Tab",enter:"Enter",shift:"Shift",ctrl:"Ctrl",alt:"Alt",pause:"Pause",capslock:"Caps Lock",escape:"Escape", pageUp:"Page Up",pageDown:"Page Down",end:"End",home:"Home",leftArrow:"Left Arrow",upArrow:"Up Arrow",rightArrow:"Right Arrow",downArrow:"Down Arrow",insert:"Insert","delete":"Delete",leftWindowKey:"Left Windows key",rightWindowKey:"Right Windows key",selectKey:"Select key",numpad0:"Numpad 0",numpad1:"Numpad 1",numpad2:"Numpad 2",numpad3:"Numpad 3",numpad4:"Numpad 4",numpad5:"Numpad 5",numpad6:"Numpad 6",numpad7:"Numpad 7",numpad8:"Numpad 8",numpad9:"Numpad 9",multiply:"Multiply",add:"Add",subtract:"Subtract", decimalPoint:"Decimal Point",divide:"Divide",f1:"F1",f2:"F2",f3:"F3",f4:"F4",f5:"F5",f6:"F6",f7:"F7",f8:"F8",f9:"F9",f10:"F10",f11:"F11",f12:"F12",numLock:"Num Lock",scrollLock:"Scroll Lock",semiColon:"Semicolon",equalSign:"Equal Sign",comma:"Comma",dash:"Dash",period:"Period",forwardSlash:"Forward Slash",graveAccent:"Grave Accent",openBracket:"Open Bracket",backSlash:"Backslash",closeBracket:"Close Bracket",singleQuote:"Single Quote"});
const gulp = require('gulp'); // Default task gulp.task('default', [$1]);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.classScopingMode = exports.__controller = void 0; // exported for tests =( var __controller = { _noConflict: false, _isSet: false, get noConflict() { return this._noConflict; }, set noConflict(v) { if (this._isSet && v !== this.noConflict) { setTimeout(function () { throw new Error("[vkui]: Single VKUI instance can not have different globalClassName settings"); }, 0); } this._noConflict = v; this._isSet = true; } }; exports.__controller = __controller; var classScopingMode = __controller; exports.classScopingMode = classScopingMode; //# sourceMappingURL=classScopingMode.js.map
version https://git-lfs.github.com/spec/v1 oid sha256:c57b04ec1812cc626cc504fb30e65afa55f72e4a6a26cb9abca83704eb6235ec size 3948
/* global require,module */ 'use strict'; var glob = require('glob'); var Promise = require('promise'); var Spider = require('./spider'); var Compress = require('./compress'); var FontSpider = function (htmlFiles, options) { if (typeof htmlFiles === 'string') { htmlFiles = glob.sync(htmlFiles); } else if (Array.isArray(htmlFiles)) { var srcs = []; htmlFiles.forEach(function (item) { srcs = srcs.concat(glob.sync(item)); }); htmlFiles = srcs; } return new FontSpider.Spider(htmlFiles, options) .then(function (webFonts) { return Promise .all(webFonts.map(function (webFont) { return new FontSpider.Compress(webFont, options); })); }); }; FontSpider.Spider = Spider; FontSpider.Compress = Compress; FontSpider.defaults = {}; mix(FontSpider.defaults, Spider.defaults); mix(FontSpider.defaults, Compress.defaults); function mix (target, object) { Object.keys(object).forEach(function (key) { target[key] = object[key]; }); } module.exports = FontSpider;
import pathMatch from 'path-match' const route = pathMatch() export default class Router { constructor () { this.routes = new Map() } add (method, path, fn) { const routes = this.routes.get(method) || new Set() routes.add({ match: route(path), fn }) this.routes.set(method, routes) } match (req, res, parsedUrl) { const routes = this.routes.get(req.method) if (!routes) return const { pathname } = parsedUrl for (const r of routes) { const params = r.match(pathname) if (params) { return async () => { return r.fn(req, res, params, parsedUrl) } } } } }
;(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'; //! moment.js locale configuration moment.defineLocale('af', { months : 'Januarie_Februarie_Maart_April_Mei_Junie_Julie_Augustus_September_Oktober_November_Desember'.split('_'), monthsShort : 'Jan_Feb_Mrt_Apr_Mei_Jun_Jul_Aug_Sep_Okt_Nov_Des'.split('_'), weekdays : 'Sondag_Maandag_Dinsdag_Woensdag_Donderdag_Vrydag_Saterdag'.split('_'), weekdaysShort : 'Son_Maa_Din_Woe_Don_Vry_Sat'.split('_'), weekdaysMin : 'So_Ma_Di_Wo_Do_Vr_Sa'.split('_'), meridiemParse: /vm|nm/i, isPM : function (input) { return /^nm$/i.test(input); }, meridiem : function (hours, minutes, isLower) { if (hours < 12) { return isLower ? 'vm' : 'VM'; } else { return isLower ? 'nm' : 'NM'; } }, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay : '[Vandag om] LT', nextDay : '[Môre om] LT', nextWeek : 'dddd [om] LT', lastDay : '[Gister om] LT', lastWeek : '[Laas] dddd [om] LT', sameElse : 'L' }, relativeTime : { future : 'oor %s', past : '%s gelede', s : '\'n paar sekondes', ss : '%d sekondes', m : '\'n minuut', mm : '%d minute', h : '\'n uur', hh : '%d ure', d : '\'n dag', dd : '%d dae', M : '\'n maand', MM : '%d maande', y : '\'n jaar', yy : '%d jaar' }, dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, ordinal : function (number) { return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); // Thanks to Joris Röling : https://github.com/jjupiter }, week : { dow : 1, // Maandag is die eerste dag van die week. doy : 4 // Die week wat die 4de Januarie bevat is die eerste week van die jaar. } }); //! moment.js locale configuration moment.defineLocale('ar-dz', { months : 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), monthsShort : 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), weekdays : 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), weekdaysShort : 'احد_اثنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'), weekdaysMin : 'أح_إث_ثلا_أر_خم_جم_سب'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { sameDay: '[اليوم على الساعة] LT', nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime : { future : 'في %s', past : 'منذ %s', s : 'ثوان', ss : '%d ثانية', m : 'دقيقة', mm : '%d دقائق', h : 'ساعة', hh : '%d ساعات', d : 'يوم', dd : '%d أيام', M : 'شهر', MM : '%d أشهر', y : 'سنة', yy : '%d سنوات' }, week : { dow : 0, // Sunday is the first day of the week. doy : 4 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('ar-kw', { months : 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), monthsShort : 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), weekdays : 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), weekdaysShort : 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'), weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { sameDay: '[اليوم على الساعة] LT', nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime : { future : 'في %s', past : 'منذ %s', s : 'ثوان', ss : '%d ثانية', m : 'دقيقة', mm : '%d دقائق', h : 'ساعة', hh : '%d ساعات', d : 'يوم', dd : '%d أيام', M : 'شهر', MM : '%d أشهر', y : 'سنة', yy : '%d سنوات' }, week : { dow : 0, // Sunday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration var symbolMap = { '1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7', '8': '8', '9': '9', '0': '0' }, pluralForm = function (n) { return n === 0 ? 0 : n === 1 ? 1 : n === 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5; }, plurals = { s : ['أقل من ثانية', 'ثانية واحدة', ['ثانيتان', 'ثانيتين'], '%d ثوان', '%d ثانية', '%d ثانية'], m : ['أقل من دقيقة', 'دقيقة واحدة', ['دقيقتان', 'دقيقتين'], '%d دقائق', '%d دقيقة', '%d دقيقة'], h : ['أقل من ساعة', 'ساعة واحدة', ['ساعتان', 'ساعتين'], '%d ساعات', '%d ساعة', '%d ساعة'], d : ['أقل من يوم', 'يوم واحد', ['يومان', 'يومين'], '%d أيام', '%d يومًا', '%d يوم'], M : ['أقل من شهر', 'شهر واحد', ['شهران', 'شهرين'], '%d أشهر', '%d شهرا', '%d شهر'], y : ['أقل من عام', 'عام واحد', ['عامان', 'عامين'], '%d أعوام', '%d عامًا', '%d عام'] }, pluralize = function (u) { return function (number, withoutSuffix, string, isFuture) { var f = pluralForm(number), str = plurals[u][pluralForm(number)]; if (f === 2) { str = str[withoutSuffix ? 0 : 1]; } return str.replace(/%d/i, number); }; }, months = [ 'يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر' ]; moment.defineLocale('ar-ly', { months : months, monthsShort : months, weekdays : 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), weekdaysShort : 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'D/\u200FM/\u200FYYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, meridiemParse: /ص|م/, isPM : function (input) { return 'م' === input; }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return 'ص'; } else { return 'م'; } }, calendar : { sameDay: '[اليوم عند الساعة] LT', nextDay: '[غدًا عند الساعة] LT', nextWeek: 'dddd [عند الساعة] LT', lastDay: '[أمس عند الساعة] LT', lastWeek: 'dddd [عند الساعة] LT', sameElse: 'L' }, relativeTime : { future : 'بعد %s', past : 'منذ %s', s : pluralize('s'), ss : pluralize('s'), m : pluralize('m'), mm : pluralize('m'), h : pluralize('h'), hh : pluralize('h'), d : pluralize('d'), dd : pluralize('d'), M : pluralize('M'), MM : pluralize('M'), y : pluralize('y'), yy : pluralize('y') }, preparse: function (string) { return string.replace(/،/g, ','); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }).replace(/,/g, '،'); }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('ar-ma', { months : 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), monthsShort : 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split('_'), weekdays : 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), weekdaysShort : 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'), weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { sameDay: '[اليوم على الساعة] LT', nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime : { future : 'في %s', past : 'منذ %s', s : 'ثوان', ss : '%d ثانية', m : 'دقيقة', mm : '%d دقائق', h : 'ساعة', hh : '%d ساعات', d : 'يوم', dd : '%d أيام', M : 'شهر', MM : '%d أشهر', y : 'سنة', yy : '%d سنوات' }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration var symbolMap$1 = { '1': '١', '2': '٢', '3': '٣', '4': '٤', '5': '٥', '6': '٦', '7': '٧', '8': '٨', '9': '٩', '0': '٠' }, numberMap = { '١': '1', '٢': '2', '٣': '3', '٤': '4', '٥': '5', '٦': '6', '٧': '7', '٨': '8', '٩': '9', '٠': '0' }; moment.defineLocale('ar-sa', { months : 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), monthsShort : 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), weekdays : 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), weekdaysShort : 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, meridiemParse: /ص|م/, isPM : function (input) { return 'م' === input; }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return 'ص'; } else { return 'م'; } }, calendar : { sameDay: '[اليوم على الساعة] LT', nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime : { future : 'في %s', past : 'منذ %s', s : 'ثوان', ss : '%d ثانية', m : 'دقيقة', mm : '%d دقائق', h : 'ساعة', hh : '%d ساعات', d : 'يوم', dd : '%d أيام', M : 'شهر', MM : '%d أشهر', y : 'سنة', yy : '%d سنوات' }, preparse: function (string) { return string.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) { return numberMap[match]; }).replace(/،/g, ','); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap$1[match]; }).replace(/,/g, '،'); }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('ar-tn', { months: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), monthsShort: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'), weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'), weekdaysParseExact : true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D MMMM YYYY HH:mm' }, calendar: { sameDay: '[اليوم على الساعة] LT', nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime: { future: 'في %s', past: 'منذ %s', s: 'ثوان', ss : '%d ثانية', m: 'دقيقة', mm: '%d دقائق', h: 'ساعة', hh: '%d ساعات', d: 'يوم', dd: '%d أيام', M: 'شهر', MM: '%d أشهر', y: 'سنة', yy: '%d سنوات' }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var symbolMap$2 = { '1': '١', '2': '٢', '3': '٣', '4': '٤', '5': '٥', '6': '٦', '7': '٧', '8': '٨', '9': '٩', '0': '٠' }, numberMap$1 = { '١': '1', '٢': '2', '٣': '3', '٤': '4', '٥': '5', '٦': '6', '٧': '7', '٨': '8', '٩': '9', '٠': '0' }, pluralForm$1 = function (n) { return n === 0 ? 0 : n === 1 ? 1 : n === 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5; }, plurals$1 = { s : ['أقل من ثانية', 'ثانية واحدة', ['ثانيتان', 'ثانيتين'], '%d ثوان', '%d ثانية', '%d ثانية'], m : ['أقل من دقيقة', 'دقيقة واحدة', ['دقيقتان', 'دقيقتين'], '%d دقائق', '%d دقيقة', '%d دقيقة'], h : ['أقل من ساعة', 'ساعة واحدة', ['ساعتان', 'ساعتين'], '%d ساعات', '%d ساعة', '%d ساعة'], d : ['أقل من يوم', 'يوم واحد', ['يومان', 'يومين'], '%d أيام', '%d يومًا', '%d يوم'], M : ['أقل من شهر', 'شهر واحد', ['شهران', 'شهرين'], '%d أشهر', '%d شهرا', '%d شهر'], y : ['أقل من عام', 'عام واحد', ['عامان', 'عامين'], '%d أعوام', '%d عامًا', '%d عام'] }, pluralize$1 = function (u) { return function (number, withoutSuffix, string, isFuture) { var f = pluralForm$1(number), str = plurals$1[u][pluralForm$1(number)]; if (f === 2) { str = str[withoutSuffix ? 0 : 1]; } return str.replace(/%d/i, number); }; }, months$1 = [ 'يناير', 'فبراير', 'مارس', 'أبريل', 'مايو', 'يونيو', 'يوليو', 'أغسطس', 'سبتمبر', 'أكتوبر', 'نوفمبر', 'ديسمبر' ]; moment.defineLocale('ar', { months : months$1, monthsShort : months$1, weekdays : 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'), weekdaysShort : 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'), weekdaysMin : 'ح_ن_ث_ر_خ_ج_س'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'D/\u200FM/\u200FYYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, meridiemParse: /ص|م/, isPM : function (input) { return 'م' === input; }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return 'ص'; } else { return 'م'; } }, calendar : { sameDay: '[اليوم عند الساعة] LT', nextDay: '[غدًا عند الساعة] LT', nextWeek: 'dddd [عند الساعة] LT', lastDay: '[أمس عند الساعة] LT', lastWeek: 'dddd [عند الساعة] LT', sameElse: 'L' }, relativeTime : { future : 'بعد %s', past : 'منذ %s', s : pluralize$1('s'), ss : pluralize$1('s'), m : pluralize$1('m'), mm : pluralize$1('m'), h : pluralize$1('h'), hh : pluralize$1('h'), d : pluralize$1('d'), dd : pluralize$1('d'), M : pluralize$1('M'), MM : pluralize$1('M'), y : pluralize$1('y'), yy : pluralize$1('y') }, preparse: function (string) { return string.replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) { return numberMap$1[match]; }).replace(/،/g, ','); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap$2[match]; }).replace(/,/g, '،'); }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration var suffixes = { 1: '-inci', 5: '-inci', 8: '-inci', 70: '-inci', 80: '-inci', 2: '-nci', 7: '-nci', 20: '-nci', 50: '-nci', 3: '-üncü', 4: '-üncü', 100: '-üncü', 6: '-ncı', 9: '-uncu', 10: '-uncu', 30: '-uncu', 60: '-ıncı', 90: '-ıncı' }; moment.defineLocale('az', { months : 'yanvar_fevral_mart_aprel_may_iyun_iyul_avqust_sentyabr_oktyabr_noyabr_dekabr'.split('_'), monthsShort : 'yan_fev_mar_apr_may_iyn_iyl_avq_sen_okt_noy_dek'.split('_'), weekdays : 'Bazar_Bazar ertəsi_Çərşənbə axşamı_Çərşənbə_Cümə axşamı_Cümə_Şənbə'.split('_'), weekdaysShort : 'Baz_BzE_ÇAx_Çər_CAx_Cüm_Şən'.split('_'), weekdaysMin : 'Bz_BE_ÇA_Çə_CA_Cü_Şə'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay : '[bugün saat] LT', nextDay : '[sabah saat] LT', nextWeek : '[gələn həftə] dddd [saat] LT', lastDay : '[dünən] LT', lastWeek : '[keçən həftə] dddd [saat] LT', sameElse : 'L' }, relativeTime : { future : '%s sonra', past : '%s əvvəl', s : 'birneçə saniyyə', ss : '%d saniyə', m : 'bir dəqiqə', mm : '%d dəqiqə', h : 'bir saat', hh : '%d saat', d : 'bir gün', dd : '%d gün', M : 'bir ay', MM : '%d ay', y : 'bir il', yy : '%d il' }, meridiemParse: /gecə|səhər|gündüz|axşam/, isPM : function (input) { return /^(gündüz|axşam)$/.test(input); }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return 'gecə'; } else if (hour < 12) { return 'səhər'; } else if (hour < 17) { return 'gündüz'; } else { return 'axşam'; } }, dayOfMonthOrdinalParse: /\d{1,2}-(ıncı|inci|nci|üncü|ncı|uncu)/, ordinal : function (number) { if (number === 0) { // special case for zero return number + '-ıncı'; } var a = number % 10, b = number % 100 - a, c = number >= 100 ? 100 : null; return number + (suffixes[a] || suffixes[b] || suffixes[c]); }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration function plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'ss': withoutSuffix ? 'секунда_секунды_секунд' : 'секунду_секунды_секунд', 'mm': withoutSuffix ? 'хвіліна_хвіліны_хвілін' : 'хвіліну_хвіліны_хвілін', 'hh': withoutSuffix ? 'гадзіна_гадзіны_гадзін' : 'гадзіну_гадзіны_гадзін', 'dd': 'дзень_дні_дзён', 'MM': 'месяц_месяцы_месяцаў', 'yy': 'год_гады_гадоў' }; if (key === 'm') { return withoutSuffix ? 'хвіліна' : 'хвіліну'; } else if (key === 'h') { return withoutSuffix ? 'гадзіна' : 'гадзіну'; } else { return number + ' ' + plural(format[key], +number); } } moment.defineLocale('be', { months : { format: 'студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня'.split('_'), standalone: 'студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань'.split('_') }, monthsShort : 'студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж'.split('_'), weekdays : { format: 'нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу'.split('_'), standalone: 'нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота'.split('_'), isFormat: /\[ ?[Вв] ?(?:мінулую|наступную)? ?\] ?dddd/ }, weekdaysShort : 'нд_пн_ат_ср_чц_пт_сб'.split('_'), weekdaysMin : 'нд_пн_ат_ср_чц_пт_сб'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D MMMM YYYY г.', LLL : 'D MMMM YYYY г., HH:mm', LLLL : 'dddd, D MMMM YYYY г., HH:mm' }, calendar : { sameDay: '[Сёння ў] LT', nextDay: '[Заўтра ў] LT', lastDay: '[Учора ў] LT', nextWeek: function () { return '[У] dddd [ў] LT'; }, lastWeek: function () { switch (this.day()) { case 0: case 3: case 5: case 6: return '[У мінулую] dddd [ў] LT'; case 1: case 2: case 4: return '[У мінулы] dddd [ў] LT'; } }, sameElse: 'L' }, relativeTime : { future : 'праз %s', past : '%s таму', s : 'некалькі секунд', m : relativeTimeWithPlural, mm : relativeTimeWithPlural, h : relativeTimeWithPlural, hh : relativeTimeWithPlural, d : 'дзень', dd : relativeTimeWithPlural, M : 'месяц', MM : relativeTimeWithPlural, y : 'год', yy : relativeTimeWithPlural }, meridiemParse: /ночы|раніцы|дня|вечара/, isPM : function (input) { return /^(дня|вечара)$/.test(input); }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return 'ночы'; } else if (hour < 12) { return 'раніцы'; } else if (hour < 17) { return 'дня'; } else { return 'вечара'; } }, dayOfMonthOrdinalParse: /\d{1,2}-(і|ы|га)/, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': case 'w': case 'W': return (number % 10 === 2 || number % 10 === 3) && (number % 100 !== 12 && number % 100 !== 13) ? number + '-і' : number + '-ы'; case 'D': return number + '-га'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('bg', { months : 'януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември'.split('_'), monthsShort : 'янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек'.split('_'), weekdays : 'неделя_понеделник_вторник_сряда_четвъртък_петък_събота'.split('_'), weekdaysShort : 'нед_пон_вто_сря_чет_пет_съб'.split('_'), weekdaysMin : 'нд_пн_вт_ср_чт_пт_сб'.split('_'), longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'D.MM.YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY H:mm', LLLL : 'dddd, D MMMM YYYY H:mm' }, calendar : { sameDay : '[Днес в] LT', nextDay : '[Утре в] LT', nextWeek : 'dddd [в] LT', lastDay : '[Вчера в] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: case 6: return '[В изминалата] dddd [в] LT'; case 1: case 2: case 4: case 5: return '[В изминалия] dddd [в] LT'; } }, sameElse : 'L' }, relativeTime : { future : 'след %s', past : 'преди %s', s : 'няколко секунди', ss : '%d секунди', m : 'минута', mm : '%d минути', h : 'час', hh : '%d часа', d : 'ден', dd : '%d дни', M : 'месец', MM : '%d месеца', y : 'година', yy : '%d години' }, dayOfMonthOrdinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/, ordinal : function (number) { var lastDigit = number % 10, last2Digits = number % 100; if (number === 0) { return number + '-ев'; } else if (last2Digits === 0) { return number + '-ен'; } else if (last2Digits > 10 && last2Digits < 20) { return number + '-ти'; } else if (lastDigit === 1) { return number + '-ви'; } else if (lastDigit === 2) { return number + '-ри'; } else if (lastDigit === 7 || lastDigit === 8) { return number + '-ми'; } else { return number + '-ти'; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('bm', { months : 'Zanwuyekalo_Fewuruyekalo_Marisikalo_Awirilikalo_Mɛkalo_Zuwɛnkalo_Zuluyekalo_Utikalo_Sɛtanburukalo_ɔkutɔburukalo_Nowanburukalo_Desanburukalo'.split('_'), monthsShort : 'Zan_Few_Mar_Awi_Mɛ_Zuw_Zul_Uti_Sɛt_ɔku_Now_Des'.split('_'), weekdays : 'Kari_Ntɛnɛn_Tarata_Araba_Alamisa_Juma_Sibiri'.split('_'), weekdaysShort : 'Kar_Ntɛ_Tar_Ara_Ala_Jum_Sib'.split('_'), weekdaysMin : 'Ka_Nt_Ta_Ar_Al_Ju_Si'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'MMMM [tile] D [san] YYYY', LLL : 'MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm', LLLL : 'dddd MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm' }, calendar : { sameDay : '[Bi lɛrɛ] LT', nextDay : '[Sini lɛrɛ] LT', nextWeek : 'dddd [don lɛrɛ] LT', lastDay : '[Kunu lɛrɛ] LT', lastWeek : 'dddd [tɛmɛnen lɛrɛ] LT', sameElse : 'L' }, relativeTime : { future : '%s kɔnɔ', past : 'a bɛ %s bɔ', s : 'sanga dama dama', ss : 'sekondi %d', m : 'miniti kelen', mm : 'miniti %d', h : 'lɛrɛ kelen', hh : 'lɛrɛ %d', d : 'tile kelen', dd : 'tile %d', M : 'kalo kelen', MM : 'kalo %d', y : 'san kelen', yy : 'san %d' }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var symbolMap$3 = { '1': '১', '2': '২', '3': '৩', '4': '৪', '5': '৫', '6': '৬', '7': '৭', '8': '৮', '9': '৯', '0': '০' }, numberMap$2 = { '১': '1', '২': '2', '৩': '3', '৪': '4', '৫': '5', '৬': '6', '৭': '7', '৮': '8', '৯': '9', '০': '0' }; moment.defineLocale('bn', { months : 'জানুয়ারী_ফেব্রুয়ারি_মার্চ_এপ্রিল_মে_জুন_জুলাই_আগস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর'.split('_'), monthsShort : 'জানু_ফেব_মার্চ_এপ্র_মে_জুন_জুল_আগ_সেপ্ট_অক্টো_নভে_ডিসে'.split('_'), weekdays : 'রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পতিবার_শুক্রবার_শনিবার'.split('_'), weekdaysShort : 'রবি_সোম_মঙ্গল_বুধ_বৃহস্পতি_শুক্র_শনি'.split('_'), weekdaysMin : 'রবি_সোম_মঙ্গ_বুধ_বৃহঃ_শুক্র_শনি'.split('_'), longDateFormat : { LT : 'A h:mm সময়', LTS : 'A h:mm:ss সময়', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY, A h:mm সময়', LLLL : 'dddd, D MMMM YYYY, A h:mm সময়' }, calendar : { sameDay : '[আজ] LT', nextDay : '[আগামীকাল] LT', nextWeek : 'dddd, LT', lastDay : '[গতকাল] LT', lastWeek : '[গত] dddd, LT', sameElse : 'L' }, relativeTime : { future : '%s পরে', past : '%s আগে', s : 'কয়েক সেকেন্ড', ss : '%d সেকেন্ড', m : 'এক মিনিট', mm : '%d মিনিট', h : 'এক ঘন্টা', hh : '%d ঘন্টা', d : 'এক দিন', dd : '%d দিন', M : 'এক মাস', MM : '%d মাস', y : 'এক বছর', yy : '%d বছর' }, preparse: function (string) { return string.replace(/[১২৩৪৫৬৭৮৯০]/g, function (match) { return numberMap$2[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap$3[match]; }); }, meridiemParse: /রাত|সকাল|দুপুর|বিকাল|রাত/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if ((meridiem === 'রাত' && hour >= 4) || (meridiem === 'দুপুর' && hour < 5) || meridiem === 'বিকাল') { return hour + 12; } else { return hour; } }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return 'রাত'; } else if (hour < 10) { return 'সকাল'; } else if (hour < 17) { return 'দুপুর'; } else if (hour < 20) { return 'বিকাল'; } else { return 'রাত'; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration var symbolMap$4 = { '1': '༡', '2': '༢', '3': '༣', '4': '༤', '5': '༥', '6': '༦', '7': '༧', '8': '༨', '9': '༩', '0': '༠' }, numberMap$3 = { '༡': '1', '༢': '2', '༣': '3', '༤': '4', '༥': '5', '༦': '6', '༧': '7', '༨': '8', '༩': '9', '༠': '0' }; moment.defineLocale('bo', { months : 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split('_'), monthsShort : 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split('_'), weekdays : 'གཟའ་ཉི་མ་_གཟའ་ཟླ་བ་_གཟའ་མིག་དམར་_གཟའ་ལྷག་པ་_གཟའ་ཕུར་བུ_གཟའ་པ་སངས་_གཟའ་སྤེན་པ་'.split('_'), weekdaysShort : 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split('_'), weekdaysMin : 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split('_'), longDateFormat : { LT : 'A h:mm', LTS : 'A h:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY, A h:mm', LLLL : 'dddd, D MMMM YYYY, A h:mm' }, calendar : { sameDay : '[དི་རིང] LT', nextDay : '[སང་ཉིན] LT', nextWeek : '[བདུན་ཕྲག་རྗེས་མ], LT', lastDay : '[ཁ་སང] LT', lastWeek : '[བདུན་ཕྲག་མཐའ་མ] dddd, LT', sameElse : 'L' }, relativeTime : { future : '%s ལ་', past : '%s སྔན་ལ', s : 'ལམ་སང', ss : '%d སྐར་ཆ།', m : 'སྐར་མ་གཅིག', mm : '%d སྐར་མ', h : 'ཆུ་ཚོད་གཅིག', hh : '%d ཆུ་ཚོད', d : 'ཉིན་གཅིག', dd : '%d ཉིན་', M : 'ཟླ་བ་གཅིག', MM : '%d ཟླ་བ', y : 'ལོ་གཅིག', yy : '%d ལོ' }, preparse: function (string) { return string.replace(/[༡༢༣༤༥༦༧༨༩༠]/g, function (match) { return numberMap$3[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap$4[match]; }); }, meridiemParse: /མཚན་མོ|ཞོགས་ཀས|ཉིན་གུང|དགོང་དག|མཚན་མོ/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if ((meridiem === 'མཚན་མོ' && hour >= 4) || (meridiem === 'ཉིན་གུང' && hour < 5) || meridiem === 'དགོང་དག') { return hour + 12; } else { return hour; } }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return 'མཚན་མོ'; } else if (hour < 10) { return 'ཞོགས་ཀས'; } else if (hour < 17) { return 'ཉིན་གུང'; } else if (hour < 20) { return 'དགོང་དག'; } else { return 'མཚན་མོ'; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration function relativeTimeWithMutation(number, withoutSuffix, key) { var format = { 'mm': 'munutenn', 'MM': 'miz', 'dd': 'devezh' }; return number + ' ' + mutation(format[key], number); } function specialMutationForYears(number) { switch (lastNumber(number)) { case 1: case 3: case 4: case 5: case 9: return number + ' bloaz'; default: return number + ' vloaz'; } } function lastNumber(number) { if (number > 9) { return lastNumber(number % 10); } return number; } function mutation(text, number) { if (number === 2) { return softMutation(text); } return text; } function softMutation(text) { var mutationTable = { 'm': 'v', 'b': 'v', 'd': 'z' }; if (mutationTable[text.charAt(0)] === undefined) { return text; } return mutationTable[text.charAt(0)] + text.substring(1); } moment.defineLocale('br', { months : 'Genver_C\'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu'.split('_'), monthsShort : 'Gen_C\'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker'.split('_'), weekdays : 'Sul_Lun_Meurzh_Merc\'her_Yaou_Gwener_Sadorn'.split('_'), weekdaysShort : 'Sul_Lun_Meu_Mer_Yao_Gwe_Sad'.split('_'), weekdaysMin : 'Su_Lu_Me_Mer_Ya_Gw_Sa'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'h[e]mm A', LTS : 'h[e]mm:ss A', L : 'DD/MM/YYYY', LL : 'D [a viz] MMMM YYYY', LLL : 'D [a viz] MMMM YYYY h[e]mm A', LLLL : 'dddd, D [a viz] MMMM YYYY h[e]mm A' }, calendar : { sameDay : '[Hiziv da] LT', nextDay : '[Warc\'hoazh da] LT', nextWeek : 'dddd [da] LT', lastDay : '[Dec\'h da] LT', lastWeek : 'dddd [paset da] LT', sameElse : 'L' }, relativeTime : { future : 'a-benn %s', past : '%s \'zo', s : 'un nebeud segondennoù', ss : '%d eilenn', m : 'ur vunutenn', mm : relativeTimeWithMutation, h : 'un eur', hh : '%d eur', d : 'un devezh', dd : relativeTimeWithMutation, M : 'ur miz', MM : relativeTimeWithMutation, y : 'ur bloaz', yy : specialMutationForYears }, dayOfMonthOrdinalParse: /\d{1,2}(añ|vet)/, ordinal : function (number) { var output = (number === 1) ? 'añ' : 'vet'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration function translate(number, withoutSuffix, key) { var result = number + ' '; switch (key) { case 'ss': if (number === 1) { result += 'sekunda'; } else if (number === 2 || number === 3 || number === 4) { result += 'sekunde'; } else { result += 'sekundi'; } return result; case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mjesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'mjeseca'; } else { result += 'mjeseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } moment.defineLocale('bs', { months : 'januar_februar_mart_april_maj_juni_juli_august_septembar_oktobar_novembar_decembar'.split('_'), monthsShort : 'jan._feb._mar._apr._maj._jun._jul._aug._sep._okt._nov._dec.'.split('_'), monthsParseExact: true, weekdays : 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'), weekdaysShort : 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), weekdaysMin : 'ne_po_ut_sr_če_pe_su'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'DD.MM.YYYY', LL : 'D. MMMM YYYY', LLL : 'D. MMMM YYYY H:mm', LLLL : 'dddd, D. MMMM YYYY H:mm' }, calendar : { sameDay : '[danas u] LT', nextDay : '[sutra u] LT', nextWeek : function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; case 3: return '[u] [srijedu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[jučer u] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: return '[prošlu] dddd [u] LT'; case 6: return '[prošle] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[prošli] dddd [u] LT'; } }, sameElse : 'L' }, relativeTime : { future : 'za %s', past : 'prije %s', s : 'par sekundi', ss : translate, m : translate, mm : translate, h : translate, hh : translate, d : 'dan', dd : translate, M : 'mjesec', MM : translate, y : 'godinu', yy : translate }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('ca', { months : { standalone: 'gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre'.split('_'), format: 'de gener_de febrer_de març_d\'abril_de maig_de juny_de juliol_d\'agost_de setembre_d\'octubre_de novembre_de desembre'.split('_'), isFormat: /D[oD]?(\s)+MMMM/ }, monthsShort : 'gen._febr._març_abr._maig_juny_jul._ag._set._oct._nov._des.'.split('_'), monthsParseExact : true, weekdays : 'diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte'.split('_'), weekdaysShort : 'dg._dl._dt._dc._dj._dv._ds.'.split('_'), weekdaysMin : 'dg_dl_dt_dc_dj_dv_ds'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM [de] YYYY', ll : 'D MMM YYYY', LLL : 'D MMMM [de] YYYY [a les] H:mm', lll : 'D MMM YYYY, H:mm', LLLL : 'dddd D MMMM [de] YYYY [a les] H:mm', llll : 'ddd D MMM YYYY, H:mm' }, calendar : { sameDay : function () { return '[avui a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, nextDay : function () { return '[demà a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, nextWeek : function () { return 'dddd [a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, lastDay : function () { return '[ahir a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, lastWeek : function () { return '[el] dddd [passat a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : 'd\'aquí %s', past : 'fa %s', s : 'uns segons', ss : '%d segons', m : 'un minut', mm : '%d minuts', h : 'una hora', hh : '%d hores', d : 'un dia', dd : '%d dies', M : 'un mes', MM : '%d mesos', y : 'un any', yy : '%d anys' }, dayOfMonthOrdinalParse: /\d{1,2}(r|n|t|è|a)/, ordinal : function (number, period) { var output = (number === 1) ? 'r' : (number === 2) ? 'n' : (number === 3) ? 'r' : (number === 4) ? 't' : 'è'; if (period === 'w' || period === 'W') { output = 'a'; } return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var months$2 = 'leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec'.split('_'), monthsShort = 'led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro'.split('_'); function plural$1(n) { return (n > 1) && (n < 5) && (~~(n / 10) !== 1); } function translate$1(number, withoutSuffix, key, isFuture) { var result = number + ' '; switch (key) { case 's': // a few seconds / in a few seconds / a few seconds ago return (withoutSuffix || isFuture) ? 'pár sekund' : 'pár sekundami'; case 'ss': // 9 seconds / in 9 seconds / 9 seconds ago if (withoutSuffix || isFuture) { return result + (plural$1(number) ? 'sekundy' : 'sekund'); } else { return result + 'sekundami'; } break; case 'm': // a minute / in a minute / a minute ago return withoutSuffix ? 'minuta' : (isFuture ? 'minutu' : 'minutou'); case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago if (withoutSuffix || isFuture) { return result + (plural$1(number) ? 'minuty' : 'minut'); } else { return result + 'minutami'; } break; case 'h': // an hour / in an hour / an hour ago return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); case 'hh': // 9 hours / in 9 hours / 9 hours ago if (withoutSuffix || isFuture) { return result + (plural$1(number) ? 'hodiny' : 'hodin'); } else { return result + 'hodinami'; } break; case 'd': // a day / in a day / a day ago return (withoutSuffix || isFuture) ? 'den' : 'dnem'; case 'dd': // 9 days / in 9 days / 9 days ago if (withoutSuffix || isFuture) { return result + (plural$1(number) ? 'dny' : 'dní'); } else { return result + 'dny'; } break; case 'M': // a month / in a month / a month ago return (withoutSuffix || isFuture) ? 'měsíc' : 'měsícem'; case 'MM': // 9 months / in 9 months / 9 months ago if (withoutSuffix || isFuture) { return result + (plural$1(number) ? 'měsíce' : 'měsíců'); } else { return result + 'měsíci'; } break; case 'y': // a year / in a year / a year ago return (withoutSuffix || isFuture) ? 'rok' : 'rokem'; case 'yy': // 9 years / in 9 years / 9 years ago if (withoutSuffix || isFuture) { return result + (plural$1(number) ? 'roky' : 'let'); } else { return result + 'lety'; } break; } } moment.defineLocale('cs', { months : months$2, monthsShort : monthsShort, monthsParse : (function (months, monthsShort) { var i, _monthsParse = []; for (i = 0; i < 12; i++) { // use custom parser to solve problem with July (červenec) _monthsParse[i] = new RegExp('^' + months[i] + '$|^' + monthsShort[i] + '$', 'i'); } return _monthsParse; }(months$2, monthsShort)), shortMonthsParse : (function (monthsShort) { var i, _shortMonthsParse = []; for (i = 0; i < 12; i++) { _shortMonthsParse[i] = new RegExp('^' + monthsShort[i] + '$', 'i'); } return _shortMonthsParse; }(monthsShort)), longMonthsParse : (function (months) { var i, _longMonthsParse = []; for (i = 0; i < 12; i++) { _longMonthsParse[i] = new RegExp('^' + months[i] + '$', 'i'); } return _longMonthsParse; }(months$2)), weekdays : 'neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota'.split('_'), weekdaysShort : 'ne_po_út_st_čt_pá_so'.split('_'), weekdaysMin : 'ne_po_út_st_čt_pá_so'.split('_'), longDateFormat : { LT: 'H:mm', LTS : 'H:mm:ss', L : 'DD.MM.YYYY', LL : 'D. MMMM YYYY', LLL : 'D. MMMM YYYY H:mm', LLLL : 'dddd D. MMMM YYYY H:mm', l : 'D. M. YYYY' }, calendar : { sameDay: '[dnes v] LT', nextDay: '[zítra v] LT', nextWeek: function () { switch (this.day()) { case 0: return '[v neděli v] LT'; case 1: case 2: return '[v] dddd [v] LT'; case 3: return '[ve středu v] LT'; case 4: return '[ve čtvrtek v] LT'; case 5: return '[v pátek v] LT'; case 6: return '[v sobotu v] LT'; } }, lastDay: '[včera v] LT', lastWeek: function () { switch (this.day()) { case 0: return '[minulou neděli v] LT'; case 1: case 2: return '[minulé] dddd [v] LT'; case 3: return '[minulou středu v] LT'; case 4: case 5: return '[minulý] dddd [v] LT'; case 6: return '[minulou sobotu v] LT'; } }, sameElse: 'L' }, relativeTime : { future : 'za %s', past : 'před %s', s : translate$1, ss : translate$1, m : translate$1, mm : translate$1, h : translate$1, hh : translate$1, d : translate$1, dd : translate$1, M : translate$1, MM : translate$1, y : translate$1, yy : translate$1 }, dayOfMonthOrdinalParse : /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('cv', { months : 'кӑрлач_нарӑс_пуш_ака_май_ҫӗртме_утӑ_ҫурла_авӑн_юпа_чӳк_раштав'.split('_'), monthsShort : 'кӑр_нар_пуш_ака_май_ҫӗр_утӑ_ҫур_авн_юпа_чӳк_раш'.split('_'), weekdays : 'вырсарникун_тунтикун_ытларикун_юнкун_кӗҫнерникун_эрнекун_шӑматкун'.split('_'), weekdaysShort : 'выр_тун_ытл_юн_кӗҫ_эрн_шӑм'.split('_'), weekdaysMin : 'вр_тн_ыт_юн_кҫ_эр_шм'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD-MM-YYYY', LL : 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ]', LLL : 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm', LLLL : 'dddd, YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm' }, calendar : { sameDay: '[Паян] LT [сехетре]', nextDay: '[Ыран] LT [сехетре]', lastDay: '[Ӗнер] LT [сехетре]', nextWeek: '[Ҫитес] dddd LT [сехетре]', lastWeek: '[Иртнӗ] dddd LT [сехетре]', sameElse: 'L' }, relativeTime : { future : function (output) { var affix = /сехет$/i.exec(output) ? 'рен' : /ҫул$/i.exec(output) ? 'тан' : 'ран'; return output + affix; }, past : '%s каялла', s : 'пӗр-ик ҫеккунт', ss : '%d ҫеккунт', m : 'пӗр минут', mm : '%d минут', h : 'пӗр сехет', hh : '%d сехет', d : 'пӗр кун', dd : '%d кун', M : 'пӗр уйӑх', MM : '%d уйӑх', y : 'пӗр ҫул', yy : '%d ҫул' }, dayOfMonthOrdinalParse: /\d{1,2}-мӗш/, ordinal : '%d-мӗш', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('cy', { months: 'Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr'.split('_'), monthsShort: 'Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag'.split('_'), weekdays: 'Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn'.split('_'), weekdaysShort: 'Sul_Llun_Maw_Mer_Iau_Gwe_Sad'.split('_'), weekdaysMin: 'Su_Ll_Ma_Me_Ia_Gw_Sa'.split('_'), weekdaysParseExact : true, // time formats are the same as en-gb longDateFormat: { LT: 'HH:mm', LTS : 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, calendar: { sameDay: '[Heddiw am] LT', nextDay: '[Yfory am] LT', nextWeek: 'dddd [am] LT', lastDay: '[Ddoe am] LT', lastWeek: 'dddd [diwethaf am] LT', sameElse: 'L' }, relativeTime: { future: 'mewn %s', past: '%s yn ôl', s: 'ychydig eiliadau', ss: '%d eiliad', m: 'munud', mm: '%d munud', h: 'awr', hh: '%d awr', d: 'diwrnod', dd: '%d diwrnod', M: 'mis', MM: '%d mis', y: 'blwyddyn', yy: '%d flynedd' }, dayOfMonthOrdinalParse: /\d{1,2}(fed|ain|af|il|ydd|ed|eg)/, // traditional ordinal numbers above 31 are not commonly used in colloquial Welsh ordinal: function (number) { var b = number, output = '', lookup = [ '', 'af', 'il', 'ydd', 'ydd', 'ed', 'ed', 'ed', 'fed', 'fed', 'fed', // 1af to 10fed 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'fed' // 11eg to 20fed ]; if (b > 20) { if (b === 40 || b === 50 || b === 60 || b === 80 || b === 100) { output = 'fed'; // not 30ain, 70ain or 90ain } else { output = 'ain'; } } else if (b > 0) { output = lookup[b]; } return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('da', { months : 'januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december'.split('_'), monthsShort : 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'), weekdays : 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'), weekdaysShort : 'søn_man_tir_ons_tor_fre_lør'.split('_'), weekdaysMin : 'sø_ma_ti_on_to_fr_lø'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D. MMMM YYYY', LLL : 'D. MMMM YYYY HH:mm', LLLL : 'dddd [d.] D. MMMM YYYY [kl.] HH:mm' }, calendar : { sameDay : '[i dag kl.] LT', nextDay : '[i morgen kl.] LT', nextWeek : 'på dddd [kl.] LT', lastDay : '[i går kl.] LT', lastWeek : '[i] dddd[s kl.] LT', sameElse : 'L' }, relativeTime : { future : 'om %s', past : '%s siden', s : 'få sekunder', ss : '%d sekunder', m : 'et minut', mm : '%d minutter', h : 'en time', hh : '%d timer', d : 'en dag', dd : '%d dage', M : 'en måned', MM : '%d måneder', y : 'et år', yy : '%d år' }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eine Minute', 'einer Minute'], 'h': ['eine Stunde', 'einer Stunde'], 'd': ['ein Tag', 'einem Tag'], 'dd': [number + ' Tage', number + ' Tagen'], 'M': ['ein Monat', 'einem Monat'], 'MM': [number + ' Monate', number + ' Monaten'], 'y': ['ein Jahr', 'einem Jahr'], 'yy': [number + ' Jahre', number + ' Jahren'] }; return withoutSuffix ? format[key][0] : format[key][1]; } moment.defineLocale('de-at', { months : 'Jänner_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), monthsShort : 'Jän._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'), monthsParseExact : true, weekdays : 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), weekdaysShort : 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'), weekdaysMin : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), weekdaysParseExact : true, longDateFormat : { LT: 'HH:mm', LTS: 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D. MMMM YYYY', LLL : 'D. MMMM YYYY HH:mm', LLLL : 'dddd, D. MMMM YYYY HH:mm' }, calendar : { sameDay: '[heute um] LT [Uhr]', sameElse: 'L', nextDay: '[morgen um] LT [Uhr]', nextWeek: 'dddd [um] LT [Uhr]', lastDay: '[gestern um] LT [Uhr]', lastWeek: '[letzten] dddd [um] LT [Uhr]' }, relativeTime : { future : 'in %s', past : 'vor %s', s : 'ein paar Sekunden', ss : '%d Sekunden', m : processRelativeTime, mm : '%d Minuten', h : processRelativeTime, hh : '%d Stunden', d : processRelativeTime, dd : processRelativeTime, M : processRelativeTime, MM : processRelativeTime, y : processRelativeTime, yy : processRelativeTime }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration function processRelativeTime$1(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eine Minute', 'einer Minute'], 'h': ['eine Stunde', 'einer Stunde'], 'd': ['ein Tag', 'einem Tag'], 'dd': [number + ' Tage', number + ' Tagen'], 'M': ['ein Monat', 'einem Monat'], 'MM': [number + ' Monate', number + ' Monaten'], 'y': ['ein Jahr', 'einem Jahr'], 'yy': [number + ' Jahre', number + ' Jahren'] }; return withoutSuffix ? format[key][0] : format[key][1]; } moment.defineLocale('de-ch', { months : 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), monthsShort : 'Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'), monthsParseExact : true, weekdays : 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), weekdaysShort : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), weekdaysMin : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), weekdaysParseExact : true, longDateFormat : { LT: 'HH:mm', LTS: 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D. MMMM YYYY', LLL : 'D. MMMM YYYY HH:mm', LLLL : 'dddd, D. MMMM YYYY HH:mm' }, calendar : { sameDay: '[heute um] LT [Uhr]', sameElse: 'L', nextDay: '[morgen um] LT [Uhr]', nextWeek: 'dddd [um] LT [Uhr]', lastDay: '[gestern um] LT [Uhr]', lastWeek: '[letzten] dddd [um] LT [Uhr]' }, relativeTime : { future : 'in %s', past : 'vor %s', s : 'ein paar Sekunden', ss : '%d Sekunden', m : processRelativeTime$1, mm : '%d Minuten', h : processRelativeTime$1, hh : '%d Stunden', d : processRelativeTime$1, dd : processRelativeTime$1, M : processRelativeTime$1, MM : processRelativeTime$1, y : processRelativeTime$1, yy : processRelativeTime$1 }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration function processRelativeTime$2(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eine Minute', 'einer Minute'], 'h': ['eine Stunde', 'einer Stunde'], 'd': ['ein Tag', 'einem Tag'], 'dd': [number + ' Tage', number + ' Tagen'], 'M': ['ein Monat', 'einem Monat'], 'MM': [number + ' Monate', number + ' Monaten'], 'y': ['ein Jahr', 'einem Jahr'], 'yy': [number + ' Jahre', number + ' Jahren'] }; return withoutSuffix ? format[key][0] : format[key][1]; } moment.defineLocale('de', { months : 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), monthsShort : 'Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'), monthsParseExact : true, weekdays : 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'), weekdaysShort : 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'), weekdaysMin : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'), weekdaysParseExact : true, longDateFormat : { LT: 'HH:mm', LTS: 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D. MMMM YYYY', LLL : 'D. MMMM YYYY HH:mm', LLLL : 'dddd, D. MMMM YYYY HH:mm' }, calendar : { sameDay: '[heute um] LT [Uhr]', sameElse: 'L', nextDay: '[morgen um] LT [Uhr]', nextWeek: 'dddd [um] LT [Uhr]', lastDay: '[gestern um] LT [Uhr]', lastWeek: '[letzten] dddd [um] LT [Uhr]' }, relativeTime : { future : 'in %s', past : 'vor %s', s : 'ein paar Sekunden', ss : '%d Sekunden', m : processRelativeTime$2, mm : '%d Minuten', h : processRelativeTime$2, hh : '%d Stunden', d : processRelativeTime$2, dd : processRelativeTime$2, M : processRelativeTime$2, MM : processRelativeTime$2, y : processRelativeTime$2, yy : processRelativeTime$2 }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var months$3 = [ 'ޖެނުއަރީ', 'ފެބްރުއަރީ', 'މާރިޗު', 'އޭޕްރީލު', 'މޭ', 'ޖޫން', 'ޖުލައި', 'އޯގަސްޓު', 'ސެޕްޓެމްބަރު', 'އޮކްޓޯބަރު', 'ނޮވެމްބަރު', 'ޑިސެމްބަރު' ], weekdays = [ 'އާދިއްތަ', 'ހޯމަ', 'އަންގާރަ', 'ބުދަ', 'ބުރާސްފަތި', 'ހުކުރު', 'ހޮނިހިރު' ]; moment.defineLocale('dv', { months : months$3, monthsShort : months$3, weekdays : weekdays, weekdaysShort : weekdays, weekdaysMin : 'އާދި_ހޯމަ_އަން_ބުދަ_ބުރާ_ހުކު_ހޮނި'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'D/M/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, meridiemParse: /މކ|މފ/, isPM : function (input) { return 'މފ' === input; }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return 'މކ'; } else { return 'މފ'; } }, calendar : { sameDay : '[މިއަދު] LT', nextDay : '[މާދަމާ] LT', nextWeek : 'dddd LT', lastDay : '[އިއްޔެ] LT', lastWeek : '[ފާއިތުވި] dddd LT', sameElse : 'L' }, relativeTime : { future : 'ތެރޭގައި %s', past : 'ކުރިން %s', s : 'ސިކުންތުކޮޅެއް', ss : 'd% ސިކުންތު', m : 'މިނިޓެއް', mm : 'މިނިޓު %d', h : 'ގަޑިއިރެއް', hh : 'ގަޑިއިރު %d', d : 'ދުވަހެއް', dd : 'ދުވަސް %d', M : 'މަހެއް', MM : 'މަސް %d', y : 'އަހަރެއް', yy : 'އަހަރު %d' }, preparse: function (string) { return string.replace(/،/g, ','); }, postformat: function (string) { return string.replace(/,/g, '،'); }, week : { dow : 7, // Sunday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); function isFunction(input) { return input instanceof Function || Object.prototype.toString.call(input) === '[object Function]'; } //! moment.js locale configuration moment.defineLocale('el', { monthsNominativeEl : 'Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος'.split('_'), monthsGenitiveEl : 'Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου'.split('_'), months : function (momentToFormat, format) { if (!momentToFormat) { return this._monthsNominativeEl; } else if (typeof format === 'string' && /D/.test(format.substring(0, format.indexOf('MMMM')))) { // if there is a day number before 'MMMM' return this._monthsGenitiveEl[momentToFormat.month()]; } else { return this._monthsNominativeEl[momentToFormat.month()]; } }, monthsShort : 'Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ'.split('_'), weekdays : 'Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο'.split('_'), weekdaysShort : 'Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ'.split('_'), weekdaysMin : 'Κυ_Δε_Τρ_Τε_Πε_Πα_Σα'.split('_'), meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'μμ' : 'ΜΜ'; } else { return isLower ? 'πμ' : 'ΠΜ'; } }, isPM : function (input) { return ((input + '').toLowerCase()[0] === 'μ'); }, meridiemParse : /[ΠΜ]\.?Μ?\.?/i, longDateFormat : { LT : 'h:mm A', LTS : 'h:mm:ss A', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY h:mm A', LLLL : 'dddd, D MMMM YYYY h:mm A' }, calendarEl : { sameDay : '[Σήμερα {}] LT', nextDay : '[Αύριο {}] LT', nextWeek : 'dddd [{}] LT', lastDay : '[Χθες {}] LT', lastWeek : function () { switch (this.day()) { case 6: return '[το προηγούμενο] dddd [{}] LT'; default: return '[την προηγούμενη] dddd [{}] LT'; } }, sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendarEl[key], hours = mom && mom.hours(); if (isFunction(output)) { output = output.apply(mom); } return output.replace('{}', (hours % 12 === 1 ? 'στη' : 'στις')); }, relativeTime : { future : 'σε %s', past : '%s πριν', s : 'λίγα δευτερόλεπτα', ss : '%d δευτερόλεπτα', m : 'ένα λεπτό', mm : '%d λεπτά', h : 'μία ώρα', hh : '%d ώρες', d : 'μία μέρα', dd : '%d μέρες', M : 'ένας μήνας', MM : '%d μήνες', y : 'ένας χρόνος', yy : '%d χρόνια' }, dayOfMonthOrdinalParse: /\d{1,2}η/, ordinal: '%dη', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('en-au', { months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), longDateFormat : { LT : 'h:mm A', LTS : 'h:mm:ss A', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY h:mm A', LLLL : 'dddd, D MMMM YYYY h:mm A' }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : 'in %s', past : '%s ago', s : 'a few seconds', ss : '%d seconds', m : 'a minute', mm : '%d minutes', h : 'an hour', hh : '%d hours', d : 'a day', dd : '%d days', M : 'a month', MM : '%d months', y : 'a year', yy : '%d years' }, dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, ordinal : function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('en-ca', { months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), longDateFormat : { LT : 'h:mm A', LTS : 'h:mm:ss A', L : 'YYYY-MM-DD', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY h:mm A', LLLL : 'dddd, MMMM D, YYYY h:mm A' }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : 'in %s', past : '%s ago', s : 'a few seconds', ss : '%d seconds', m : 'a minute', mm : '%d minutes', h : 'an hour', hh : '%d hours', d : 'a day', dd : '%d days', M : 'a month', MM : '%d months', y : 'a year', yy : '%d years' }, dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, ordinal : function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); //! moment.js locale configuration moment.defineLocale('en-gb', { months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : 'in %s', past : '%s ago', s : 'a few seconds', ss : '%d seconds', m : 'a minute', mm : '%d minutes', h : 'an hour', hh : '%d hours', d : 'a day', dd : '%d days', M : 'a month', MM : '%d months', y : 'a year', yy : '%d years' }, dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, ordinal : function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('en-ie', { months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD-MM-YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : 'in %s', past : '%s ago', s : 'a few seconds', ss : '%d seconds', m : 'a minute', mm : '%d minutes', h : 'an hour', hh : '%d hours', d : 'a day', dd : '%d days', M : 'a month', MM : '%d months', y : 'a year', yy : '%d years' }, dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, ordinal : function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('en-il', { months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : 'in %s', past : '%s ago', s : 'a few seconds', m : 'a minute', mm : '%d minutes', h : 'an hour', hh : '%d hours', d : 'a day', dd : '%d days', M : 'a month', MM : '%d months', y : 'a year', yy : '%d years' }, dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, ordinal : function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); //! moment.js locale configuration moment.defineLocale('en-nz', { months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), longDateFormat : { LT : 'h:mm A', LTS : 'h:mm:ss A', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY h:mm A', LLLL : 'dddd, D MMMM YYYY h:mm A' }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : 'in %s', past : '%s ago', s : 'a few seconds', ss : '%d seconds', m : 'a minute', mm : '%d minutes', h : 'an hour', hh : '%d hours', d : 'a day', dd : '%d days', M : 'a month', MM : '%d months', y : 'a year', yy : '%d years' }, dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, ordinal : function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('eo', { months : 'januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro'.split('_'), monthsShort : 'jan_feb_mar_apr_maj_jun_jul_aŭg_sep_okt_nov_dec'.split('_'), weekdays : 'dimanĉo_lundo_mardo_merkredo_ĵaŭdo_vendredo_sabato'.split('_'), weekdaysShort : 'dim_lun_mard_merk_ĵaŭ_ven_sab'.split('_'), weekdaysMin : 'di_lu_ma_me_ĵa_ve_sa'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'YYYY-MM-DD', LL : 'D[-a de] MMMM, YYYY', LLL : 'D[-a de] MMMM, YYYY HH:mm', LLLL : 'dddd, [la] D[-a de] MMMM, YYYY HH:mm' }, meridiemParse: /[ap]\.t\.m/i, isPM: function (input) { return input.charAt(0).toLowerCase() === 'p'; }, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'p.t.m.' : 'P.T.M.'; } else { return isLower ? 'a.t.m.' : 'A.T.M.'; } }, calendar : { sameDay : '[Hodiaŭ je] LT', nextDay : '[Morgaŭ je] LT', nextWeek : 'dddd [je] LT', lastDay : '[Hieraŭ je] LT', lastWeek : '[pasinta] dddd [je] LT', sameElse : 'L' }, relativeTime : { future : 'post %s', past : 'antaŭ %s', s : 'sekundoj', ss : '%d sekundoj', m : 'minuto', mm : '%d minutoj', h : 'horo', hh : '%d horoj', d : 'tago',//ne 'diurno', ĉar estas uzita por proksimumo dd : '%d tagoj', M : 'monato', MM : '%d monatoj', y : 'jaro', yy : '%d jaroj' }, dayOfMonthOrdinalParse: /\d{1,2}a/, ordinal : '%da', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'), monthsShort$1 = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); var monthsParse = [/^ene/i, /^feb/i, /^mar/i, /^abr/i, /^may/i, /^jun/i, /^jul/i, /^ago/i, /^sep/i, /^oct/i, /^nov/i, /^dic/i]; var monthsRegex = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i; moment.defineLocale('es-do', { months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), monthsShort : function (m, format) { if (!m) { return monthsShortDot; } else if (/-MMM-/.test(format)) { return monthsShort$1[m.month()]; } else { return monthsShortDot[m.month()]; } }, monthsRegex: monthsRegex, monthsShortRegex: monthsRegex, monthsStrictRegex: /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i, monthsShortStrictRegex: /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i, monthsParse: monthsParse, longMonthsParse: monthsParse, shortMonthsParse: monthsParse, weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'h:mm A', LTS : 'h:mm:ss A', L : 'DD/MM/YYYY', LL : 'D [de] MMMM [de] YYYY', LLL : 'D [de] MMMM [de] YYYY h:mm A', LLLL : 'dddd, D [de] MMMM [de] YYYY h:mm A' }, calendar : { sameDay : function () { return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextDay : function () { return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextWeek : function () { return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastDay : function () { return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastWeek : function () { return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : 'en %s', past : 'hace %s', s : 'unos segundos', ss : '%d segundos', m : 'un minuto', mm : '%d minutos', h : 'una hora', hh : '%d horas', d : 'un día', dd : '%d días', M : 'un mes', MM : '%d meses', y : 'un año', yy : '%d años' }, dayOfMonthOrdinalParse : /\d{1,2}º/, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var monthsShortDot$1 = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'), monthsShort$2 = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); moment.defineLocale('es-us', { months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), monthsShort : function (m, format) { if (!m) { return monthsShortDot$1; } else if (/-MMM-/.test(format)) { return monthsShort$2[m.month()]; } else { return monthsShortDot$1[m.month()]; } }, monthsParseExact : true, weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'h:mm A', LTS : 'h:mm:ss A', L : 'MM/DD/YYYY', LL : 'MMMM [de] D [de] YYYY', LLL : 'MMMM [de] D [de] YYYY h:mm A', LLLL : 'dddd, MMMM [de] D [de] YYYY h:mm A' }, calendar : { sameDay : function () { return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextDay : function () { return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextWeek : function () { return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastDay : function () { return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastWeek : function () { return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : 'en %s', past : 'hace %s', s : 'unos segundos', ss : '%d segundos', m : 'un minuto', mm : '%d minutos', h : 'una hora', hh : '%d horas', d : 'un día', dd : '%d días', M : 'un mes', MM : '%d meses', y : 'un año', yy : '%d años' }, dayOfMonthOrdinalParse : /\d{1,2}º/, ordinal : '%dº', week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration var monthsShortDot$2 = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'), monthsShort$3 = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); var monthsParse$1 = [/^ene/i, /^feb/i, /^mar/i, /^abr/i, /^may/i, /^jun/i, /^jul/i, /^ago/i, /^sep/i, /^oct/i, /^nov/i, /^dic/i]; var monthsRegex$1 = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i; moment.defineLocale('es', { months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), monthsShort : function (m, format) { if (!m) { return monthsShortDot$2; } else if (/-MMM-/.test(format)) { return monthsShort$3[m.month()]; } else { return monthsShortDot$2[m.month()]; } }, monthsRegex : monthsRegex$1, monthsShortRegex : monthsRegex$1, monthsStrictRegex : /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i, monthsShortStrictRegex : /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i, monthsParse : monthsParse$1, longMonthsParse : monthsParse$1, shortMonthsParse : monthsParse$1, weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'DD/MM/YYYY', LL : 'D [de] MMMM [de] YYYY', LLL : 'D [de] MMMM [de] YYYY H:mm', LLLL : 'dddd, D [de] MMMM [de] YYYY H:mm' }, calendar : { sameDay : function () { return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextDay : function () { return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextWeek : function () { return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastDay : function () { return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastWeek : function () { return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : 'en %s', past : 'hace %s', s : 'unos segundos', ss : '%d segundos', m : 'un minuto', mm : '%d minutos', h : 'una hora', hh : '%d horas', d : 'un día', dd : '%d días', M : 'un mes', MM : '%d meses', y : 'un año', yy : '%d años' }, dayOfMonthOrdinalParse : /\d{1,2}º/, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration function processRelativeTime$3(number, withoutSuffix, key, isFuture) { var format = { 's' : ['mõne sekundi', 'mõni sekund', 'paar sekundit'], 'ss': [number + 'sekundi', number + 'sekundit'], 'm' : ['ühe minuti', 'üks minut'], 'mm': [number + ' minuti', number + ' minutit'], 'h' : ['ühe tunni', 'tund aega', 'üks tund'], 'hh': [number + ' tunni', number + ' tundi'], 'd' : ['ühe päeva', 'üks päev'], 'M' : ['kuu aja', 'kuu aega', 'üks kuu'], 'MM': [number + ' kuu', number + ' kuud'], 'y' : ['ühe aasta', 'aasta', 'üks aasta'], 'yy': [number + ' aasta', number + ' aastat'] }; if (withoutSuffix) { return format[key][2] ? format[key][2] : format[key][1]; } return isFuture ? format[key][0] : format[key][1]; } moment.defineLocale('et', { months : 'jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember'.split('_'), monthsShort : 'jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets'.split('_'), weekdays : 'pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev'.split('_'), weekdaysShort : 'P_E_T_K_N_R_L'.split('_'), weekdaysMin : 'P_E_T_K_N_R_L'.split('_'), longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'DD.MM.YYYY', LL : 'D. MMMM YYYY', LLL : 'D. MMMM YYYY H:mm', LLLL : 'dddd, D. MMMM YYYY H:mm' }, calendar : { sameDay : '[Täna,] LT', nextDay : '[Homme,] LT', nextWeek : '[Järgmine] dddd LT', lastDay : '[Eile,] LT', lastWeek : '[Eelmine] dddd LT', sameElse : 'L' }, relativeTime : { future : '%s pärast', past : '%s tagasi', s : processRelativeTime$3, ss : processRelativeTime$3, m : processRelativeTime$3, mm : processRelativeTime$3, h : processRelativeTime$3, hh : processRelativeTime$3, d : processRelativeTime$3, dd : '%d päeva', M : processRelativeTime$3, MM : processRelativeTime$3, y : processRelativeTime$3, yy : processRelativeTime$3 }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('eu', { months : 'urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua'.split('_'), monthsShort : 'urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.'.split('_'), monthsParseExact : true, weekdays : 'igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata'.split('_'), weekdaysShort : 'ig._al._ar._az._og._ol._lr.'.split('_'), weekdaysMin : 'ig_al_ar_az_og_ol_lr'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'YYYY-MM-DD', LL : 'YYYY[ko] MMMM[ren] D[a]', LLL : 'YYYY[ko] MMMM[ren] D[a] HH:mm', LLLL : 'dddd, YYYY[ko] MMMM[ren] D[a] HH:mm', l : 'YYYY-M-D', ll : 'YYYY[ko] MMM D[a]', lll : 'YYYY[ko] MMM D[a] HH:mm', llll : 'ddd, YYYY[ko] MMM D[a] HH:mm' }, calendar : { sameDay : '[gaur] LT[etan]', nextDay : '[bihar] LT[etan]', nextWeek : 'dddd LT[etan]', lastDay : '[atzo] LT[etan]', lastWeek : '[aurreko] dddd LT[etan]', sameElse : 'L' }, relativeTime : { future : '%s barru', past : 'duela %s', s : 'segundo batzuk', ss : '%d segundo', m : 'minutu bat', mm : '%d minutu', h : 'ordu bat', hh : '%d ordu', d : 'egun bat', dd : '%d egun', M : 'hilabete bat', MM : '%d hilabete', y : 'urte bat', yy : '%d urte' }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration var symbolMap$5 = { '1': '۱', '2': '۲', '3': '۳', '4': '۴', '5': '۵', '6': '۶', '7': '۷', '8': '۸', '9': '۹', '0': '۰' }, numberMap$4 = { '۱': '1', '۲': '2', '۳': '3', '۴': '4', '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9', '۰': '0' }; moment.defineLocale('fa', { months : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), monthsShort : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), weekdays : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), weekdaysShort : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), weekdaysMin : 'ی_د_س_چ_پ_ج_ش'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, meridiemParse: /قبل از ظهر|بعد از ظهر/, isPM: function (input) { return /بعد از ظهر/.test(input); }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return 'قبل از ظهر'; } else { return 'بعد از ظهر'; } }, calendar : { sameDay : '[امروز ساعت] LT', nextDay : '[فردا ساعت] LT', nextWeek : 'dddd [ساعت] LT', lastDay : '[دیروز ساعت] LT', lastWeek : 'dddd [پیش] [ساعت] LT', sameElse : 'L' }, relativeTime : { future : 'در %s', past : '%s پیش', s : 'چند ثانیه', ss : 'ثانیه d%', m : 'یک دقیقه', mm : '%d دقیقه', h : 'یک ساعت', hh : '%d ساعت', d : 'یک روز', dd : '%d روز', M : 'یک ماه', MM : '%d ماه', y : 'یک سال', yy : '%d سال' }, preparse: function (string) { return string.replace(/[۰-۹]/g, function (match) { return numberMap$4[match]; }).replace(/،/g, ','); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap$5[match]; }).replace(/,/g, '،'); }, dayOfMonthOrdinalParse: /\d{1,2}م/, ordinal : '%dم', week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration var numbersPast = 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(' '), numbersFuture = [ 'nolla', 'yhden', 'kahden', 'kolmen', 'neljän', 'viiden', 'kuuden', numbersPast[7], numbersPast[8], numbersPast[9] ]; function translate$2(number, withoutSuffix, key, isFuture) { var result = ''; switch (key) { case 's': return isFuture ? 'muutaman sekunnin' : 'muutama sekunti'; case 'ss': return isFuture ? 'sekunnin' : 'sekuntia'; case 'm': return isFuture ? 'minuutin' : 'minuutti'; case 'mm': result = isFuture ? 'minuutin' : 'minuuttia'; break; case 'h': return isFuture ? 'tunnin' : 'tunti'; case 'hh': result = isFuture ? 'tunnin' : 'tuntia'; break; case 'd': return isFuture ? 'päivän' : 'päivä'; case 'dd': result = isFuture ? 'päivän' : 'päivää'; break; case 'M': return isFuture ? 'kuukauden' : 'kuukausi'; case 'MM': result = isFuture ? 'kuukauden' : 'kuukautta'; break; case 'y': return isFuture ? 'vuoden' : 'vuosi'; case 'yy': result = isFuture ? 'vuoden' : 'vuotta'; break; } result = verbalNumber(number, isFuture) + ' ' + result; return result; } function verbalNumber(number, isFuture) { return number < 10 ? (isFuture ? numbersFuture[number] : numbersPast[number]) : number; } moment.defineLocale('fi', { months : 'tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu'.split('_'), monthsShort : 'tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu'.split('_'), weekdays : 'sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai'.split('_'), weekdaysShort : 'su_ma_ti_ke_to_pe_la'.split('_'), weekdaysMin : 'su_ma_ti_ke_to_pe_la'.split('_'), longDateFormat : { LT : 'HH.mm', LTS : 'HH.mm.ss', L : 'DD.MM.YYYY', LL : 'Do MMMM[ta] YYYY', LLL : 'Do MMMM[ta] YYYY, [klo] HH.mm', LLLL : 'dddd, Do MMMM[ta] YYYY, [klo] HH.mm', l : 'D.M.YYYY', ll : 'Do MMM YYYY', lll : 'Do MMM YYYY, [klo] HH.mm', llll : 'ddd, Do MMM YYYY, [klo] HH.mm' }, calendar : { sameDay : '[tänään] [klo] LT', nextDay : '[huomenna] [klo] LT', nextWeek : 'dddd [klo] LT', lastDay : '[eilen] [klo] LT', lastWeek : '[viime] dddd[na] [klo] LT', sameElse : 'L' }, relativeTime : { future : '%s päästä', past : '%s sitten', s : translate$2, ss : translate$2, m : translate$2, mm : translate$2, h : translate$2, hh : translate$2, d : translate$2, dd : translate$2, M : translate$2, MM : translate$2, y : translate$2, yy : translate$2 }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('fo', { months : 'januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember'.split('_'), monthsShort : 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'), weekdays : 'sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur'.split('_'), weekdaysShort : 'sun_mán_týs_mik_hós_frí_ley'.split('_'), weekdaysMin : 'su_má_tý_mi_hó_fr_le'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D. MMMM, YYYY HH:mm' }, calendar : { sameDay : '[Í dag kl.] LT', nextDay : '[Í morgin kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[Í gjár kl.] LT', lastWeek : '[síðstu] dddd [kl] LT', sameElse : 'L' }, relativeTime : { future : 'um %s', past : '%s síðani', s : 'fá sekund', ss : '%d sekundir', m : 'ein minutt', mm : '%d minuttir', h : 'ein tími', hh : '%d tímar', d : 'ein dagur', dd : '%d dagar', M : 'ein mánaði', MM : '%d mánaðir', y : 'eitt ár', yy : '%d ár' }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('fr-ca', { months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'), monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), monthsParseExact : true, weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), weekdaysMin : 'di_lu_ma_me_je_ve_sa'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'YYYY-MM-DD', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { sameDay : '[Aujourd’hui à] LT', nextDay : '[Demain à] LT', nextWeek : 'dddd [à] LT', lastDay : '[Hier à] LT', lastWeek : 'dddd [dernier à] LT', sameElse : 'L' }, relativeTime : { future : 'dans %s', past : 'il y a %s', s : 'quelques secondes', ss : '%d secondes', m : 'une minute', mm : '%d minutes', h : 'une heure', hh : '%d heures', d : 'un jour', dd : '%d jours', M : 'un mois', MM : '%d mois', y : 'un an', yy : '%d ans' }, dayOfMonthOrdinalParse: /\d{1,2}(er|e)/, ordinal : function (number, period) { switch (period) { // Words with masculine grammatical gender: mois, trimestre, jour default: case 'M': case 'Q': case 'D': case 'DDD': case 'd': return number + (number === 1 ? 'er' : 'e'); // Words with feminine grammatical gender: semaine case 'w': case 'W': return number + (number === 1 ? 're' : 'e'); } } }); //! moment.js locale configuration moment.defineLocale('fr-ch', { months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'), monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), monthsParseExact : true, weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), weekdaysMin : 'di_lu_ma_me_je_ve_sa'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { sameDay : '[Aujourd’hui à] LT', nextDay : '[Demain à] LT', nextWeek : 'dddd [à] LT', lastDay : '[Hier à] LT', lastWeek : 'dddd [dernier à] LT', sameElse : 'L' }, relativeTime : { future : 'dans %s', past : 'il y a %s', s : 'quelques secondes', ss : '%d secondes', m : 'une minute', mm : '%d minutes', h : 'une heure', hh : '%d heures', d : 'un jour', dd : '%d jours', M : 'un mois', MM : '%d mois', y : 'un an', yy : '%d ans' }, dayOfMonthOrdinalParse: /\d{1,2}(er|e)/, ordinal : function (number, period) { switch (period) { // Words with masculine grammatical gender: mois, trimestre, jour default: case 'M': case 'Q': case 'D': case 'DDD': case 'd': return number + (number === 1 ? 'er' : 'e'); // Words with feminine grammatical gender: semaine case 'w': case 'W': return number + (number === 1 ? 're' : 'e'); } }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('fr', { months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'), monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), monthsParseExact : true, weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), weekdaysMin : 'di_lu_ma_me_je_ve_sa'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { sameDay : '[Aujourd’hui à] LT', nextDay : '[Demain à] LT', nextWeek : 'dddd [à] LT', lastDay : '[Hier à] LT', lastWeek : 'dddd [dernier à] LT', sameElse : 'L' }, relativeTime : { future : 'dans %s', past : 'il y a %s', s : 'quelques secondes', ss : '%d secondes', m : 'une minute', mm : '%d minutes', h : 'une heure', hh : '%d heures', d : 'un jour', dd : '%d jours', M : 'un mois', MM : '%d mois', y : 'un an', yy : '%d ans' }, dayOfMonthOrdinalParse: /\d{1,2}(er|)/, ordinal : function (number, period) { switch (period) { // TODO: Return 'e' when day of month > 1. Move this case inside // block for masculine words below. // See https://github.com/moment/moment/issues/3375 case 'D': return number + (number === 1 ? 'er' : ''); // Words with masculine grammatical gender: mois, trimestre, jour default: case 'M': case 'Q': case 'DDD': case 'd': return number + (number === 1 ? 'er' : 'e'); // Words with feminine grammatical gender: semaine case 'w': case 'W': return number + (number === 1 ? 're' : 'e'); } }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var monthsShortWithDots = 'jan._feb._mrt._apr._mai_jun._jul._aug._sep._okt._nov._des.'.split('_'), monthsShortWithoutDots = 'jan_feb_mrt_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'); moment.defineLocale('fy', { months : 'jannewaris_febrewaris_maart_april_maaie_juny_july_augustus_septimber_oktober_novimber_desimber'.split('_'), monthsShort : function (m, format) { if (!m) { return monthsShortWithDots; } else if (/-MMM-/.test(format)) { return monthsShortWithoutDots[m.month()]; } else { return monthsShortWithDots[m.month()]; } }, monthsParseExact : true, weekdays : 'snein_moandei_tiisdei_woansdei_tongersdei_freed_sneon'.split('_'), weekdaysShort : 'si._mo._ti._wo._to._fr._so.'.split('_'), weekdaysMin : 'Si_Mo_Ti_Wo_To_Fr_So'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD-MM-YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { sameDay: '[hjoed om] LT', nextDay: '[moarn om] LT', nextWeek: 'dddd [om] LT', lastDay: '[juster om] LT', lastWeek: '[ôfrûne] dddd [om] LT', sameElse: 'L' }, relativeTime : { future : 'oer %s', past : '%s lyn', s : 'in pear sekonden', ss : '%d sekonden', m : 'ien minút', mm : '%d minuten', h : 'ien oere', hh : '%d oeren', d : 'ien dei', dd : '%d dagen', M : 'ien moanne', MM : '%d moannen', y : 'ien jier', yy : '%d jierren' }, dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, ordinal : function (number) { return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var months$4 = [ 'Am Faoilleach', 'An Gearran', 'Am Màrt', 'An Giblean', 'An Cèitean', 'An t-Ògmhios', 'An t-Iuchar', 'An Lùnastal', 'An t-Sultain', 'An Dàmhair', 'An t-Samhain', 'An Dùbhlachd' ]; var monthsShort$4 = ['Faoi', 'Gear', 'Màrt', 'Gibl', 'Cèit', 'Ògmh', 'Iuch', 'Lùn', 'Sult', 'Dàmh', 'Samh', 'Dùbh']; var weekdays$1 = ['Didòmhnaich', 'Diluain', 'Dimàirt', 'Diciadain', 'Diardaoin', 'Dihaoine', 'Disathairne']; var weekdaysShort = ['Did', 'Dil', 'Dim', 'Dic', 'Dia', 'Dih', 'Dis']; var weekdaysMin = ['Dò', 'Lu', 'Mà', 'Ci', 'Ar', 'Ha', 'Sa']; moment.defineLocale('gd', { months : months$4, monthsShort : monthsShort$4, monthsParseExact : true, weekdays : weekdays$1, weekdaysShort : weekdaysShort, weekdaysMin : weekdaysMin, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay : '[An-diugh aig] LT', nextDay : '[A-màireach aig] LT', nextWeek : 'dddd [aig] LT', lastDay : '[An-dè aig] LT', lastWeek : 'dddd [seo chaidh] [aig] LT', sameElse : 'L' }, relativeTime : { future : 'ann an %s', past : 'bho chionn %s', s : 'beagan diogan', ss : '%d diogan', m : 'mionaid', mm : '%d mionaidean', h : 'uair', hh : '%d uairean', d : 'latha', dd : '%d latha', M : 'mìos', MM : '%d mìosan', y : 'bliadhna', yy : '%d bliadhna' }, dayOfMonthOrdinalParse : /\d{1,2}(d|na|mh)/, ordinal : function (number) { var output = number === 1 ? 'd' : number % 10 === 2 ? 'na' : 'mh'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('gl', { months : 'xaneiro_febreiro_marzo_abril_maio_xuño_xullo_agosto_setembro_outubro_novembro_decembro'.split('_'), monthsShort : 'xan._feb._mar._abr._mai._xuñ._xul._ago._set._out._nov._dec.'.split('_'), monthsParseExact: true, weekdays : 'domingo_luns_martes_mércores_xoves_venres_sábado'.split('_'), weekdaysShort : 'dom._lun._mar._mér._xov._ven._sáb.'.split('_'), weekdaysMin : 'do_lu_ma_mé_xo_ve_sá'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'DD/MM/YYYY', LL : 'D [de] MMMM [de] YYYY', LLL : 'D [de] MMMM [de] YYYY H:mm', LLLL : 'dddd, D [de] MMMM [de] YYYY H:mm' }, calendar : { sameDay : function () { return '[hoxe ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextDay : function () { return '[mañá ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextWeek : function () { return 'dddd [' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, lastDay : function () { return '[onte ' + ((this.hours() !== 1) ? 'á' : 'a') + '] LT'; }, lastWeek : function () { return '[o] dddd [pasado ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : function (str) { if (str.indexOf('un') === 0) { return 'n' + str; } return 'en ' + str; }, past : 'hai %s', s : 'uns segundos', ss : '%d segundos', m : 'un minuto', mm : '%d minutos', h : 'unha hora', hh : '%d horas', d : 'un día', dd : '%d días', M : 'un mes', MM : '%d meses', y : 'un ano', yy : '%d anos' }, dayOfMonthOrdinalParse : /\d{1,2}º/, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration function processRelativeTime$4(number, withoutSuffix, key, isFuture) { var format = { 's': ['thodde secondanim', 'thodde second'], 'ss': [number + ' secondanim', number + ' second'], 'm': ['eka mintan', 'ek minute'], 'mm': [number + ' mintanim', number + ' mintam'], 'h': ['eka horan', 'ek hor'], 'hh': [number + ' horanim', number + ' hor'], 'd': ['eka disan', 'ek dis'], 'dd': [number + ' disanim', number + ' dis'], 'M': ['eka mhoinean', 'ek mhoino'], 'MM': [number + ' mhoineanim', number + ' mhoine'], 'y': ['eka vorsan', 'ek voros'], 'yy': [number + ' vorsanim', number + ' vorsam'] }; return withoutSuffix ? format[key][0] : format[key][1]; } moment.defineLocale('gom-latn', { months : 'Janer_Febrer_Mars_Abril_Mai_Jun_Julai_Agost_Setembr_Otubr_Novembr_Dezembr'.split('_'), monthsShort : 'Jan._Feb._Mars_Abr._Mai_Jun_Jul._Ago._Set._Otu._Nov._Dez.'.split('_'), monthsParseExact : true, weekdays : 'Aitar_Somar_Mongllar_Budvar_Brestar_Sukrar_Son\'var'.split('_'), weekdaysShort : 'Ait._Som._Mon._Bud._Bre._Suk._Son.'.split('_'), weekdaysMin : 'Ai_Sm_Mo_Bu_Br_Su_Sn'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'A h:mm [vazta]', LTS : 'A h:mm:ss [vazta]', L : 'DD-MM-YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY A h:mm [vazta]', LLLL : 'dddd, MMMM[achea] Do, YYYY, A h:mm [vazta]', llll: 'ddd, D MMM YYYY, A h:mm [vazta]' }, calendar : { sameDay: '[Aiz] LT', nextDay: '[Faleam] LT', nextWeek: '[Ieta to] dddd[,] LT', lastDay: '[Kal] LT', lastWeek: '[Fatlo] dddd[,] LT', sameElse: 'L' }, relativeTime : { future : '%s', past : '%s adim', s : processRelativeTime$4, ss : processRelativeTime$4, m : processRelativeTime$4, mm : processRelativeTime$4, h : processRelativeTime$4, hh : processRelativeTime$4, d : processRelativeTime$4, dd : processRelativeTime$4, M : processRelativeTime$4, MM : processRelativeTime$4, y : processRelativeTime$4, yy : processRelativeTime$4 }, dayOfMonthOrdinalParse : /\d{1,2}(er)/, ordinal : function (number, period) { switch (period) { // the ordinal 'er' only applies to day of the month case 'D': return number + 'er'; default: case 'M': case 'Q': case 'DDD': case 'd': case 'w': case 'W': return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. }, meridiemParse: /rati|sokalli|donparam|sanje/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'rati') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'sokalli') { return hour; } else if (meridiem === 'donparam') { return hour > 12 ? hour : hour + 12; } else if (meridiem === 'sanje') { return hour + 12; } }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return 'rati'; } else if (hour < 12) { return 'sokalli'; } else if (hour < 16) { return 'donparam'; } else if (hour < 20) { return 'sanje'; } else { return 'rati'; } } }); //! moment.js locale configuration var symbolMap$6 = { '1': '૧', '2': '૨', '3': '૩', '4': '૪', '5': '૫', '6': '૬', '7': '૭', '8': '૮', '9': '૯', '0': '૦' }, numberMap$5 = { '૧': '1', '૨': '2', '૩': '3', '૪': '4', '૫': '5', '૬': '6', '૭': '7', '૮': '8', '૯': '9', '૦': '0' }; moment.defineLocale('gu', { months: 'જાન્યુઆરી_ફેબ્રુઆરી_માર્ચ_એપ્રિલ_મે_જૂન_જુલાઈ_ઑગસ્ટ_સપ્ટેમ્બર_ઑક્ટ્બર_નવેમ્બર_ડિસેમ્બર'.split('_'), monthsShort: 'જાન્યુ._ફેબ્રુ._માર્ચ_એપ્રિ._મે_જૂન_જુલા._ઑગ._સપ્ટે._ઑક્ટ્._નવે._ડિસે.'.split('_'), monthsParseExact: true, weekdays: 'રવિવાર_સોમવાર_મંગળવાર_બુધ્વાર_ગુરુવાર_શુક્રવાર_શનિવાર'.split('_'), weekdaysShort: 'રવિ_સોમ_મંગળ_બુધ્_ગુરુ_શુક્ર_શનિ'.split('_'), weekdaysMin: 'ર_સો_મં_બુ_ગુ_શુ_શ'.split('_'), longDateFormat: { LT: 'A h:mm વાગ્યે', LTS: 'A h:mm:ss વાગ્યે', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY, A h:mm વાગ્યે', LLLL: 'dddd, D MMMM YYYY, A h:mm વાગ્યે' }, calendar: { sameDay: '[આજ] LT', nextDay: '[કાલે] LT', nextWeek: 'dddd, LT', lastDay: '[ગઇકાલે] LT', lastWeek: '[પાછલા] dddd, LT', sameElse: 'L' }, relativeTime: { future: '%s મા', past: '%s પેહલા', s: 'અમુક પળો', ss: '%d સેકંડ', m: 'એક મિનિટ', mm: '%d મિનિટ', h: 'એક કલાક', hh: '%d કલાક', d: 'એક દિવસ', dd: '%d દિવસ', M: 'એક મહિનો', MM: '%d મહિનો', y: 'એક વર્ષ', yy: '%d વર્ષ' }, preparse: function (string) { return string.replace(/[૧૨૩૪૫૬૭૮૯૦]/g, function (match) { return numberMap$5[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap$6[match]; }); }, // Gujarati notation for meridiems are quite fuzzy in practice. While there exists // a rigid notion of a 'Pahar' it is not used as rigidly in modern Gujarati. meridiemParse: /રાત|બપોર|સવાર|સાંજ/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'રાત') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'સવાર') { return hour; } else if (meridiem === 'બપોર') { return hour >= 10 ? hour : hour + 12; } else if (meridiem === 'સાંજ') { return hour + 12; } }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return 'રાત'; } else if (hour < 10) { return 'સવાર'; } else if (hour < 17) { return 'બપોર'; } else if (hour < 20) { return 'સાંજ'; } else { return 'રાત'; } }, week: { dow: 0, // Sunday is the first day of the week. doy: 6 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('he', { months : 'ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר'.split('_'), monthsShort : 'ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳'.split('_'), weekdays : 'ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת'.split('_'), weekdaysShort : 'א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳'.split('_'), weekdaysMin : 'א_ב_ג_ד_ה_ו_ש'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D [ב]MMMM YYYY', LLL : 'D [ב]MMMM YYYY HH:mm', LLLL : 'dddd, D [ב]MMMM YYYY HH:mm', l : 'D/M/YYYY', ll : 'D MMM YYYY', lll : 'D MMM YYYY HH:mm', llll : 'ddd, D MMM YYYY HH:mm' }, calendar : { sameDay : '[היום ב־]LT', nextDay : '[מחר ב־]LT', nextWeek : 'dddd [בשעה] LT', lastDay : '[אתמול ב־]LT', lastWeek : '[ביום] dddd [האחרון בשעה] LT', sameElse : 'L' }, relativeTime : { future : 'בעוד %s', past : 'לפני %s', s : 'מספר שניות', ss : '%d שניות', m : 'דקה', mm : '%d דקות', h : 'שעה', hh : function (number) { if (number === 2) { return 'שעתיים'; } return number + ' שעות'; }, d : 'יום', dd : function (number) { if (number === 2) { return 'יומיים'; } return number + ' ימים'; }, M : 'חודש', MM : function (number) { if (number === 2) { return 'חודשיים'; } return number + ' חודשים'; }, y : 'שנה', yy : function (number) { if (number === 2) { return 'שנתיים'; } else if (number % 10 === 0 && number !== 10) { return number + ' שנה'; } return number + ' שנים'; } }, meridiemParse: /אחה"צ|לפנה"צ|אחרי הצהריים|לפני הצהריים|לפנות בוקר|בבוקר|בערב/i, isPM : function (input) { return /^(אחה"צ|אחרי הצהריים|בערב)$/.test(input); }, meridiem : function (hour, minute, isLower) { if (hour < 5) { return 'לפנות בוקר'; } else if (hour < 10) { return 'בבוקר'; } else if (hour < 12) { return isLower ? 'לפנה"צ' : 'לפני הצהריים'; } else if (hour < 18) { return isLower ? 'אחה"צ' : 'אחרי הצהריים'; } else { return 'בערב'; } } }); //! moment.js locale configuration var symbolMap$7 = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap$6 = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; moment.defineLocale('hi', { months : 'जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर'.split('_'), monthsShort : 'जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.'.split('_'), monthsParseExact: true, weekdays : 'रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'), weekdaysShort : 'रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि'.split('_'), weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split('_'), longDateFormat : { LT : 'A h:mm बजे', LTS : 'A h:mm:ss बजे', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY, A h:mm बजे', LLLL : 'dddd, D MMMM YYYY, A h:mm बजे' }, calendar : { sameDay : '[आज] LT', nextDay : '[कल] LT', nextWeek : 'dddd, LT', lastDay : '[कल] LT', lastWeek : '[पिछले] dddd, LT', sameElse : 'L' }, relativeTime : { future : '%s में', past : '%s पहले', s : 'कुछ ही क्षण', ss : '%d सेकंड', m : 'एक मिनट', mm : '%d मिनट', h : 'एक घंटा', hh : '%d घंटे', d : 'एक दिन', dd : '%d दिन', M : 'एक महीने', MM : '%d महीने', y : 'एक वर्ष', yy : '%d वर्ष' }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap$6[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap$7[match]; }); }, // Hindi notation for meridiems are quite fuzzy in practice. While there exists // a rigid notion of a 'Pahar' it is not used as rigidly in modern Hindi. meridiemParse: /रात|सुबह|दोपहर|शाम/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'रात') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'सुबह') { return hour; } else if (meridiem === 'दोपहर') { return hour >= 10 ? hour : hour + 12; } else if (meridiem === 'शाम') { return hour + 12; } }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return 'रात'; } else if (hour < 10) { return 'सुबह'; } else if (hour < 17) { return 'दोपहर'; } else if (hour < 20) { return 'शाम'; } else { return 'रात'; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration function translate$3(number, withoutSuffix, key) { var result = number + ' '; switch (key) { case 'ss': if (number === 1) { result += 'sekunda'; } else if (number === 2 || number === 3 || number === 4) { result += 'sekunde'; } else { result += 'sekundi'; } return result; case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mjesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'mjeseca'; } else { result += 'mjeseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } moment.defineLocale('hr', { months : { format: 'siječnja_veljače_ožujka_travnja_svibnja_lipnja_srpnja_kolovoza_rujna_listopada_studenoga_prosinca'.split('_'), standalone: 'siječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac'.split('_') }, monthsShort : 'sij._velj._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.'.split('_'), monthsParseExact: true, weekdays : 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'), weekdaysShort : 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), weekdaysMin : 'ne_po_ut_sr_če_pe_su'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'DD.MM.YYYY', LL : 'D. MMMM YYYY', LLL : 'D. MMMM YYYY H:mm', LLLL : 'dddd, D. MMMM YYYY H:mm' }, calendar : { sameDay : '[danas u] LT', nextDay : '[sutra u] LT', nextWeek : function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; case 3: return '[u] [srijedu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[jučer u] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: return '[prošlu] dddd [u] LT'; case 6: return '[prošle] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[prošli] dddd [u] LT'; } }, sameElse : 'L' }, relativeTime : { future : 'za %s', past : 'prije %s', s : 'par sekundi', ss : translate$3, m : translate$3, mm : translate$3, h : translate$3, hh : translate$3, d : 'dan', dd : translate$3, M : 'mjesec', MM : translate$3, y : 'godinu', yy : translate$3 }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' '); function translate$4(number, withoutSuffix, key, isFuture) { var num = number; switch (key) { case 's': return (isFuture || withoutSuffix) ? 'néhány másodperc' : 'néhány másodperce'; case 'ss': return num + (isFuture || withoutSuffix) ? ' másodperc' : ' másodperce'; case 'm': return 'egy' + (isFuture || withoutSuffix ? ' perc' : ' perce'); case 'mm': return num + (isFuture || withoutSuffix ? ' perc' : ' perce'); case 'h': return 'egy' + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'hh': return num + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'd': return 'egy' + (isFuture || withoutSuffix ? ' nap' : ' napja'); case 'dd': return num + (isFuture || withoutSuffix ? ' nap' : ' napja'); case 'M': return 'egy' + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); case 'MM': return num + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); case 'y': return 'egy' + (isFuture || withoutSuffix ? ' év' : ' éve'); case 'yy': return num + (isFuture || withoutSuffix ? ' év' : ' éve'); } return ''; } function week(isFuture) { return (isFuture ? '' : '[múlt] ') + '[' + weekEndings[this.day()] + '] LT[-kor]'; } moment.defineLocale('hu', { months : 'január_február_március_április_május_június_július_augusztus_szeptember_október_november_december'.split('_'), monthsShort : 'jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec'.split('_'), weekdays : 'vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat'.split('_'), weekdaysShort : 'vas_hét_kedd_sze_csüt_pén_szo'.split('_'), weekdaysMin : 'v_h_k_sze_cs_p_szo'.split('_'), longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'YYYY.MM.DD.', LL : 'YYYY. MMMM D.', LLL : 'YYYY. MMMM D. H:mm', LLLL : 'YYYY. MMMM D., dddd H:mm' }, meridiemParse: /de|du/i, isPM: function (input) { return input.charAt(1).toLowerCase() === 'u'; }, meridiem : function (hours, minutes, isLower) { if (hours < 12) { return isLower === true ? 'de' : 'DE'; } else { return isLower === true ? 'du' : 'DU'; } }, calendar : { sameDay : '[ma] LT[-kor]', nextDay : '[holnap] LT[-kor]', nextWeek : function () { return week.call(this, true); }, lastDay : '[tegnap] LT[-kor]', lastWeek : function () { return week.call(this, false); }, sameElse : 'L' }, relativeTime : { future : '%s múlva', past : '%s', s : translate$4, ss : translate$4, m : translate$4, mm : translate$4, h : translate$4, hh : translate$4, d : translate$4, dd : translate$4, M : translate$4, MM : translate$4, y : translate$4, yy : translate$4 }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('hy-am', { months : { format: 'հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի'.split('_'), standalone: 'հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր'.split('_') }, monthsShort : 'հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ'.split('_'), weekdays : 'կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ'.split('_'), weekdaysShort : 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'), weekdaysMin : 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D MMMM YYYY թ.', LLL : 'D MMMM YYYY թ., HH:mm', LLLL : 'dddd, D MMMM YYYY թ., HH:mm' }, calendar : { sameDay: '[այսօր] LT', nextDay: '[վաղը] LT', lastDay: '[երեկ] LT', nextWeek: function () { return 'dddd [օրը ժամը] LT'; }, lastWeek: function () { return '[անցած] dddd [օրը ժամը] LT'; }, sameElse: 'L' }, relativeTime : { future : '%s հետո', past : '%s առաջ', s : 'մի քանի վայրկյան', ss : '%d վայրկյան', m : 'րոպե', mm : '%d րոպե', h : 'ժամ', hh : '%d ժամ', d : 'օր', dd : '%d օր', M : 'ամիս', MM : '%d ամիս', y : 'տարի', yy : '%d տարի' }, meridiemParse: /գիշերվա|առավոտվա|ցերեկվա|երեկոյան/, isPM: function (input) { return /^(ցերեկվա|երեկոյան)$/.test(input); }, meridiem : function (hour) { if (hour < 4) { return 'գիշերվա'; } else if (hour < 12) { return 'առավոտվա'; } else if (hour < 17) { return 'ցերեկվա'; } else { return 'երեկոյան'; } }, dayOfMonthOrdinalParse: /\d{1,2}|\d{1,2}-(ին|րդ)/, ordinal: function (number, period) { switch (period) { case 'DDD': case 'w': case 'W': case 'DDDo': if (number === 1) { return number + '-ին'; } return number + '-րդ'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('id', { months : 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember'.split('_'), monthsShort : 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Agt_Sep_Okt_Nov_Des'.split('_'), weekdays : 'Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu'.split('_'), weekdaysShort : 'Min_Sen_Sel_Rab_Kam_Jum_Sab'.split('_'), weekdaysMin : 'Mg_Sn_Sl_Rb_Km_Jm_Sb'.split('_'), longDateFormat : { LT : 'HH.mm', LTS : 'HH.mm.ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY [pukul] HH.mm', LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm' }, meridiemParse: /pagi|siang|sore|malam/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'pagi') { return hour; } else if (meridiem === 'siang') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === 'sore' || meridiem === 'malam') { return hour + 12; } }, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'siang'; } else if (hours < 19) { return 'sore'; } else { return 'malam'; } }, calendar : { sameDay : '[Hari ini pukul] LT', nextDay : '[Besok pukul] LT', nextWeek : 'dddd [pukul] LT', lastDay : '[Kemarin pukul] LT', lastWeek : 'dddd [lalu pukul] LT', sameElse : 'L' }, relativeTime : { future : 'dalam %s', past : '%s yang lalu', s : 'beberapa detik', ss : '%d detik', m : 'semenit', mm : '%d menit', h : 'sejam', hh : '%d jam', d : 'sehari', dd : '%d hari', M : 'sebulan', MM : '%d bulan', y : 'setahun', yy : '%d tahun' }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration function plural$2(n) { if (n % 100 === 11) { return true; } else if (n % 10 === 1) { return false; } return true; } function translate$5(number, withoutSuffix, key, isFuture) { var result = number + ' '; switch (key) { case 's': return withoutSuffix || isFuture ? 'nokkrar sekúndur' : 'nokkrum sekúndum'; case 'ss': if (plural$2(number)) { return result + (withoutSuffix || isFuture ? 'sekúndur' : 'sekúndum'); } return result + 'sekúnda'; case 'm': return withoutSuffix ? 'mínúta' : 'mínútu'; case 'mm': if (plural$2(number)) { return result + (withoutSuffix || isFuture ? 'mínútur' : 'mínútum'); } else if (withoutSuffix) { return result + 'mínúta'; } return result + 'mínútu'; case 'hh': if (plural$2(number)) { return result + (withoutSuffix || isFuture ? 'klukkustundir' : 'klukkustundum'); } return result + 'klukkustund'; case 'd': if (withoutSuffix) { return 'dagur'; } return isFuture ? 'dag' : 'degi'; case 'dd': if (plural$2(number)) { if (withoutSuffix) { return result + 'dagar'; } return result + (isFuture ? 'daga' : 'dögum'); } else if (withoutSuffix) { return result + 'dagur'; } return result + (isFuture ? 'dag' : 'degi'); case 'M': if (withoutSuffix) { return 'mánuður'; } return isFuture ? 'mánuð' : 'mánuði'; case 'MM': if (plural$2(number)) { if (withoutSuffix) { return result + 'mánuðir'; } return result + (isFuture ? 'mánuði' : 'mánuðum'); } else if (withoutSuffix) { return result + 'mánuður'; } return result + (isFuture ? 'mánuð' : 'mánuði'); case 'y': return withoutSuffix || isFuture ? 'ár' : 'ári'; case 'yy': if (plural$2(number)) { return result + (withoutSuffix || isFuture ? 'ár' : 'árum'); } return result + (withoutSuffix || isFuture ? 'ár' : 'ári'); } } moment.defineLocale('is', { months : 'janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember'.split('_'), monthsShort : 'jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des'.split('_'), weekdays : 'sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur'.split('_'), weekdaysShort : 'sun_mán_þri_mið_fim_fös_lau'.split('_'), weekdaysMin : 'Su_Má_Þr_Mi_Fi_Fö_La'.split('_'), longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'DD.MM.YYYY', LL : 'D. MMMM YYYY', LLL : 'D. MMMM YYYY [kl.] H:mm', LLLL : 'dddd, D. MMMM YYYY [kl.] H:mm' }, calendar : { sameDay : '[í dag kl.] LT', nextDay : '[á morgun kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[í gær kl.] LT', lastWeek : '[síðasta] dddd [kl.] LT', sameElse : 'L' }, relativeTime : { future : 'eftir %s', past : 'fyrir %s síðan', s : translate$5, ss : translate$5, m : translate$5, mm : translate$5, h : 'klukkustund', hh : translate$5, d : translate$5, dd : translate$5, M : translate$5, MM : translate$5, y : translate$5, yy : translate$5 }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('it', { months : 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split('_'), monthsShort : 'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'), weekdays : 'domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato'.split('_'), weekdaysShort : 'dom_lun_mar_mer_gio_ven_sab'.split('_'), weekdaysMin : 'do_lu_ma_me_gi_ve_sa'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { sameDay: '[Oggi alle] LT', nextDay: '[Domani alle] LT', nextWeek: 'dddd [alle] LT', lastDay: '[Ieri alle] LT', lastWeek: function () { switch (this.day()) { case 0: return '[la scorsa] dddd [alle] LT'; default: return '[lo scorso] dddd [alle] LT'; } }, sameElse: 'L' }, relativeTime : { future : function (s) { return ((/^[0-9].+$/).test(s) ? 'tra' : 'in') + ' ' + s; }, past : '%s fa', s : 'alcuni secondi', ss : '%d secondi', m : 'un minuto', mm : '%d minuti', h : 'un\'ora', hh : '%d ore', d : 'un giorno', dd : '%d giorni', M : 'un mese', MM : '%d mesi', y : 'un anno', yy : '%d anni' }, dayOfMonthOrdinalParse : /\d{1,2}º/, ordinal: '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('ja', { months : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), weekdays : '日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日'.split('_'), weekdaysShort : '日_月_火_水_木_金_土'.split('_'), weekdaysMin : '日_月_火_水_木_金_土'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'YYYY/MM/DD', LL : 'YYYY年M月D日', LLL : 'YYYY年M月D日 HH:mm', LLLL : 'YYYY年M月D日 HH:mm dddd', l : 'YYYY/MM/DD', ll : 'YYYY年M月D日', lll : 'YYYY年M月D日 HH:mm', llll : 'YYYY年M月D日 HH:mm dddd' }, meridiemParse: /午前|午後/i, isPM : function (input) { return input === '午後'; }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return '午前'; } else { return '午後'; } }, calendar : { sameDay : '[今日] LT', nextDay : '[明日] LT', nextWeek : '[来週]dddd LT', lastDay : '[昨日] LT', lastWeek : '[前週]dddd LT', sameElse : 'L' }, dayOfMonthOrdinalParse : /\d{1,2}日/, ordinal : function (number, period) { switch (period) { case 'd': case 'D': case 'DDD': return number + '日'; default: return number; } }, relativeTime : { future : '%s後', past : '%s前', s : '数秒', ss : '%d秒', m : '1分', mm : '%d分', h : '1時間', hh : '%d時間', d : '1日', dd : '%d日', M : '1ヶ月', MM : '%dヶ月', y : '1年', yy : '%d年' } }); //! moment.js locale configuration moment.defineLocale('jv', { months : 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_Nopember_Desember'.split('_'), monthsShort : 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nop_Des'.split('_'), weekdays : 'Minggu_Senen_Seloso_Rebu_Kemis_Jemuwah_Septu'.split('_'), weekdaysShort : 'Min_Sen_Sel_Reb_Kem_Jem_Sep'.split('_'), weekdaysMin : 'Mg_Sn_Sl_Rb_Km_Jm_Sp'.split('_'), longDateFormat : { LT : 'HH.mm', LTS : 'HH.mm.ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY [pukul] HH.mm', LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm' }, meridiemParse: /enjing|siyang|sonten|ndalu/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'enjing') { return hour; } else if (meridiem === 'siyang') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === 'sonten' || meridiem === 'ndalu') { return hour + 12; } }, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'enjing'; } else if (hours < 15) { return 'siyang'; } else if (hours < 19) { return 'sonten'; } else { return 'ndalu'; } }, calendar : { sameDay : '[Dinten puniko pukul] LT', nextDay : '[Mbenjang pukul] LT', nextWeek : 'dddd [pukul] LT', lastDay : '[Kala wingi pukul] LT', lastWeek : 'dddd [kepengker pukul] LT', sameElse : 'L' }, relativeTime : { future : 'wonten ing %s', past : '%s ingkang kepengker', s : 'sawetawis detik', ss : '%d detik', m : 'setunggal menit', mm : '%d menit', h : 'setunggal jam', hh : '%d jam', d : 'sedinten', dd : '%d dinten', M : 'sewulan', MM : '%d wulan', y : 'setaun', yy : '%d taun' }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('ka', { months : { standalone: 'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split('_'), format: 'იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს'.split('_') }, monthsShort : 'იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ'.split('_'), weekdays : { standalone: 'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split('_'), format: 'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split('_'), isFormat: /(წინა|შემდეგ)/ }, weekdaysShort : 'კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ'.split('_'), weekdaysMin : 'კვ_ორ_სა_ოთ_ხუ_პა_შა'.split('_'), longDateFormat : { LT : 'h:mm A', LTS : 'h:mm:ss A', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY h:mm A', LLLL : 'dddd, D MMMM YYYY h:mm A' }, calendar : { sameDay : '[დღეს] LT[-ზე]', nextDay : '[ხვალ] LT[-ზე]', lastDay : '[გუშინ] LT[-ზე]', nextWeek : '[შემდეგ] dddd LT[-ზე]', lastWeek : '[წინა] dddd LT-ზე', sameElse : 'L' }, relativeTime : { future : function (s) { return (/(წამი|წუთი|საათი|წელი)/).test(s) ? s.replace(/ი$/, 'ში') : s + 'ში'; }, past : function (s) { if ((/(წამი|წუთი|საათი|დღე|თვე)/).test(s)) { return s.replace(/(ი|ე)$/, 'ის უკან'); } if ((/წელი/).test(s)) { return s.replace(/წელი$/, 'წლის უკან'); } }, s : 'რამდენიმე წამი', ss : '%d წამი', m : 'წუთი', mm : '%d წუთი', h : 'საათი', hh : '%d საათი', d : 'დღე', dd : '%d დღე', M : 'თვე', MM : '%d თვე', y : 'წელი', yy : '%d წელი' }, dayOfMonthOrdinalParse: /0|1-ლი|მე-\d{1,2}|\d{1,2}-ე/, ordinal : function (number) { if (number === 0) { return number; } if (number === 1) { return number + '-ლი'; } if ((number < 20) || (number <= 100 && (number % 20 === 0)) || (number % 100 === 0)) { return 'მე-' + number; } return number + '-ე'; }, week : { dow : 1, doy : 7 } }); //! moment.js locale configuration var suffixes$1 = { 0: '-ші', 1: '-ші', 2: '-ші', 3: '-ші', 4: '-ші', 5: '-ші', 6: '-шы', 7: '-ші', 8: '-ші', 9: '-шы', 10: '-шы', 20: '-шы', 30: '-шы', 40: '-шы', 50: '-ші', 60: '-шы', 70: '-ші', 80: '-ші', 90: '-шы', 100: '-ші' }; moment.defineLocale('kk', { months : 'қаңтар_ақпан_наурыз_сәуір_мамыр_маусым_шілде_тамыз_қыркүйек_қазан_қараша_желтоқсан'.split('_'), monthsShort : 'қаң_ақп_нау_сәу_мам_мау_шіл_там_қыр_қаз_қар_жел'.split('_'), weekdays : 'жексенбі_дүйсенбі_сейсенбі_сәрсенбі_бейсенбі_жұма_сенбі'.split('_'), weekdaysShort : 'жек_дүй_сей_сәр_бей_жұм_сен'.split('_'), weekdaysMin : 'жк_дй_сй_ср_бй_жм_сн'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay : '[Бүгін сағат] LT', nextDay : '[Ертең сағат] LT', nextWeek : 'dddd [сағат] LT', lastDay : '[Кеше сағат] LT', lastWeek : '[Өткен аптаның] dddd [сағат] LT', sameElse : 'L' }, relativeTime : { future : '%s ішінде', past : '%s бұрын', s : 'бірнеше секунд', ss : '%d секунд', m : 'бір минут', mm : '%d минут', h : 'бір сағат', hh : '%d сағат', d : 'бір күн', dd : '%d күн', M : 'бір ай', MM : '%d ай', y : 'бір жыл', yy : '%d жыл' }, dayOfMonthOrdinalParse: /\d{1,2}-(ші|шы)/, ordinal : function (number) { var a = number % 10, b = number >= 100 ? 100 : null; return number + (suffixes$1[number] || suffixes$1[a] || suffixes$1[b]); }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('km', { months: 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split('_'), monthsShort: 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split('_'), weekdays: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'), weekdaysShort: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'), weekdaysMin: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'), longDateFormat: { LT: 'HH:mm', LTS : 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, calendar: { sameDay: '[ថ្ងៃនេះ ម៉ោង] LT', nextDay: '[ស្អែក ម៉ោង] LT', nextWeek: 'dddd [ម៉ោង] LT', lastDay: '[ម្សិលមិញ ម៉ោង] LT', lastWeek: 'dddd [សប្តាហ៍មុន] [ម៉ោង] LT', sameElse: 'L' }, relativeTime: { future: '%sទៀត', past: '%sមុន', s: 'ប៉ុន្មានវិនាទី', ss: '%d វិនាទី', m: 'មួយនាទី', mm: '%d នាទី', h: 'មួយម៉ោង', hh: '%d ម៉ោង', d: 'មួយថ្ងៃ', dd: '%d ថ្ងៃ', M: 'មួយខែ', MM: '%d ខែ', y: 'មួយឆ្នាំ', yy: '%d ឆ្នាំ' }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var symbolMap$8 = { '1': '೧', '2': '೨', '3': '೩', '4': '೪', '5': '೫', '6': '೬', '7': '೭', '8': '೮', '9': '೯', '0': '೦' }, numberMap$7 = { '೧': '1', '೨': '2', '೩': '3', '೪': '4', '೫': '5', '೬': '6', '೭': '7', '೮': '8', '೯': '9', '೦': '0' }; moment.defineLocale('kn', { months : 'ಜನವರಿ_ಫೆಬ್ರವರಿ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂಬರ್_ಅಕ್ಟೋಬರ್_ನವೆಂಬರ್_ಡಿಸೆಂಬರ್'.split('_'), monthsShort : 'ಜನ_ಫೆಬ್ರ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂ_ಅಕ್ಟೋ_ನವೆಂ_ಡಿಸೆಂ'.split('_'), monthsParseExact: true, weekdays : 'ಭಾನುವಾರ_ಸೋಮವಾರ_ಮಂಗಳವಾರ_ಬುಧವಾರ_ಗುರುವಾರ_ಶುಕ್ರವಾರ_ಶನಿವಾರ'.split('_'), weekdaysShort : 'ಭಾನು_ಸೋಮ_ಮಂಗಳ_ಬುಧ_ಗುರು_ಶುಕ್ರ_ಶನಿ'.split('_'), weekdaysMin : 'ಭಾ_ಸೋ_ಮಂ_ಬು_ಗು_ಶು_ಶ'.split('_'), longDateFormat : { LT : 'A h:mm', LTS : 'A h:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY, A h:mm', LLLL : 'dddd, D MMMM YYYY, A h:mm' }, calendar : { sameDay : '[ಇಂದು] LT', nextDay : '[ನಾಳೆ] LT', nextWeek : 'dddd, LT', lastDay : '[ನಿನ್ನೆ] LT', lastWeek : '[ಕೊನೆಯ] dddd, LT', sameElse : 'L' }, relativeTime : { future : '%s ನಂತರ', past : '%s ಹಿಂದೆ', s : 'ಕೆಲವು ಕ್ಷಣಗಳು', ss : '%d ಸೆಕೆಂಡುಗಳು', m : 'ಒಂದು ನಿಮಿಷ', mm : '%d ನಿಮಿಷ', h : 'ಒಂದು ಗಂಟೆ', hh : '%d ಗಂಟೆ', d : 'ಒಂದು ದಿನ', dd : '%d ದಿನ', M : 'ಒಂದು ತಿಂಗಳು', MM : '%d ತಿಂಗಳು', y : 'ಒಂದು ವರ್ಷ', yy : '%d ವರ್ಷ' }, preparse: function (string) { return string.replace(/[೧೨೩೪೫೬೭೮೯೦]/g, function (match) { return numberMap$7[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap$8[match]; }); }, meridiemParse: /ರಾತ್ರಿ|ಬೆಳಿಗ್ಗೆ|ಮಧ್ಯಾಹ್ನ|ಸಂಜೆ/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'ರಾತ್ರಿ') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'ಬೆಳಿಗ್ಗೆ') { return hour; } else if (meridiem === 'ಮಧ್ಯಾಹ್ನ') { return hour >= 10 ? hour : hour + 12; } else if (meridiem === 'ಸಂಜೆ') { return hour + 12; } }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return 'ರಾತ್ರಿ'; } else if (hour < 10) { return 'ಬೆಳಿಗ್ಗೆ'; } else if (hour < 17) { return 'ಮಧ್ಯಾಹ್ನ'; } else if (hour < 20) { return 'ಸಂಜೆ'; } else { return 'ರಾತ್ರಿ'; } }, dayOfMonthOrdinalParse: /\d{1,2}(ನೇ)/, ordinal : function (number) { return number + 'ನೇ'; }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('ko', { months : '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'), monthsShort : '1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월'.split('_'), weekdays : '일요일_월요일_화요일_수요일_목요일_금요일_토요일'.split('_'), weekdaysShort : '일_월_화_수_목_금_토'.split('_'), weekdaysMin : '일_월_화_수_목_금_토'.split('_'), longDateFormat : { LT : 'A h:mm', LTS : 'A h:mm:ss', L : 'YYYY.MM.DD.', LL : 'YYYY년 MMMM D일', LLL : 'YYYY년 MMMM D일 A h:mm', LLLL : 'YYYY년 MMMM D일 dddd A h:mm', l : 'YYYY.MM.DD.', ll : 'YYYY년 MMMM D일', lll : 'YYYY년 MMMM D일 A h:mm', llll : 'YYYY년 MMMM D일 dddd A h:mm' }, calendar : { sameDay : '오늘 LT', nextDay : '내일 LT', nextWeek : 'dddd LT', lastDay : '어제 LT', lastWeek : '지난주 dddd LT', sameElse : 'L' }, relativeTime : { future : '%s 후', past : '%s 전', s : '몇 초', ss : '%d초', m : '1분', mm : '%d분', h : '한 시간', hh : '%d시간', d : '하루', dd : '%d일', M : '한 달', MM : '%d달', y : '일 년', yy : '%d년' }, dayOfMonthOrdinalParse : /\d{1,2}(일|월|주)/, ordinal : function (number, period) { switch (period) { case 'd': case 'D': case 'DDD': return number + '일'; case 'M': return number + '월'; case 'w': case 'W': return number + '주'; default: return number; } }, meridiemParse : /오전|오후/, isPM : function (token) { return token === '오후'; }, meridiem : function (hour, minute, isUpper) { return hour < 12 ? '오전' : '오후'; } }); //! moment.js locale configuration var suffixes$2 = { 0: '-чү', 1: '-чи', 2: '-чи', 3: '-чү', 4: '-чү', 5: '-чи', 6: '-чы', 7: '-чи', 8: '-чи', 9: '-чу', 10: '-чу', 20: '-чы', 30: '-чу', 40: '-чы', 50: '-чү', 60: '-чы', 70: '-чи', 80: '-чи', 90: '-чу', 100: '-чү' }; moment.defineLocale('ky', { months : 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'), monthsShort : 'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'), weekdays : 'Жекшемби_Дүйшөмбү_Шейшемби_Шаршемби_Бейшемби_Жума_Ишемби'.split('_'), weekdaysShort : 'Жек_Дүй_Шей_Шар_Бей_Жум_Ише'.split('_'), weekdaysMin : 'Жк_Дй_Шй_Шр_Бй_Жм_Иш'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay : '[Бүгүн саат] LT', nextDay : '[Эртең саат] LT', nextWeek : 'dddd [саат] LT', lastDay : '[Кече саат] LT', lastWeek : '[Өткен аптанын] dddd [күнү] [саат] LT', sameElse : 'L' }, relativeTime : { future : '%s ичинде', past : '%s мурун', s : 'бирнече секунд', ss : '%d секунд', m : 'бир мүнөт', mm : '%d мүнөт', h : 'бир саат', hh : '%d саат', d : 'бир күн', dd : '%d күн', M : 'бир ай', MM : '%d ай', y : 'бир жыл', yy : '%d жыл' }, dayOfMonthOrdinalParse: /\d{1,2}-(чи|чы|чү|чу)/, ordinal : function (number) { var a = number % 10, b = number >= 100 ? 100 : null; return number + (suffixes$2[number] || suffixes$2[a] || suffixes$2[b]); }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration function processRelativeTime$5(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eng Minutt', 'enger Minutt'], 'h': ['eng Stonn', 'enger Stonn'], 'd': ['een Dag', 'engem Dag'], 'M': ['ee Mount', 'engem Mount'], 'y': ['ee Joer', 'engem Joer'] }; return withoutSuffix ? format[key][0] : format[key][1]; } function processFutureTime(string) { var number = string.substr(0, string.indexOf(' ')); if (eifelerRegelAppliesToNumber(number)) { return 'a ' + string; } return 'an ' + string; } function processPastTime(string) { var number = string.substr(0, string.indexOf(' ')); if (eifelerRegelAppliesToNumber(number)) { return 'viru ' + string; } return 'virun ' + string; } /** * Returns true if the word before the given number loses the '-n' ending. * e.g. 'an 10 Deeg' but 'a 5 Deeg' * * @param number {integer} * @returns {boolean} */ function eifelerRegelAppliesToNumber(number) { number = parseInt(number, 10); if (isNaN(number)) { return false; } if (number < 0) { // Negative Number --> always true return true; } else if (number < 10) { // Only 1 digit if (4 <= number && number <= 7) { return true; } return false; } else if (number < 100) { // 2 digits var lastDigit = number % 10, firstDigit = number / 10; if (lastDigit === 0) { return eifelerRegelAppliesToNumber(firstDigit); } return eifelerRegelAppliesToNumber(lastDigit); } else if (number < 10000) { // 3 or 4 digits --> recursively check first digit while (number >= 10) { number = number / 10; } return eifelerRegelAppliesToNumber(number); } else { // Anything larger than 4 digits: recursively check first n-3 digits number = number / 1000; return eifelerRegelAppliesToNumber(number); } } moment.defineLocale('lb', { months: 'Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'), monthsShort: 'Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'), monthsParseExact : true, weekdays: 'Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg'.split('_'), weekdaysShort: 'So._Mé._Dë._Më._Do._Fr._Sa.'.split('_'), weekdaysMin: 'So_Mé_Dë_Më_Do_Fr_Sa'.split('_'), weekdaysParseExact : true, longDateFormat: { LT: 'H:mm [Auer]', LTS: 'H:mm:ss [Auer]', L: 'DD.MM.YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY H:mm [Auer]', LLLL: 'dddd, D. MMMM YYYY H:mm [Auer]' }, calendar: { sameDay: '[Haut um] LT', sameElse: 'L', nextDay: '[Muer um] LT', nextWeek: 'dddd [um] LT', lastDay: '[Gëschter um] LT', lastWeek: function () { // Different date string for 'Dënschdeg' (Tuesday) and 'Donneschdeg' (Thursday) due to phonological rule switch (this.day()) { case 2: case 4: return '[Leschten] dddd [um] LT'; default: return '[Leschte] dddd [um] LT'; } } }, relativeTime : { future : processFutureTime, past : processPastTime, s : 'e puer Sekonnen', ss : '%d Sekonnen', m : processRelativeTime$5, mm : '%d Minutten', h : processRelativeTime$5, hh : '%d Stonnen', d : processRelativeTime$5, dd : '%d Deeg', M : processRelativeTime$5, MM : '%d Méint', y : processRelativeTime$5, yy : '%d Joer' }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('lo', { months : 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'), monthsShort : 'ມັງກອນ_ກຸມພາ_ມີນາ_ເມສາ_ພຶດສະພາ_ມິຖຸນາ_ກໍລະກົດ_ສິງຫາ_ກັນຍາ_ຕຸລາ_ພະຈິກ_ທັນວາ'.split('_'), weekdays : 'ອາທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'), weekdaysShort : 'ທິດ_ຈັນ_ອັງຄານ_ພຸດ_ພະຫັດ_ສຸກ_ເສົາ'.split('_'), weekdaysMin : 'ທ_ຈ_ອຄ_ພ_ພຫ_ສກ_ສ'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'ວັນdddd D MMMM YYYY HH:mm' }, meridiemParse: /ຕອນເຊົ້າ|ຕອນແລງ/, isPM: function (input) { return input === 'ຕອນແລງ'; }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return 'ຕອນເຊົ້າ'; } else { return 'ຕອນແລງ'; } }, calendar : { sameDay : '[ມື້ນີ້ເວລາ] LT', nextDay : '[ມື້ອື່ນເວລາ] LT', nextWeek : '[ວັນ]dddd[ໜ້າເວລາ] LT', lastDay : '[ມື້ວານນີ້ເວລາ] LT', lastWeek : '[ວັນ]dddd[ແລ້ວນີ້ເວລາ] LT', sameElse : 'L' }, relativeTime : { future : 'ອີກ %s', past : '%sຜ່ານມາ', s : 'ບໍ່ເທົ່າໃດວິນາທີ', ss : '%d ວິນາທີ' , m : '1 ນາທີ', mm : '%d ນາທີ', h : '1 ຊົ່ວໂມງ', hh : '%d ຊົ່ວໂມງ', d : '1 ມື້', dd : '%d ມື້', M : '1 ເດືອນ', MM : '%d ເດືອນ', y : '1 ປີ', yy : '%d ປີ' }, dayOfMonthOrdinalParse: /(ທີ່)\d{1,2}/, ordinal : function (number) { return 'ທີ່' + number; } }); //! moment.js locale configuration var units = { 'ss' : 'sekundė_sekundžių_sekundes', 'm' : 'minutė_minutės_minutę', 'mm': 'minutės_minučių_minutes', 'h' : 'valanda_valandos_valandą', 'hh': 'valandos_valandų_valandas', 'd' : 'diena_dienos_dieną', 'dd': 'dienos_dienų_dienas', 'M' : 'mėnuo_mėnesio_mėnesį', 'MM': 'mėnesiai_mėnesių_mėnesius', 'y' : 'metai_metų_metus', 'yy': 'metai_metų_metus' }; function translateSeconds(number, withoutSuffix, key, isFuture) { if (withoutSuffix) { return 'kelios sekundės'; } else { return isFuture ? 'kelių sekundžių' : 'kelias sekundes'; } } function translateSingular(number, withoutSuffix, key, isFuture) { return withoutSuffix ? forms(key)[0] : (isFuture ? forms(key)[1] : forms(key)[2]); } function special(number) { return number % 10 === 0 || (number > 10 && number < 20); } function forms(key) { return units[key].split('_'); } function translate$6(number, withoutSuffix, key, isFuture) { var result = number + ' '; if (number === 1) { return result + translateSingular(number, withoutSuffix, key[0], isFuture); } else if (withoutSuffix) { return result + (special(number) ? forms(key)[1] : forms(key)[0]); } else { if (isFuture) { return result + forms(key)[1]; } else { return result + (special(number) ? forms(key)[1] : forms(key)[2]); } } } moment.defineLocale('lt', { months : { format: 'sausio_vasario_kovo_balandžio_gegužės_birželio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio'.split('_'), standalone: 'sausis_vasaris_kovas_balandis_gegužė_birželis_liepa_rugpjūtis_rugsėjis_spalis_lapkritis_gruodis'.split('_'), isFormat: /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?|MMMM?(\[[^\[\]]*\]|\s)+D[oD]?/ }, monthsShort : 'sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd'.split('_'), weekdays : { format: 'sekmadienį_pirmadienį_antradienį_trečiadienį_ketvirtadienį_penktadienį_šeštadienį'.split('_'), standalone: 'sekmadienis_pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis'.split('_'), isFormat: /dddd HH:mm/ }, weekdaysShort : 'Sek_Pir_Ant_Tre_Ket_Pen_Šeš'.split('_'), weekdaysMin : 'S_P_A_T_K_Pn_Š'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'YYYY-MM-DD', LL : 'YYYY [m.] MMMM D [d.]', LLL : 'YYYY [m.] MMMM D [d.], HH:mm [val.]', LLLL : 'YYYY [m.] MMMM D [d.], dddd, HH:mm [val.]', l : 'YYYY-MM-DD', ll : 'YYYY [m.] MMMM D [d.]', lll : 'YYYY [m.] MMMM D [d.], HH:mm [val.]', llll : 'YYYY [m.] MMMM D [d.], ddd, HH:mm [val.]' }, calendar : { sameDay : '[Šiandien] LT', nextDay : '[Rytoj] LT', nextWeek : 'dddd LT', lastDay : '[Vakar] LT', lastWeek : '[Praėjusį] dddd LT', sameElse : 'L' }, relativeTime : { future : 'po %s', past : 'prieš %s', s : translateSeconds, ss : translate$6, m : translateSingular, mm : translate$6, h : translateSingular, hh : translate$6, d : translateSingular, dd : translate$6, M : translateSingular, MM : translate$6, y : translateSingular, yy : translate$6 }, dayOfMonthOrdinalParse: /\d{1,2}-oji/, ordinal : function (number) { return number + '-oji'; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var units$1 = { 'ss': 'sekundes_sekundēm_sekunde_sekundes'.split('_'), 'm': 'minūtes_minūtēm_minūte_minūtes'.split('_'), 'mm': 'minūtes_minūtēm_minūte_minūtes'.split('_'), 'h': 'stundas_stundām_stunda_stundas'.split('_'), 'hh': 'stundas_stundām_stunda_stundas'.split('_'), 'd': 'dienas_dienām_diena_dienas'.split('_'), 'dd': 'dienas_dienām_diena_dienas'.split('_'), 'M': 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'), 'MM': 'mēneša_mēnešiem_mēnesis_mēneši'.split('_'), 'y': 'gada_gadiem_gads_gadi'.split('_'), 'yy': 'gada_gadiem_gads_gadi'.split('_') }; /** * @param withoutSuffix boolean true = a length of time; false = before/after a period of time. */ function format(forms, number, withoutSuffix) { if (withoutSuffix) { // E.g. "21 minūte", "3 minūtes". return number % 10 === 1 && number % 100 !== 11 ? forms[2] : forms[3]; } else { // E.g. "21 minūtes" as in "pēc 21 minūtes". // E.g. "3 minūtēm" as in "pēc 3 minūtēm". return number % 10 === 1 && number % 100 !== 11 ? forms[0] : forms[1]; } } function relativeTimeWithPlural$1(number, withoutSuffix, key) { return number + ' ' + format(units$1[key], number, withoutSuffix); } function relativeTimeWithSingular(number, withoutSuffix, key) { return format(units$1[key], number, withoutSuffix); } function relativeSeconds(number, withoutSuffix) { return withoutSuffix ? 'dažas sekundes' : 'dažām sekundēm'; } moment.defineLocale('lv', { months : 'janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris'.split('_'), monthsShort : 'jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec'.split('_'), weekdays : 'svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena'.split('_'), weekdaysShort : 'Sv_P_O_T_C_Pk_S'.split('_'), weekdaysMin : 'Sv_P_O_T_C_Pk_S'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY.', LL : 'YYYY. [gada] D. MMMM', LLL : 'YYYY. [gada] D. MMMM, HH:mm', LLLL : 'YYYY. [gada] D. MMMM, dddd, HH:mm' }, calendar : { sameDay : '[Šodien pulksten] LT', nextDay : '[Rīt pulksten] LT', nextWeek : 'dddd [pulksten] LT', lastDay : '[Vakar pulksten] LT', lastWeek : '[Pagājušā] dddd [pulksten] LT', sameElse : 'L' }, relativeTime : { future : 'pēc %s', past : 'pirms %s', s : relativeSeconds, ss : relativeTimeWithPlural$1, m : relativeTimeWithSingular, mm : relativeTimeWithPlural$1, h : relativeTimeWithSingular, hh : relativeTimeWithPlural$1, d : relativeTimeWithSingular, dd : relativeTimeWithPlural$1, M : relativeTimeWithSingular, MM : relativeTimeWithPlural$1, y : relativeTimeWithSingular, yy : relativeTimeWithPlural$1 }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var translator = { words: { //Different grammatical cases ss: ['sekund', 'sekunda', 'sekundi'], m: ['jedan minut', 'jednog minuta'], mm: ['minut', 'minuta', 'minuta'], h: ['jedan sat', 'jednog sata'], hh: ['sat', 'sata', 'sati'], dd: ['dan', 'dana', 'dana'], MM: ['mjesec', 'mjeseca', 'mjeseci'], yy: ['godina', 'godine', 'godina'] }, correctGrammaticalCase: function (number, wordKey) { return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]); }, translate: function (number, withoutSuffix, key) { var wordKey = translator.words[key]; if (key.length === 1) { return withoutSuffix ? wordKey[0] : wordKey[1]; } else { return number + ' ' + translator.correctGrammaticalCase(number, wordKey); } } }; moment.defineLocale('me', { months: 'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split('_'), monthsShort: 'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'), monthsParseExact : true, weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split('_'), weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), weekdaysParseExact : true, longDateFormat: { LT: 'H:mm', LTS : 'H:mm:ss', L: 'DD.MM.YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY H:mm', LLLL: 'dddd, D. MMMM YYYY H:mm' }, calendar: { sameDay: '[danas u] LT', nextDay: '[sjutra u] LT', nextWeek: function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; case 3: return '[u] [srijedu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[juče u] LT', lastWeek : function () { var lastWeekDays = [ '[prošle] [nedjelje] [u] LT', '[prošlog] [ponedjeljka] [u] LT', '[prošlog] [utorka] [u] LT', '[prošle] [srijede] [u] LT', '[prošlog] [četvrtka] [u] LT', '[prošlog] [petka] [u] LT', '[prošle] [subote] [u] LT' ]; return lastWeekDays[this.day()]; }, sameElse : 'L' }, relativeTime : { future : 'za %s', past : 'prije %s', s : 'nekoliko sekundi', ss : translator.translate, m : translator.translate, mm : translator.translate, h : translator.translate, hh : translator.translate, d : 'dan', dd : translator.translate, M : 'mjesec', MM : translator.translate, y : 'godinu', yy : translator.translate }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('mi', { months: 'Kohi-tāte_Hui-tanguru_Poutū-te-rangi_Paenga-whāwhā_Haratua_Pipiri_Hōngoingoi_Here-turi-kōkā_Mahuru_Whiringa-ā-nuku_Whiringa-ā-rangi_Hakihea'.split('_'), monthsShort: 'Kohi_Hui_Pou_Pae_Hara_Pipi_Hōngoi_Here_Mahu_Whi-nu_Whi-ra_Haki'.split('_'), monthsRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i, monthsStrictRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i, monthsShortRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,3}/i, monthsShortStrictRegex: /(?:['a-z\u0101\u014D\u016B]+\-?){1,2}/i, weekdays: 'Rātapu_Mane_Tūrei_Wenerei_Tāite_Paraire_Hātarei'.split('_'), weekdaysShort: 'Ta_Ma_Tū_We_Tāi_Pa_Hā'.split('_'), weekdaysMin: 'Ta_Ma_Tū_We_Tāi_Pa_Hā'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY [i] HH:mm', LLLL: 'dddd, D MMMM YYYY [i] HH:mm' }, calendar: { sameDay: '[i teie mahana, i] LT', nextDay: '[apopo i] LT', nextWeek: 'dddd [i] LT', lastDay: '[inanahi i] LT', lastWeek: 'dddd [whakamutunga i] LT', sameElse: 'L' }, relativeTime: { future: 'i roto i %s', past: '%s i mua', s: 'te hēkona ruarua', ss: '%d hēkona', m: 'he meneti', mm: '%d meneti', h: 'te haora', hh: '%d haora', d: 'he ra', dd: '%d ra', M: 'he marama', MM: '%d marama', y: 'he tau', yy: '%d tau' }, dayOfMonthOrdinalParse: /\d{1,2}º/, ordinal: '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('mk', { months : 'јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември'.split('_'), monthsShort : 'јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек'.split('_'), weekdays : 'недела_понеделник_вторник_среда_четврток_петок_сабота'.split('_'), weekdaysShort : 'нед_пон_вто_сре_чет_пет_саб'.split('_'), weekdaysMin : 'нe_пo_вт_ср_че_пе_сa'.split('_'), longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'D.MM.YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY H:mm', LLLL : 'dddd, D MMMM YYYY H:mm' }, calendar : { sameDay : '[Денес во] LT', nextDay : '[Утре во] LT', nextWeek : '[Во] dddd [во] LT', lastDay : '[Вчера во] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: case 6: return '[Изминатата] dddd [во] LT'; case 1: case 2: case 4: case 5: return '[Изминатиот] dddd [во] LT'; } }, sameElse : 'L' }, relativeTime : { future : 'после %s', past : 'пред %s', s : 'неколку секунди', ss : '%d секунди', m : 'минута', mm : '%d минути', h : 'час', hh : '%d часа', d : 'ден', dd : '%d дена', M : 'месец', MM : '%d месеци', y : 'година', yy : '%d години' }, dayOfMonthOrdinalParse: /\d{1,2}-(ев|ен|ти|ви|ри|ми)/, ordinal : function (number) { var lastDigit = number % 10, last2Digits = number % 100; if (number === 0) { return number + '-ев'; } else if (last2Digits === 0) { return number + '-ен'; } else if (last2Digits > 10 && last2Digits < 20) { return number + '-ти'; } else if (lastDigit === 1) { return number + '-ви'; } else if (lastDigit === 2) { return number + '-ри'; } else if (lastDigit === 7 || lastDigit === 8) { return number + '-ми'; } else { return number + '-ти'; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('ml', { months : 'ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ'.split('_'), monthsShort : 'ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.'.split('_'), monthsParseExact : true, weekdays : 'ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച'.split('_'), weekdaysShort : 'ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി'.split('_'), weekdaysMin : 'ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ'.split('_'), longDateFormat : { LT : 'A h:mm -നു', LTS : 'A h:mm:ss -നു', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY, A h:mm -നു', LLLL : 'dddd, D MMMM YYYY, A h:mm -നു' }, calendar : { sameDay : '[ഇന്ന്] LT', nextDay : '[നാളെ] LT', nextWeek : 'dddd, LT', lastDay : '[ഇന്നലെ] LT', lastWeek : '[കഴിഞ്ഞ] dddd, LT', sameElse : 'L' }, relativeTime : { future : '%s കഴിഞ്ഞ്', past : '%s മുൻപ്', s : 'അൽപ നിമിഷങ്ങൾ', ss : '%d സെക്കൻഡ്', m : 'ഒരു മിനിറ്റ്', mm : '%d മിനിറ്റ്', h : 'ഒരു മണിക്കൂർ', hh : '%d മണിക്കൂർ', d : 'ഒരു ദിവസം', dd : '%d ദിവസം', M : 'ഒരു മാസം', MM : '%d മാസം', y : 'ഒരു വർഷം', yy : '%d വർഷം' }, meridiemParse: /രാത്രി|രാവിലെ|ഉച്ച കഴിഞ്ഞ്|വൈകുന്നേരം|രാത്രി/i, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if ((meridiem === 'രാത്രി' && hour >= 4) || meridiem === 'ഉച്ച കഴിഞ്ഞ്' || meridiem === 'വൈകുന്നേരം') { return hour + 12; } else { return hour; } }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return 'രാത്രി'; } else if (hour < 12) { return 'രാവിലെ'; } else if (hour < 17) { return 'ഉച്ച കഴിഞ്ഞ്'; } else if (hour < 20) { return 'വൈകുന്നേരം'; } else { return 'രാത്രി'; } } }); //! moment.js locale configuration var symbolMap$9 = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap$8 = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; function relativeTimeMr(number, withoutSuffix, string, isFuture) { var output = ''; if (withoutSuffix) { switch (string) { case 's': output = 'काही सेकंद'; break; case 'ss': output = '%d सेकंद'; break; case 'm': output = 'एक मिनिट'; break; case 'mm': output = '%d मिनिटे'; break; case 'h': output = 'एक तास'; break; case 'hh': output = '%d तास'; break; case 'd': output = 'एक दिवस'; break; case 'dd': output = '%d दिवस'; break; case 'M': output = 'एक महिना'; break; case 'MM': output = '%d महिने'; break; case 'y': output = 'एक वर्ष'; break; case 'yy': output = '%d वर्षे'; break; } } else { switch (string) { case 's': output = 'काही सेकंदां'; break; case 'ss': output = '%d सेकंदां'; break; case 'm': output = 'एका मिनिटा'; break; case 'mm': output = '%d मिनिटां'; break; case 'h': output = 'एका तासा'; break; case 'hh': output = '%d तासां'; break; case 'd': output = 'एका दिवसा'; break; case 'dd': output = '%d दिवसां'; break; case 'M': output = 'एका महिन्या'; break; case 'MM': output = '%d महिन्यां'; break; case 'y': output = 'एका वर्षा'; break; case 'yy': output = '%d वर्षां'; break; } } return output.replace(/%d/i, number); } moment.defineLocale('mr', { months : 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split('_'), monthsShort: 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split('_'), monthsParseExact : true, weekdays : 'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'), weekdaysShort : 'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split('_'), weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split('_'), longDateFormat : { LT : 'A h:mm वाजता', LTS : 'A h:mm:ss वाजता', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY, A h:mm वाजता', LLLL : 'dddd, D MMMM YYYY, A h:mm वाजता' }, calendar : { sameDay : '[आज] LT', nextDay : '[उद्या] LT', nextWeek : 'dddd, LT', lastDay : '[काल] LT', lastWeek: '[मागील] dddd, LT', sameElse : 'L' }, relativeTime : { future: '%sमध्ये', past: '%sपूर्वी', s: relativeTimeMr, ss: relativeTimeMr, m: relativeTimeMr, mm: relativeTimeMr, h: relativeTimeMr, hh: relativeTimeMr, d: relativeTimeMr, dd: relativeTimeMr, M: relativeTimeMr, MM: relativeTimeMr, y: relativeTimeMr, yy: relativeTimeMr }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap$8[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap$9[match]; }); }, meridiemParse: /रात्री|सकाळी|दुपारी|सायंकाळी/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'रात्री') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'सकाळी') { return hour; } else if (meridiem === 'दुपारी') { return hour >= 10 ? hour : hour + 12; } else if (meridiem === 'सायंकाळी') { return hour + 12; } }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return 'रात्री'; } else if (hour < 10) { return 'सकाळी'; } else if (hour < 17) { return 'दुपारी'; } else if (hour < 20) { return 'सायंकाळी'; } else { return 'रात्री'; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('ms-my', { months : 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'), monthsShort : 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'), weekdays : 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'), weekdaysShort : 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'), weekdaysMin : 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'), longDateFormat : { LT : 'HH.mm', LTS : 'HH.mm.ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY [pukul] HH.mm', LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm' }, meridiemParse: /pagi|tengahari|petang|malam/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'pagi') { return hour; } else if (meridiem === 'tengahari') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === 'petang' || meridiem === 'malam') { return hour + 12; } }, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'tengahari'; } else if (hours < 19) { return 'petang'; } else { return 'malam'; } }, calendar : { sameDay : '[Hari ini pukul] LT', nextDay : '[Esok pukul] LT', nextWeek : 'dddd [pukul] LT', lastDay : '[Kelmarin pukul] LT', lastWeek : 'dddd [lepas pukul] LT', sameElse : 'L' }, relativeTime : { future : 'dalam %s', past : '%s yang lepas', s : 'beberapa saat', ss : '%d saat', m : 'seminit', mm : '%d minit', h : 'sejam', hh : '%d jam', d : 'sehari', dd : '%d hari', M : 'sebulan', MM : '%d bulan', y : 'setahun', yy : '%d tahun' }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('ms', { months : 'Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember'.split('_'), monthsShort : 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis'.split('_'), weekdays : 'Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu'.split('_'), weekdaysShort : 'Ahd_Isn_Sel_Rab_Kha_Jum_Sab'.split('_'), weekdaysMin : 'Ah_Is_Sl_Rb_Km_Jm_Sb'.split('_'), longDateFormat : { LT : 'HH.mm', LTS : 'HH.mm.ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY [pukul] HH.mm', LLLL : 'dddd, D MMMM YYYY [pukul] HH.mm' }, meridiemParse: /pagi|tengahari|petang|malam/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'pagi') { return hour; } else if (meridiem === 'tengahari') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === 'petang' || meridiem === 'malam') { return hour + 12; } }, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'tengahari'; } else if (hours < 19) { return 'petang'; } else { return 'malam'; } }, calendar : { sameDay : '[Hari ini pukul] LT', nextDay : '[Esok pukul] LT', nextWeek : 'dddd [pukul] LT', lastDay : '[Kelmarin pukul] LT', lastWeek : 'dddd [lepas pukul] LT', sameElse : 'L' }, relativeTime : { future : 'dalam %s', past : '%s yang lepas', s : 'beberapa saat', ss : '%d saat', m : 'seminit', mm : '%d minit', h : 'sejam', hh : '%d jam', d : 'sehari', dd : '%d hari', M : 'sebulan', MM : '%d bulan', y : 'setahun', yy : '%d tahun' }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('mt', { months : 'Jannar_Frar_Marzu_April_Mejju_Ġunju_Lulju_Awwissu_Settembru_Ottubru_Novembru_Diċembru'.split('_'), monthsShort : 'Jan_Fra_Mar_Apr_Mej_Ġun_Lul_Aww_Set_Ott_Nov_Diċ'.split('_'), weekdays : 'Il-Ħadd_It-Tnejn_It-Tlieta_L-Erbgħa_Il-Ħamis_Il-Ġimgħa_Is-Sibt'.split('_'), weekdaysShort : 'Ħad_Tne_Tli_Erb_Ħam_Ġim_Sib'.split('_'), weekdaysMin : 'Ħa_Tn_Tl_Er_Ħa_Ġi_Si'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay : '[Illum fil-]LT', nextDay : '[Għada fil-]LT', nextWeek : 'dddd [fil-]LT', lastDay : '[Il-bieraħ fil-]LT', lastWeek : 'dddd [li għadda] [fil-]LT', sameElse : 'L' }, relativeTime : { future : 'f’ %s', past : '%s ilu', s : 'ftit sekondi', ss : '%d sekondi', m : 'minuta', mm : '%d minuti', h : 'siegħa', hh : '%d siegħat', d : 'ġurnata', dd : '%d ġranet', M : 'xahar', MM : '%d xhur', y : 'sena', yy : '%d sni' }, dayOfMonthOrdinalParse : /\d{1,2}º/, ordinal: '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var symbolMap$10 = { '1': '၁', '2': '၂', '3': '၃', '4': '၄', '5': '၅', '6': '၆', '7': '၇', '8': '၈', '9': '၉', '0': '၀' }, numberMap$9 = { '၁': '1', '၂': '2', '၃': '3', '၄': '4', '၅': '5', '၆': '6', '၇': '7', '၈': '8', '၉': '9', '၀': '0' }; moment.defineLocale('my', { months: 'ဇန်နဝါရီ_ဖေဖော်ဝါရီ_မတ်_ဧပြီ_မေ_ဇွန်_ဇူလိုင်_သြဂုတ်_စက်တင်ဘာ_အောက်တိုဘာ_နိုဝင်ဘာ_ဒီဇင်ဘာ'.split('_'), monthsShort: 'ဇန်_ဖေ_မတ်_ပြီ_မေ_ဇွန်_လိုင်_သြ_စက်_အောက်_နို_ဒီ'.split('_'), weekdays: 'တနင်္ဂနွေ_တနင်္လာ_အင်္ဂါ_ဗုဒ္ဓဟူး_ကြာသပတေး_သောကြာ_စနေ'.split('_'), weekdaysShort: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'), weekdaysMin: 'နွေ_လာ_ဂါ_ဟူး_ကြာ_သော_နေ'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd D MMMM YYYY HH:mm' }, calendar: { sameDay: '[ယနေ.] LT [မှာ]', nextDay: '[မနက်ဖြန်] LT [မှာ]', nextWeek: 'dddd LT [မှာ]', lastDay: '[မနေ.က] LT [မှာ]', lastWeek: '[ပြီးခဲ့သော] dddd LT [မှာ]', sameElse: 'L' }, relativeTime: { future: 'လာမည့် %s မှာ', past: 'လွန်ခဲ့သော %s က', s: 'စက္ကန်.အနည်းငယ်', ss : '%d စက္ကန့်', m: 'တစ်မိနစ်', mm: '%d မိနစ်', h: 'တစ်နာရီ', hh: '%d နာရီ', d: 'တစ်ရက်', dd: '%d ရက်', M: 'တစ်လ', MM: '%d လ', y: 'တစ်နှစ်', yy: '%d နှစ်' }, preparse: function (string) { return string.replace(/[၁၂၃၄၅၆၇၈၉၀]/g, function (match) { return numberMap$9[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap$10[match]; }); }, week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('nb', { months : 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'), monthsShort : 'jan._feb._mars_april_mai_juni_juli_aug._sep._okt._nov._des.'.split('_'), monthsParseExact : true, weekdays : 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'), weekdaysShort : 'sø._ma._ti._on._to._fr._lø.'.split('_'), weekdaysMin : 'sø_ma_ti_on_to_fr_lø'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D. MMMM YYYY', LLL : 'D. MMMM YYYY [kl.] HH:mm', LLLL : 'dddd D. MMMM YYYY [kl.] HH:mm' }, calendar : { sameDay: '[i dag kl.] LT', nextDay: '[i morgen kl.] LT', nextWeek: 'dddd [kl.] LT', lastDay: '[i går kl.] LT', lastWeek: '[forrige] dddd [kl.] LT', sameElse: 'L' }, relativeTime : { future : 'om %s', past : '%s siden', s : 'noen sekunder', ss : '%d sekunder', m : 'ett minutt', mm : '%d minutter', h : 'en time', hh : '%d timer', d : 'en dag', dd : '%d dager', M : 'en måned', MM : '%d måneder', y : 'ett år', yy : '%d år' }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var symbolMap$11 = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap$10 = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; moment.defineLocale('ne', { months : 'जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर'.split('_'), monthsShort : 'जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.'.split('_'), monthsParseExact : true, weekdays : 'आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार'.split('_'), weekdaysShort : 'आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.'.split('_'), weekdaysMin : 'आ._सो._मं._बु._बि._शु._श.'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'Aको h:mm बजे', LTS : 'Aको h:mm:ss बजे', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY, Aको h:mm बजे', LLLL : 'dddd, D MMMM YYYY, Aको h:mm बजे' }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap$10[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap$11[match]; }); }, meridiemParse: /राति|बिहान|दिउँसो|साँझ/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'राति') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'बिहान') { return hour; } else if (meridiem === 'दिउँसो') { return hour >= 10 ? hour : hour + 12; } else if (meridiem === 'साँझ') { return hour + 12; } }, meridiem : function (hour, minute, isLower) { if (hour < 3) { return 'राति'; } else if (hour < 12) { return 'बिहान'; } else if (hour < 16) { return 'दिउँसो'; } else if (hour < 20) { return 'साँझ'; } else { return 'राति'; } }, calendar : { sameDay : '[आज] LT', nextDay : '[भोलि] LT', nextWeek : '[आउँदो] dddd[,] LT', lastDay : '[हिजो] LT', lastWeek : '[गएको] dddd[,] LT', sameElse : 'L' }, relativeTime : { future : '%sमा', past : '%s अगाडि', s : 'केही क्षण', ss : '%d सेकेण्ड', m : 'एक मिनेट', mm : '%d मिनेट', h : 'एक घण्टा', hh : '%d घण्टा', d : 'एक दिन', dd : '%d दिन', M : 'एक महिना', MM : '%d महिना', y : 'एक बर्ष', yy : '%d बर्ष' }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration var monthsShortWithDots$1 = 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'), monthsShortWithoutDots$1 = 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_'); var monthsParse$2 = [/^jan/i, /^feb/i, /^maart|mrt.?$/i, /^apr/i, /^mei$/i, /^jun[i.]?$/i, /^jul[i.]?$/i, /^aug/i, /^sep/i, /^okt/i, /^nov/i, /^dec/i]; var monthsRegex$2 = /^(januari|februari|maart|april|mei|april|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i; moment.defineLocale('nl-be', { months : 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'), monthsShort : function (m, format) { if (!m) { return monthsShortWithDots$1; } else if (/-MMM-/.test(format)) { return monthsShortWithoutDots$1[m.month()]; } else { return monthsShortWithDots$1[m.month()]; } }, monthsRegex: monthsRegex$2, monthsShortRegex: monthsRegex$2, monthsStrictRegex: /^(januari|februari|maart|mei|ju[nl]i|april|augustus|september|oktober|november|december)/i, monthsShortStrictRegex: /^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i, monthsParse : monthsParse$2, longMonthsParse : monthsParse$2, shortMonthsParse : monthsParse$2, weekdays : 'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'), weekdaysShort : 'zo._ma._di._wo._do._vr._za.'.split('_'), weekdaysMin : 'zo_ma_di_wo_do_vr_za'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { sameDay: '[vandaag om] LT', nextDay: '[morgen om] LT', nextWeek: 'dddd [om] LT', lastDay: '[gisteren om] LT', lastWeek: '[afgelopen] dddd [om] LT', sameElse: 'L' }, relativeTime : { future : 'over %s', past : '%s geleden', s : 'een paar seconden', ss : '%d seconden', m : 'één minuut', mm : '%d minuten', h : 'één uur', hh : '%d uur', d : 'één dag', dd : '%d dagen', M : 'één maand', MM : '%d maanden', y : 'één jaar', yy : '%d jaar' }, dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, ordinal : function (number) { return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var monthsShortWithDots$2 = 'jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.'.split('_'), monthsShortWithoutDots$2 = 'jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec'.split('_'); var monthsParse$3 = [/^jan/i, /^feb/i, /^maart|mrt.?$/i, /^apr/i, /^mei$/i, /^jun[i.]?$/i, /^jul[i.]?$/i, /^aug/i, /^sep/i, /^okt/i, /^nov/i, /^dec/i]; var monthsRegex$3 = /^(januari|februari|maart|april|mei|april|ju[nl]i|augustus|september|oktober|november|december|jan\.?|feb\.?|mrt\.?|apr\.?|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i; moment.defineLocale('nl', { months : 'januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december'.split('_'), monthsShort : function (m, format) { if (!m) { return monthsShortWithDots$2; } else if (/-MMM-/.test(format)) { return monthsShortWithoutDots$2[m.month()]; } else { return monthsShortWithDots$2[m.month()]; } }, monthsRegex: monthsRegex$3, monthsShortRegex: monthsRegex$3, monthsStrictRegex: /^(januari|februari|maart|mei|ju[nl]i|april|augustus|september|oktober|november|december)/i, monthsShortStrictRegex: /^(jan\.?|feb\.?|mrt\.?|apr\.?|mei|ju[nl]\.?|aug\.?|sep\.?|okt\.?|nov\.?|dec\.?)/i, monthsParse : monthsParse$3, longMonthsParse : monthsParse$3, shortMonthsParse : monthsParse$3, weekdays : 'zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag'.split('_'), weekdaysShort : 'zo._ma._di._wo._do._vr._za.'.split('_'), weekdaysMin : 'zo_ma_di_wo_do_vr_za'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD-MM-YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { sameDay: '[vandaag om] LT', nextDay: '[morgen om] LT', nextWeek: 'dddd [om] LT', lastDay: '[gisteren om] LT', lastWeek: '[afgelopen] dddd [om] LT', sameElse: 'L' }, relativeTime : { future : 'over %s', past : '%s geleden', s : 'een paar seconden', ss : '%d seconden', m : 'één minuut', mm : '%d minuten', h : 'één uur', hh : '%d uur', d : 'één dag', dd : '%d dagen', M : 'één maand', MM : '%d maanden', y : 'één jaar', yy : '%d jaar' }, dayOfMonthOrdinalParse: /\d{1,2}(ste|de)/, ordinal : function (number) { return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('nn', { months : 'januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember'.split('_'), monthsShort : 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'), weekdays : 'sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag'.split('_'), weekdaysShort : 'sun_mån_tys_ons_tor_fre_lau'.split('_'), weekdaysMin : 'su_må_ty_on_to_fr_lø'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D. MMMM YYYY', LLL : 'D. MMMM YYYY [kl.] H:mm', LLLL : 'dddd D. MMMM YYYY [kl.] HH:mm' }, calendar : { sameDay: '[I dag klokka] LT', nextDay: '[I morgon klokka] LT', nextWeek: 'dddd [klokka] LT', lastDay: '[I går klokka] LT', lastWeek: '[Føregåande] dddd [klokka] LT', sameElse: 'L' }, relativeTime : { future : 'om %s', past : '%s sidan', s : 'nokre sekund', ss : '%d sekund', m : 'eit minutt', mm : '%d minutt', h : 'ein time', hh : '%d timar', d : 'ein dag', dd : '%d dagar', M : 'ein månad', MM : '%d månader', y : 'eit år', yy : '%d år' }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var symbolMap$12 = { '1': '੧', '2': '੨', '3': '੩', '4': '੪', '5': '੫', '6': '੬', '7': '੭', '8': '੮', '9': '੯', '0': '੦' }, numberMap$11 = { '੧': '1', '੨': '2', '੩': '3', '੪': '4', '੫': '5', '੬': '6', '੭': '7', '੮': '8', '੯': '9', '੦': '0' }; moment.defineLocale('pa-in', { // There are months name as per Nanakshahi Calender but they are not used as rigidly in modern Punjabi. months : 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'), monthsShort : 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'), weekdays : 'ਐਤਵਾਰ_ਸੋਮਵਾਰ_ਮੰਗਲਵਾਰ_ਬੁਧਵਾਰ_ਵੀਰਵਾਰ_ਸ਼ੁੱਕਰਵਾਰ_ਸ਼ਨੀਚਰਵਾਰ'.split('_'), weekdaysShort : 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), weekdaysMin : 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), longDateFormat : { LT : 'A h:mm ਵਜੇ', LTS : 'A h:mm:ss ਵਜੇ', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY, A h:mm ਵਜੇ', LLLL : 'dddd, D MMMM YYYY, A h:mm ਵਜੇ' }, calendar : { sameDay : '[ਅਜ] LT', nextDay : '[ਕਲ] LT', nextWeek : 'dddd, LT', lastDay : '[ਕਲ] LT', lastWeek : '[ਪਿਛਲੇ] dddd, LT', sameElse : 'L' }, relativeTime : { future : '%s ਵਿੱਚ', past : '%s ਪਿਛਲੇ', s : 'ਕੁਝ ਸਕਿੰਟ', ss : '%d ਸਕਿੰਟ', m : 'ਇਕ ਮਿੰਟ', mm : '%d ਮਿੰਟ', h : 'ਇੱਕ ਘੰਟਾ', hh : '%d ਘੰਟੇ', d : 'ਇੱਕ ਦਿਨ', dd : '%d ਦਿਨ', M : 'ਇੱਕ ਮਹੀਨਾ', MM : '%d ਮਹੀਨੇ', y : 'ਇੱਕ ਸਾਲ', yy : '%d ਸਾਲ' }, preparse: function (string) { return string.replace(/[੧੨੩੪੫੬੭੮੯੦]/g, function (match) { return numberMap$11[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap$12[match]; }); }, // Punjabi notation for meridiems are quite fuzzy in practice. While there exists // a rigid notion of a 'Pahar' it is not used as rigidly in modern Punjabi. meridiemParse: /ਰਾਤ|ਸਵੇਰ|ਦੁਪਹਿਰ|ਸ਼ਾਮ/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'ਰਾਤ') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'ਸਵੇਰ') { return hour; } else if (meridiem === 'ਦੁਪਹਿਰ') { return hour >= 10 ? hour : hour + 12; } else if (meridiem === 'ਸ਼ਾਮ') { return hour + 12; } }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return 'ਰਾਤ'; } else if (hour < 10) { return 'ਸਵੇਰ'; } else if (hour < 17) { return 'ਦੁਪਹਿਰ'; } else if (hour < 20) { return 'ਸ਼ਾਮ'; } else { return 'ਰਾਤ'; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration var monthsNominative = 'styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień'.split('_'), monthsSubjective = 'stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia'.split('_'); function plural$3(n) { return (n % 10 < 5) && (n % 10 > 1) && ((~~(n / 10) % 10) !== 1); } function translate$7(number, withoutSuffix, key) { var result = number + ' '; switch (key) { case 'ss': return result + (plural$3(number) ? 'sekundy' : 'sekund'); case 'm': return withoutSuffix ? 'minuta' : 'minutę'; case 'mm': return result + (plural$3(number) ? 'minuty' : 'minut'); case 'h': return withoutSuffix ? 'godzina' : 'godzinę'; case 'hh': return result + (plural$3(number) ? 'godziny' : 'godzin'); case 'MM': return result + (plural$3(number) ? 'miesiące' : 'miesięcy'); case 'yy': return result + (plural$3(number) ? 'lata' : 'lat'); } } moment.defineLocale('pl', { months : function (momentToFormat, format) { if (!momentToFormat) { return monthsNominative; } else if (format === '') { // Hack: if format empty we know this is used to generate // RegExp by moment. Give then back both valid forms of months // in RegExp ready format. return '(' + monthsSubjective[momentToFormat.month()] + '|' + monthsNominative[momentToFormat.month()] + ')'; } else if (/D MMMM/.test(format)) { return monthsSubjective[momentToFormat.month()]; } else { return monthsNominative[momentToFormat.month()]; } }, monthsShort : 'sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru'.split('_'), weekdays : 'niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota'.split('_'), weekdaysShort : 'ndz_pon_wt_śr_czw_pt_sob'.split('_'), weekdaysMin : 'Nd_Pn_Wt_Śr_Cz_Pt_So'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay: '[Dziś o] LT', nextDay: '[Jutro o] LT', nextWeek: function () { switch (this.day()) { case 0: return '[W niedzielę o] LT'; case 2: return '[We wtorek o] LT'; case 3: return '[W środę o] LT'; case 6: return '[W sobotę o] LT'; default: return '[W] dddd [o] LT'; } }, lastDay: '[Wczoraj o] LT', lastWeek: function () { switch (this.day()) { case 0: return '[W zeszłą niedzielę o] LT'; case 3: return '[W zeszłą środę o] LT'; case 6: return '[W zeszłą sobotę o] LT'; default: return '[W zeszły] dddd [o] LT'; } }, sameElse: 'L' }, relativeTime : { future : 'za %s', past : '%s temu', s : 'kilka sekund', ss : translate$7, m : translate$7, mm : translate$7, h : translate$7, hh : translate$7, d : '1 dzień', dd : '%d dni', M : 'miesiąc', MM : translate$7, y : 'rok', yy : translate$7 }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('pt-br', { months : 'janeiro_fevereiro_março_abril_maio_junho_julho_agosto_setembro_outubro_novembro_dezembro'.split('_'), monthsShort : 'jan_fev_mar_abr_mai_jun_jul_ago_set_out_nov_dez'.split('_'), weekdays : 'Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado'.split('_'), weekdaysShort : 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'), weekdaysMin : 'Do_2ª_3ª_4ª_5ª_6ª_Sá'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D [de] MMMM [de] YYYY', LLL : 'D [de] MMMM [de] YYYY [às] HH:mm', LLLL : 'dddd, D [de] MMMM [de] YYYY [às] HH:mm' }, calendar : { sameDay: '[Hoje às] LT', nextDay: '[Amanhã às] LT', nextWeek: 'dddd [às] LT', lastDay: '[Ontem às] LT', lastWeek: function () { return (this.day() === 0 || this.day() === 6) ? '[Último] dddd [às] LT' : // Saturday + Sunday '[Última] dddd [às] LT'; // Monday - Friday }, sameElse: 'L' }, relativeTime : { future : 'em %s', past : 'há %s', s : 'poucos segundos', ss : '%d segundos', m : 'um minuto', mm : '%d minutos', h : 'uma hora', hh : '%d horas', d : 'um dia', dd : '%d dias', M : 'um mês', MM : '%d meses', y : 'um ano', yy : '%d anos' }, dayOfMonthOrdinalParse: /\d{1,2}º/, ordinal : '%dº' }); //! moment.js locale configuration moment.defineLocale('pt', { months : 'janeiro_fevereiro_março_abril_maio_junho_julho_agosto_setembro_outubro_novembro_dezembro'.split('_'), monthsShort : 'jan_fev_mar_abr_mai_jun_jul_ago_set_out_nov_dez'.split('_'), weekdays : 'Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado'.split('_'), weekdaysShort : 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'), weekdaysMin : 'Do_2ª_3ª_4ª_5ª_6ª_Sá'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D [de] MMMM [de] YYYY', LLL : 'D [de] MMMM [de] YYYY HH:mm', LLLL : 'dddd, D [de] MMMM [de] YYYY HH:mm' }, calendar : { sameDay: '[Hoje às] LT', nextDay: '[Amanhã às] LT', nextWeek: 'dddd [às] LT', lastDay: '[Ontem às] LT', lastWeek: function () { return (this.day() === 0 || this.day() === 6) ? '[Último] dddd [às] LT' : // Saturday + Sunday '[Última] dddd [às] LT'; // Monday - Friday }, sameElse: 'L' }, relativeTime : { future : 'em %s', past : 'há %s', s : 'segundos', ss : '%d segundos', m : 'um minuto', mm : '%d minutos', h : 'uma hora', hh : '%d horas', d : 'um dia', dd : '%d dias', M : 'um mês', MM : '%d meses', y : 'um ano', yy : '%d anos' }, dayOfMonthOrdinalParse: /\d{1,2}º/, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration function relativeTimeWithPlural$2(number, withoutSuffix, key) { var format = { 'ss': 'secunde', 'mm': 'minute', 'hh': 'ore', 'dd': 'zile', 'MM': 'luni', 'yy': 'ani' }, separator = ' '; if (number % 100 >= 20 || (number >= 100 && number % 100 === 0)) { separator = ' de '; } return number + separator + format[key]; } moment.defineLocale('ro', { months : 'ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie'.split('_'), monthsShort : 'ian._febr._mart._apr._mai_iun._iul._aug._sept._oct._nov._dec.'.split('_'), monthsParseExact: true, weekdays : 'duminică_luni_marți_miercuri_joi_vineri_sâmbătă'.split('_'), weekdaysShort : 'Dum_Lun_Mar_Mie_Joi_Vin_Sâm'.split('_'), weekdaysMin : 'Du_Lu_Ma_Mi_Jo_Vi_Sâ'.split('_'), longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'DD.MM.YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY H:mm', LLLL : 'dddd, D MMMM YYYY H:mm' }, calendar : { sameDay: '[azi la] LT', nextDay: '[mâine la] LT', nextWeek: 'dddd [la] LT', lastDay: '[ieri la] LT', lastWeek: '[fosta] dddd [la] LT', sameElse: 'L' }, relativeTime : { future : 'peste %s', past : '%s în urmă', s : 'câteva secunde', ss : relativeTimeWithPlural$2, m : 'un minut', mm : relativeTimeWithPlural$2, h : 'o oră', hh : relativeTimeWithPlural$2, d : 'o zi', dd : relativeTimeWithPlural$2, M : 'o lună', MM : relativeTimeWithPlural$2, y : 'un an', yy : relativeTimeWithPlural$2 }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration function plural$4(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural$3(number, withoutSuffix, key) { var format = { 'ss': withoutSuffix ? 'секунда_секунды_секунд' : 'секунду_секунды_секунд', 'mm': withoutSuffix ? 'минута_минуты_минут' : 'минуту_минуты_минут', 'hh': 'час_часа_часов', 'dd': 'день_дня_дней', 'MM': 'месяц_месяца_месяцев', 'yy': 'год_года_лет' }; if (key === 'm') { return withoutSuffix ? 'минута' : 'минуту'; } else { return number + ' ' + plural$4(format[key], +number); } } var monthsParse$4 = [/^янв/i, /^фев/i, /^мар/i, /^апр/i, /^ма[йя]/i, /^июн/i, /^июл/i, /^авг/i, /^сен/i, /^окт/i, /^ноя/i, /^дек/i]; // http://new.gramota.ru/spravka/rules/139-prop : § 103 // Сокращения месяцев: http://new.gramota.ru/spravka/buro/search-answer?s=242637 // CLDR data: http://www.unicode.org/cldr/charts/28/summary/ru.html#1753 moment.defineLocale('ru', { months : { format: 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_'), standalone: 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_') }, monthsShort : { // по CLDR именно "июл." и "июн.", но какой смысл менять букву на точку ? format: 'янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.'.split('_'), standalone: 'янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.'.split('_') }, weekdays : { standalone: 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'), format: 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_'), isFormat: /\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/ }, weekdaysShort : 'вс_пн_вт_ср_чт_пт_сб'.split('_'), weekdaysMin : 'вс_пн_вт_ср_чт_пт_сб'.split('_'), monthsParse : monthsParse$4, longMonthsParse : monthsParse$4, shortMonthsParse : monthsParse$4, // полные названия с падежами, по три буквы, для некоторых, по 4 буквы, сокращения с точкой и без точки monthsRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, // копия предыдущего monthsShortRegex: /^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i, // полные названия с падежами monthsStrictRegex: /^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i, // Выражение, которое соотвествует только сокращённым формам monthsShortStrictRegex: /^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i, longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'DD.MM.YYYY', LL : 'D MMMM YYYY г.', LLL : 'D MMMM YYYY г., H:mm', LLLL : 'dddd, D MMMM YYYY г., H:mm' }, calendar : { sameDay: '[Сегодня в] LT', nextDay: '[Завтра в] LT', lastDay: '[Вчера в] LT', nextWeek: function (now) { if (now.week() !== this.week()) { switch (this.day()) { case 0: return '[В следующее] dddd [в] LT'; case 1: case 2: case 4: return '[В следующий] dddd [в] LT'; case 3: case 5: case 6: return '[В следующую] dddd [в] LT'; } } else { if (this.day() === 2) { return '[Во] dddd [в] LT'; } else { return '[В] dddd [в] LT'; } } }, lastWeek: function (now) { if (now.week() !== this.week()) { switch (this.day()) { case 0: return '[В прошлое] dddd [в] LT'; case 1: case 2: case 4: return '[В прошлый] dddd [в] LT'; case 3: case 5: case 6: return '[В прошлую] dddd [в] LT'; } } else { if (this.day() === 2) { return '[Во] dddd [в] LT'; } else { return '[В] dddd [в] LT'; } } }, sameElse: 'L' }, relativeTime : { future : 'через %s', past : '%s назад', s : 'несколько секунд', ss : relativeTimeWithPlural$3, m : relativeTimeWithPlural$3, mm : relativeTimeWithPlural$3, h : 'час', hh : relativeTimeWithPlural$3, d : 'день', dd : relativeTimeWithPlural$3, M : 'месяц', MM : relativeTimeWithPlural$3, y : 'год', yy : relativeTimeWithPlural$3 }, meridiemParse: /ночи|утра|дня|вечера/i, isPM : function (input) { return /^(дня|вечера)$/.test(input); }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return 'ночи'; } else if (hour < 12) { return 'утра'; } else if (hour < 17) { return 'дня'; } else { return 'вечера'; } }, dayOfMonthOrdinalParse: /\d{1,2}-(й|го|я)/, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': return number + '-й'; case 'D': return number + '-го'; case 'w': case 'W': return number + '-я'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var months$5 = [ 'جنوري', 'فيبروري', 'مارچ', 'اپريل', 'مئي', 'جون', 'جولاءِ', 'آگسٽ', 'سيپٽمبر', 'آڪٽوبر', 'نومبر', 'ڊسمبر' ]; var days = [ 'آچر', 'سومر', 'اڱارو', 'اربع', 'خميس', 'جمع', 'ڇنڇر' ]; moment.defineLocale('sd', { months : months$5, monthsShort : months$5, weekdays : days, weekdaysShort : days, weekdaysMin : days, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd، D MMMM YYYY HH:mm' }, meridiemParse: /صبح|شام/, isPM : function (input) { return 'شام' === input; }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return 'صبح'; } return 'شام'; }, calendar : { sameDay : '[اڄ] LT', nextDay : '[سڀاڻي] LT', nextWeek : 'dddd [اڳين هفتي تي] LT', lastDay : '[ڪالهه] LT', lastWeek : '[گزريل هفتي] dddd [تي] LT', sameElse : 'L' }, relativeTime : { future : '%s پوء', past : '%s اڳ', s : 'چند سيڪنڊ', ss : '%d سيڪنڊ', m : 'هڪ منٽ', mm : '%d منٽ', h : 'هڪ ڪلاڪ', hh : '%d ڪلاڪ', d : 'هڪ ڏينهن', dd : '%d ڏينهن', M : 'هڪ مهينو', MM : '%d مهينا', y : 'هڪ سال', yy : '%d سال' }, preparse: function (string) { return string.replace(/،/g, ','); }, postformat: function (string) { return string.replace(/,/g, '،'); }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('se', { months : 'ođđajagemánnu_guovvamánnu_njukčamánnu_cuoŋománnu_miessemánnu_geassemánnu_suoidnemánnu_borgemánnu_čakčamánnu_golggotmánnu_skábmamánnu_juovlamánnu'.split('_'), monthsShort : 'ođđj_guov_njuk_cuo_mies_geas_suoi_borg_čakč_golg_skáb_juov'.split('_'), weekdays : 'sotnabeaivi_vuossárga_maŋŋebárga_gaskavahkku_duorastat_bearjadat_lávvardat'.split('_'), weekdaysShort : 'sotn_vuos_maŋ_gask_duor_bear_láv'.split('_'), weekdaysMin : 's_v_m_g_d_b_L'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'MMMM D. [b.] YYYY', LLL : 'MMMM D. [b.] YYYY [ti.] HH:mm', LLLL : 'dddd, MMMM D. [b.] YYYY [ti.] HH:mm' }, calendar : { sameDay: '[otne ti] LT', nextDay: '[ihttin ti] LT', nextWeek: 'dddd [ti] LT', lastDay: '[ikte ti] LT', lastWeek: '[ovddit] dddd [ti] LT', sameElse: 'L' }, relativeTime : { future : '%s geažes', past : 'maŋit %s', s : 'moadde sekunddat', ss: '%d sekunddat', m : 'okta minuhta', mm : '%d minuhtat', h : 'okta diimmu', hh : '%d diimmut', d : 'okta beaivi', dd : '%d beaivvit', M : 'okta mánnu', MM : '%d mánut', y : 'okta jahki', yy : '%d jagit' }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration /*jshint -W100*/ moment.defineLocale('si', { months : 'ජනවාරි_පෙබරවාරි_මාර්තු_අප්‍රේල්_මැයි_ජූනි_ජූලි_අගෝස්තු_සැප්තැම්බර්_ඔක්තෝබර්_නොවැම්බර්_දෙසැම්බර්'.split('_'), monthsShort : 'ජන_පෙබ_මාර්_අප්_මැයි_ජූනි_ජූලි_අගෝ_සැප්_ඔක්_නොවැ_දෙසැ'.split('_'), weekdays : 'ඉරිදා_සඳුදා_අඟහරුවාදා_බදාදා_බ්‍රහස්පතින්දා_සිකුරාදා_සෙනසුරාදා'.split('_'), weekdaysShort : 'ඉරි_සඳු_අඟ_බදා_බ්‍රහ_සිකු_සෙන'.split('_'), weekdaysMin : 'ඉ_ස_අ_බ_බ්‍ර_සි_සෙ'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'a h:mm', LTS : 'a h:mm:ss', L : 'YYYY/MM/DD', LL : 'YYYY MMMM D', LLL : 'YYYY MMMM D, a h:mm', LLLL : 'YYYY MMMM D [වැනි] dddd, a h:mm:ss' }, calendar : { sameDay : '[අද] LT[ට]', nextDay : '[හෙට] LT[ට]', nextWeek : 'dddd LT[ට]', lastDay : '[ඊයේ] LT[ට]', lastWeek : '[පසුගිය] dddd LT[ට]', sameElse : 'L' }, relativeTime : { future : '%sකින්', past : '%sකට පෙර', s : 'තත්පර කිහිපය', ss : 'තත්පර %d', m : 'මිනිත්තුව', mm : 'මිනිත්තු %d', h : 'පැය', hh : 'පැය %d', d : 'දිනය', dd : 'දින %d', M : 'මාසය', MM : 'මාස %d', y : 'වසර', yy : 'වසර %d' }, dayOfMonthOrdinalParse: /\d{1,2} වැනි/, ordinal : function (number) { return number + ' වැනි'; }, meridiemParse : /පෙර වරු|පස් වරු|පෙ.ව|ප.ව./, isPM : function (input) { return input === 'ප.ව.' || input === 'පස් වරු'; }, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'ප.ව.' : 'පස් වරු'; } else { return isLower ? 'පෙ.ව.' : 'පෙර වරු'; } } }); //! moment.js locale configuration var months$6 = 'január_február_marec_apríl_máj_jún_júl_august_september_október_november_december'.split('_'), monthsShort$5 = 'jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec'.split('_'); function plural$5(n) { return (n > 1) && (n < 5); } function translate$8(number, withoutSuffix, key, isFuture) { var result = number + ' '; switch (key) { case 's': // a few seconds / in a few seconds / a few seconds ago return (withoutSuffix || isFuture) ? 'pár sekúnd' : 'pár sekundami'; case 'ss': // 9 seconds / in 9 seconds / 9 seconds ago if (withoutSuffix || isFuture) { return result + (plural$5(number) ? 'sekundy' : 'sekúnd'); } else { return result + 'sekundami'; } break; case 'm': // a minute / in a minute / a minute ago return withoutSuffix ? 'minúta' : (isFuture ? 'minútu' : 'minútou'); case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago if (withoutSuffix || isFuture) { return result + (plural$5(number) ? 'minúty' : 'minút'); } else { return result + 'minútami'; } break; case 'h': // an hour / in an hour / an hour ago return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); case 'hh': // 9 hours / in 9 hours / 9 hours ago if (withoutSuffix || isFuture) { return result + (plural$5(number) ? 'hodiny' : 'hodín'); } else { return result + 'hodinami'; } break; case 'd': // a day / in a day / a day ago return (withoutSuffix || isFuture) ? 'deň' : 'dňom'; case 'dd': // 9 days / in 9 days / 9 days ago if (withoutSuffix || isFuture) { return result + (plural$5(number) ? 'dni' : 'dní'); } else { return result + 'dňami'; } break; case 'M': // a month / in a month / a month ago return (withoutSuffix || isFuture) ? 'mesiac' : 'mesiacom'; case 'MM': // 9 months / in 9 months / 9 months ago if (withoutSuffix || isFuture) { return result + (plural$5(number) ? 'mesiace' : 'mesiacov'); } else { return result + 'mesiacmi'; } break; case 'y': // a year / in a year / a year ago return (withoutSuffix || isFuture) ? 'rok' : 'rokom'; case 'yy': // 9 years / in 9 years / 9 years ago if (withoutSuffix || isFuture) { return result + (plural$5(number) ? 'roky' : 'rokov'); } else { return result + 'rokmi'; } break; } } moment.defineLocale('sk', { months : months$6, monthsShort : monthsShort$5, weekdays : 'nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota'.split('_'), weekdaysShort : 'ne_po_ut_st_št_pi_so'.split('_'), weekdaysMin : 'ne_po_ut_st_št_pi_so'.split('_'), longDateFormat : { LT: 'H:mm', LTS : 'H:mm:ss', L : 'DD.MM.YYYY', LL : 'D. MMMM YYYY', LLL : 'D. MMMM YYYY H:mm', LLLL : 'dddd D. MMMM YYYY H:mm' }, calendar : { sameDay: '[dnes o] LT', nextDay: '[zajtra o] LT', nextWeek: function () { switch (this.day()) { case 0: return '[v nedeľu o] LT'; case 1: case 2: return '[v] dddd [o] LT'; case 3: return '[v stredu o] LT'; case 4: return '[vo štvrtok o] LT'; case 5: return '[v piatok o] LT'; case 6: return '[v sobotu o] LT'; } }, lastDay: '[včera o] LT', lastWeek: function () { switch (this.day()) { case 0: return '[minulú nedeľu o] LT'; case 1: case 2: return '[minulý] dddd [o] LT'; case 3: return '[minulú stredu o] LT'; case 4: case 5: return '[minulý] dddd [o] LT'; case 6: return '[minulú sobotu o] LT'; } }, sameElse: 'L' }, relativeTime : { future : 'za %s', past : 'pred %s', s : translate$8, ss : translate$8, m : translate$8, mm : translate$8, h : translate$8, hh : translate$8, d : translate$8, dd : translate$8, M : translate$8, MM : translate$8, y : translate$8, yy : translate$8 }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration function processRelativeTime$6(number, withoutSuffix, key, isFuture) { var result = number + ' '; switch (key) { case 's': return withoutSuffix || isFuture ? 'nekaj sekund' : 'nekaj sekundami'; case 'ss': if (number === 1) { result += withoutSuffix ? 'sekundo' : 'sekundi'; } else if (number === 2) { result += withoutSuffix || isFuture ? 'sekundi' : 'sekundah'; } else if (number < 5) { result += withoutSuffix || isFuture ? 'sekunde' : 'sekundah'; } else { result += withoutSuffix || isFuture ? 'sekund' : 'sekund'; } return result; case 'm': return withoutSuffix ? 'ena minuta' : 'eno minuto'; case 'mm': if (number === 1) { result += withoutSuffix ? 'minuta' : 'minuto'; } else if (number === 2) { result += withoutSuffix || isFuture ? 'minuti' : 'minutama'; } else if (number < 5) { result += withoutSuffix || isFuture ? 'minute' : 'minutami'; } else { result += withoutSuffix || isFuture ? 'minut' : 'minutami'; } return result; case 'h': return withoutSuffix ? 'ena ura' : 'eno uro'; case 'hh': if (number === 1) { result += withoutSuffix ? 'ura' : 'uro'; } else if (number === 2) { result += withoutSuffix || isFuture ? 'uri' : 'urama'; } else if (number < 5) { result += withoutSuffix || isFuture ? 'ure' : 'urami'; } else { result += withoutSuffix || isFuture ? 'ur' : 'urami'; } return result; case 'd': return withoutSuffix || isFuture ? 'en dan' : 'enim dnem'; case 'dd': if (number === 1) { result += withoutSuffix || isFuture ? 'dan' : 'dnem'; } else if (number === 2) { result += withoutSuffix || isFuture ? 'dni' : 'dnevoma'; } else { result += withoutSuffix || isFuture ? 'dni' : 'dnevi'; } return result; case 'M': return withoutSuffix || isFuture ? 'en mesec' : 'enim mesecem'; case 'MM': if (number === 1) { result += withoutSuffix || isFuture ? 'mesec' : 'mesecem'; } else if (number === 2) { result += withoutSuffix || isFuture ? 'meseca' : 'mesecema'; } else if (number < 5) { result += withoutSuffix || isFuture ? 'mesece' : 'meseci'; } else { result += withoutSuffix || isFuture ? 'mesecev' : 'meseci'; } return result; case 'y': return withoutSuffix || isFuture ? 'eno leto' : 'enim letom'; case 'yy': if (number === 1) { result += withoutSuffix || isFuture ? 'leto' : 'letom'; } else if (number === 2) { result += withoutSuffix || isFuture ? 'leti' : 'letoma'; } else if (number < 5) { result += withoutSuffix || isFuture ? 'leta' : 'leti'; } else { result += withoutSuffix || isFuture ? 'let' : 'leti'; } return result; } } moment.defineLocale('sl', { months : 'januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december'.split('_'), monthsShort : 'jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.'.split('_'), monthsParseExact: true, weekdays : 'nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota'.split('_'), weekdaysShort : 'ned._pon._tor._sre._čet._pet._sob.'.split('_'), weekdaysMin : 'ne_po_to_sr_če_pe_so'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'DD.MM.YYYY', LL : 'D. MMMM YYYY', LLL : 'D. MMMM YYYY H:mm', LLLL : 'dddd, D. MMMM YYYY H:mm' }, calendar : { sameDay : '[danes ob] LT', nextDay : '[jutri ob] LT', nextWeek : function () { switch (this.day()) { case 0: return '[v] [nedeljo] [ob] LT'; case 3: return '[v] [sredo] [ob] LT'; case 6: return '[v] [soboto] [ob] LT'; case 1: case 2: case 4: case 5: return '[v] dddd [ob] LT'; } }, lastDay : '[včeraj ob] LT', lastWeek : function () { switch (this.day()) { case 0: return '[prejšnjo] [nedeljo] [ob] LT'; case 3: return '[prejšnjo] [sredo] [ob] LT'; case 6: return '[prejšnjo] [soboto] [ob] LT'; case 1: case 2: case 4: case 5: return '[prejšnji] dddd [ob] LT'; } }, sameElse : 'L' }, relativeTime : { future : 'čez %s', past : 'pred %s', s : processRelativeTime$6, ss : processRelativeTime$6, m : processRelativeTime$6, mm : processRelativeTime$6, h : processRelativeTime$6, hh : processRelativeTime$6, d : processRelativeTime$6, dd : processRelativeTime$6, M : processRelativeTime$6, MM : processRelativeTime$6, y : processRelativeTime$6, yy : processRelativeTime$6 }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('sq', { months : 'Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor'.split('_'), monthsShort : 'Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj'.split('_'), weekdays : 'E Diel_E Hënë_E Martë_E Mërkurë_E Enjte_E Premte_E Shtunë'.split('_'), weekdaysShort : 'Die_Hën_Mar_Mër_Enj_Pre_Sht'.split('_'), weekdaysMin : 'D_H_Ma_Më_E_P_Sh'.split('_'), weekdaysParseExact : true, meridiemParse: /PD|MD/, isPM: function (input) { return input.charAt(0) === 'M'; }, meridiem : function (hours, minutes, isLower) { return hours < 12 ? 'PD' : 'MD'; }, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay : '[Sot në] LT', nextDay : '[Nesër në] LT', nextWeek : 'dddd [në] LT', lastDay : '[Dje në] LT', lastWeek : 'dddd [e kaluar në] LT', sameElse : 'L' }, relativeTime : { future : 'në %s', past : '%s më parë', s : 'disa sekonda', ss : '%d sekonda', m : 'një minutë', mm : '%d minuta', h : 'një orë', hh : '%d orë', d : 'një ditë', dd : '%d ditë', M : 'një muaj', MM : '%d muaj', y : 'një vit', yy : '%d vite' }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var translator$1 = { words: { //Different grammatical cases ss: ['секунда', 'секунде', 'секунди'], m: ['један минут', 'једне минуте'], mm: ['минут', 'минуте', 'минута'], h: ['један сат', 'једног сата'], hh: ['сат', 'сата', 'сати'], dd: ['дан', 'дана', 'дана'], MM: ['месец', 'месеца', 'месеци'], yy: ['година', 'године', 'година'] }, correctGrammaticalCase: function (number, wordKey) { return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]); }, translate: function (number, withoutSuffix, key) { var wordKey = translator$1.words[key]; if (key.length === 1) { return withoutSuffix ? wordKey[0] : wordKey[1]; } else { return number + ' ' + translator$1.correctGrammaticalCase(number, wordKey); } } }; moment.defineLocale('sr-cyrl', { months: 'јануар_фебруар_март_април_мај_јун_јул_август_септембар_октобар_новембар_децембар'.split('_'), monthsShort: 'јан._феб._мар._апр._мај_јун_јул_авг._сеп._окт._нов._дец.'.split('_'), monthsParseExact: true, weekdays: 'недеља_понедељак_уторак_среда_четвртак_петак_субота'.split('_'), weekdaysShort: 'нед._пон._уто._сре._чет._пет._суб.'.split('_'), weekdaysMin: 'не_по_ут_ср_че_пе_су'.split('_'), weekdaysParseExact : true, longDateFormat: { LT: 'H:mm', LTS : 'H:mm:ss', L: 'DD.MM.YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY H:mm', LLLL: 'dddd, D. MMMM YYYY H:mm' }, calendar: { sameDay: '[данас у] LT', nextDay: '[сутра у] LT', nextWeek: function () { switch (this.day()) { case 0: return '[у] [недељу] [у] LT'; case 3: return '[у] [среду] [у] LT'; case 6: return '[у] [суботу] [у] LT'; case 1: case 2: case 4: case 5: return '[у] dddd [у] LT'; } }, lastDay : '[јуче у] LT', lastWeek : function () { var lastWeekDays = [ '[прошле] [недеље] [у] LT', '[прошлог] [понедељка] [у] LT', '[прошлог] [уторка] [у] LT', '[прошле] [среде] [у] LT', '[прошлог] [четвртка] [у] LT', '[прошлог] [петка] [у] LT', '[прошле] [суботе] [у] LT' ]; return lastWeekDays[this.day()]; }, sameElse : 'L' }, relativeTime : { future : 'за %s', past : 'пре %s', s : 'неколико секунди', ss : translator$1.translate, m : translator$1.translate, mm : translator$1.translate, h : translator$1.translate, hh : translator$1.translate, d : 'дан', dd : translator$1.translate, M : 'месец', MM : translator$1.translate, y : 'годину', yy : translator$1.translate }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration var translator$2 = { words: { //Different grammatical cases ss: ['sekunda', 'sekunde', 'sekundi'], m: ['jedan minut', 'jedne minute'], mm: ['minut', 'minute', 'minuta'], h: ['jedan sat', 'jednog sata'], hh: ['sat', 'sata', 'sati'], dd: ['dan', 'dana', 'dana'], MM: ['mesec', 'meseca', 'meseci'], yy: ['godina', 'godine', 'godina'] }, correctGrammaticalCase: function (number, wordKey) { return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]); }, translate: function (number, withoutSuffix, key) { var wordKey = translator$2.words[key]; if (key.length === 1) { return withoutSuffix ? wordKey[0] : wordKey[1]; } else { return number + ' ' + translator$2.correctGrammaticalCase(number, wordKey); } } }; moment.defineLocale('sr', { months: 'januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar'.split('_'), monthsShort: 'jan._feb._mar._apr._maj_jun_jul_avg._sep._okt._nov._dec.'.split('_'), monthsParseExact: true, weekdays: 'nedelja_ponedeljak_utorak_sreda_četvrtak_petak_subota'.split('_'), weekdaysShort: 'ned._pon._uto._sre._čet._pet._sub.'.split('_'), weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), weekdaysParseExact : true, longDateFormat: { LT: 'H:mm', LTS : 'H:mm:ss', L: 'DD.MM.YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY H:mm', LLLL: 'dddd, D. MMMM YYYY H:mm' }, calendar: { sameDay: '[danas u] LT', nextDay: '[sutra u] LT', nextWeek: function () { switch (this.day()) { case 0: return '[u] [nedelju] [u] LT'; case 3: return '[u] [sredu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[juče u] LT', lastWeek : function () { var lastWeekDays = [ '[prošle] [nedelje] [u] LT', '[prošlog] [ponedeljka] [u] LT', '[prošlog] [utorka] [u] LT', '[prošle] [srede] [u] LT', '[prošlog] [četvrtka] [u] LT', '[prošlog] [petka] [u] LT', '[prošle] [subote] [u] LT' ]; return lastWeekDays[this.day()]; }, sameElse : 'L' }, relativeTime : { future : 'za %s', past : 'pre %s', s : 'nekoliko sekundi', ss : translator$2.translate, m : translator$2.translate, mm : translator$2.translate, h : translator$2.translate, hh : translator$2.translate, d : 'dan', dd : translator$2.translate, M : 'mesec', MM : translator$2.translate, y : 'godinu', yy : translator$2.translate }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('ss', { months : "Bhimbidvwane_Indlovana_Indlov'lenkhulu_Mabasa_Inkhwekhweti_Inhlaba_Kholwane_Ingci_Inyoni_Imphala_Lweti_Ingongoni".split('_'), monthsShort : 'Bhi_Ina_Inu_Mab_Ink_Inh_Kho_Igc_Iny_Imp_Lwe_Igo'.split('_'), weekdays : 'Lisontfo_Umsombuluko_Lesibili_Lesitsatfu_Lesine_Lesihlanu_Umgcibelo'.split('_'), weekdaysShort : 'Lis_Umb_Lsb_Les_Lsi_Lsh_Umg'.split('_'), weekdaysMin : 'Li_Us_Lb_Lt_Ls_Lh_Ug'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'h:mm A', LTS : 'h:mm:ss A', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY h:mm A', LLLL : 'dddd, D MMMM YYYY h:mm A' }, calendar : { sameDay : '[Namuhla nga] LT', nextDay : '[Kusasa nga] LT', nextWeek : 'dddd [nga] LT', lastDay : '[Itolo nga] LT', lastWeek : 'dddd [leliphelile] [nga] LT', sameElse : 'L' }, relativeTime : { future : 'nga %s', past : 'wenteka nga %s', s : 'emizuzwana lomcane', ss : '%d mzuzwana', m : 'umzuzu', mm : '%d emizuzu', h : 'lihora', hh : '%d emahora', d : 'lilanga', dd : '%d emalanga', M : 'inyanga', MM : '%d tinyanga', y : 'umnyaka', yy : '%d iminyaka' }, meridiemParse: /ekuseni|emini|entsambama|ebusuku/, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'ekuseni'; } else if (hours < 15) { return 'emini'; } else if (hours < 19) { return 'entsambama'; } else { return 'ebusuku'; } }, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'ekuseni') { return hour; } else if (meridiem === 'emini') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === 'entsambama' || meridiem === 'ebusuku') { if (hour === 0) { return 0; } return hour + 12; } }, dayOfMonthOrdinalParse: /\d{1,2}/, ordinal : '%d', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('sv', { months : 'januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december'.split('_'), monthsShort : 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'), weekdays : 'söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag'.split('_'), weekdaysShort : 'sön_mån_tis_ons_tor_fre_lör'.split('_'), weekdaysMin : 'sö_må_ti_on_to_fr_lö'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'YYYY-MM-DD', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY [kl.] HH:mm', LLLL : 'dddd D MMMM YYYY [kl.] HH:mm', lll : 'D MMM YYYY HH:mm', llll : 'ddd D MMM YYYY HH:mm' }, calendar : { sameDay: '[Idag] LT', nextDay: '[Imorgon] LT', lastDay: '[Igår] LT', nextWeek: '[På] dddd LT', lastWeek: '[I] dddd[s] LT', sameElse: 'L' }, relativeTime : { future : 'om %s', past : 'för %s sedan', s : 'några sekunder', ss : '%d sekunder', m : 'en minut', mm : '%d minuter', h : 'en timme', hh : '%d timmar', d : 'en dag', dd : '%d dagar', M : 'en månad', MM : '%d månader', y : 'ett år', yy : '%d år' }, dayOfMonthOrdinalParse: /\d{1,2}(e|a)/, ordinal : function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'e' : (b === 1) ? 'a' : (b === 2) ? 'a' : (b === 3) ? 'e' : 'e'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('sw', { months : 'Januari_Februari_Machi_Aprili_Mei_Juni_Julai_Agosti_Septemba_Oktoba_Novemba_Desemba'.split('_'), monthsShort : 'Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ago_Sep_Okt_Nov_Des'.split('_'), weekdays : 'Jumapili_Jumatatu_Jumanne_Jumatano_Alhamisi_Ijumaa_Jumamosi'.split('_'), weekdaysShort : 'Jpl_Jtat_Jnne_Jtan_Alh_Ijm_Jmos'.split('_'), weekdaysMin : 'J2_J3_J4_J5_Al_Ij_J1'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay : '[leo saa] LT', nextDay : '[kesho saa] LT', nextWeek : '[wiki ijayo] dddd [saat] LT', lastDay : '[jana] LT', lastWeek : '[wiki iliyopita] dddd [saat] LT', sameElse : 'L' }, relativeTime : { future : '%s baadaye', past : 'tokea %s', s : 'hivi punde', ss : 'sekunde %d', m : 'dakika moja', mm : 'dakika %d', h : 'saa limoja', hh : 'masaa %d', d : 'siku moja', dd : 'masiku %d', M : 'mwezi mmoja', MM : 'miezi %d', y : 'mwaka mmoja', yy : 'miaka %d' }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration var symbolMap$13 = { '1': '௧', '2': '௨', '3': '௩', '4': '௪', '5': '௫', '6': '௬', '7': '௭', '8': '௮', '9': '௯', '0': '௦' }, numberMap$12 = { '௧': '1', '௨': '2', '௩': '3', '௪': '4', '௫': '5', '௬': '6', '௭': '7', '௮': '8', '௯': '9', '௦': '0' }; moment.defineLocale('ta', { months : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'), monthsShort : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split('_'), weekdays : 'ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை'.split('_'), weekdaysShort : 'ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி'.split('_'), weekdaysMin : 'ஞா_தி_செ_பு_வி_வெ_ச'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY, HH:mm', LLLL : 'dddd, D MMMM YYYY, HH:mm' }, calendar : { sameDay : '[இன்று] LT', nextDay : '[நாளை] LT', nextWeek : 'dddd, LT', lastDay : '[நேற்று] LT', lastWeek : '[கடந்த வாரம்] dddd, LT', sameElse : 'L' }, relativeTime : { future : '%s இல்', past : '%s முன்', s : 'ஒரு சில விநாடிகள்', ss : '%d விநாடிகள்', m : 'ஒரு நிமிடம்', mm : '%d நிமிடங்கள்', h : 'ஒரு மணி நேரம்', hh : '%d மணி நேரம்', d : 'ஒரு நாள்', dd : '%d நாட்கள்', M : 'ஒரு மாதம்', MM : '%d மாதங்கள்', y : 'ஒரு வருடம்', yy : '%d ஆண்டுகள்' }, dayOfMonthOrdinalParse: /\d{1,2}வது/, ordinal : function (number) { return number + 'வது'; }, preparse: function (string) { return string.replace(/[௧௨௩௪௫௬௭௮௯௦]/g, function (match) { return numberMap$12[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap$13[match]; }); }, // refer http://ta.wikipedia.org/s/1er1 meridiemParse: /யாமம்|வைகறை|காலை|நண்பகல்|எற்பாடு|மாலை/, meridiem : function (hour, minute, isLower) { if (hour < 2) { return ' யாமம்'; } else if (hour < 6) { return ' வைகறை'; // வைகறை } else if (hour < 10) { return ' காலை'; // காலை } else if (hour < 14) { return ' நண்பகல்'; // நண்பகல் } else if (hour < 18) { return ' எற்பாடு'; // எற்பாடு } else if (hour < 22) { return ' மாலை'; // மாலை } else { return ' யாமம்'; } }, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'யாமம்') { return hour < 2 ? hour : hour + 12; } else if (meridiem === 'வைகறை' || meridiem === 'காலை') { return hour; } else if (meridiem === 'நண்பகல்') { return hour >= 10 ? hour : hour + 12; } else { return hour + 12; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('te', { months : 'జనవరి_ఫిబ్రవరి_మార్చి_ఏప్రిల్_మే_జూన్_జూలై_ఆగస్టు_సెప్టెంబర్_అక్టోబర్_నవంబర్_డిసెంబర్'.split('_'), monthsShort : 'జన._ఫిబ్ర._మార్చి_ఏప్రి._మే_జూన్_జూలై_ఆగ._సెప్._అక్టో._నవ._డిసె.'.split('_'), monthsParseExact : true, weekdays : 'ఆదివారం_సోమవారం_మంగళవారం_బుధవారం_గురువారం_శుక్రవారం_శనివారం'.split('_'), weekdaysShort : 'ఆది_సోమ_మంగళ_బుధ_గురు_శుక్ర_శని'.split('_'), weekdaysMin : 'ఆ_సో_మం_బు_గు_శు_శ'.split('_'), longDateFormat : { LT : 'A h:mm', LTS : 'A h:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY, A h:mm', LLLL : 'dddd, D MMMM YYYY, A h:mm' }, calendar : { sameDay : '[నేడు] LT', nextDay : '[రేపు] LT', nextWeek : 'dddd, LT', lastDay : '[నిన్న] LT', lastWeek : '[గత] dddd, LT', sameElse : 'L' }, relativeTime : { future : '%s లో', past : '%s క్రితం', s : 'కొన్ని క్షణాలు', ss : '%d సెకన్లు', m : 'ఒక నిమిషం', mm : '%d నిమిషాలు', h : 'ఒక గంట', hh : '%d గంటలు', d : 'ఒక రోజు', dd : '%d రోజులు', M : 'ఒక నెల', MM : '%d నెలలు', y : 'ఒక సంవత్సరం', yy : '%d సంవత్సరాలు' }, dayOfMonthOrdinalParse : /\d{1,2}వ/, ordinal : '%dవ', meridiemParse: /రాత్రి|ఉదయం|మధ్యాహ్నం|సాయంత్రం/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'రాత్రి') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'ఉదయం') { return hour; } else if (meridiem === 'మధ్యాహ్నం') { return hour >= 10 ? hour : hour + 12; } else if (meridiem === 'సాయంత్రం') { return hour + 12; } }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return 'రాత్రి'; } else if (hour < 10) { return 'ఉదయం'; } else if (hour < 17) { return 'మధ్యాహ్నం'; } else if (hour < 20) { return 'సాయంత్రం'; } else { return 'రాత్రి'; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('tet', { months : 'Janeiru_Fevereiru_Marsu_Abril_Maiu_Juñu_Jullu_Agustu_Setembru_Outubru_Novembru_Dezembru'.split('_'), monthsShort : 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'), weekdays : 'Domingu_Segunda_Tersa_Kuarta_Kinta_Sesta_Sabadu'.split('_'), weekdaysShort : 'Dom_Seg_Ters_Kua_Kint_Sest_Sab'.split('_'), weekdaysMin : 'Do_Seg_Te_Ku_Ki_Ses_Sa'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay: '[Ohin iha] LT', nextDay: '[Aban iha] LT', nextWeek: 'dddd [iha] LT', lastDay: '[Horiseik iha] LT', lastWeek: 'dddd [semana kotuk] [iha] LT', sameElse: 'L' }, relativeTime : { future : 'iha %s', past : '%s liuba', s : 'minutu balun', ss : 'minutu %d', m : 'minutu ida', mm : 'minutu %d', h : 'oras ida', hh : 'oras %d', d : 'loron ida', dd : 'loron %d', M : 'fulan ida', MM : 'fulan %d', y : 'tinan ida', yy : 'tinan %d' }, dayOfMonthOrdinalParse: /\d{1,2}(st|nd|rd|th)/, ordinal : function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var suffixes$3 = { 0: '-ум', 1: '-ум', 2: '-юм', 3: '-юм', 4: '-ум', 5: '-ум', 6: '-ум', 7: '-ум', 8: '-ум', 9: '-ум', 10: '-ум', 12: '-ум', 13: '-ум', 20: '-ум', 30: '-юм', 40: '-ум', 50: '-ум', 60: '-ум', 70: '-ум', 80: '-ум', 90: '-ум', 100: '-ум' }; moment.defineLocale('tg', { months : 'январ_феврал_март_апрел_май_июн_июл_август_сентябр_октябр_ноябр_декабр'.split('_'), monthsShort : 'янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек'.split('_'), weekdays : 'якшанбе_душанбе_сешанбе_чоршанбе_панҷшанбе_ҷумъа_шанбе'.split('_'), weekdaysShort : 'яшб_дшб_сшб_чшб_пшб_ҷум_шнб'.split('_'), weekdaysMin : 'яш_дш_сш_чш_пш_ҷм_шб'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay : '[Имрӯз соати] LT', nextDay : '[Пагоҳ соати] LT', lastDay : '[Дирӯз соати] LT', nextWeek : 'dddd[и] [ҳафтаи оянда соати] LT', lastWeek : 'dddd[и] [ҳафтаи гузашта соати] LT', sameElse : 'L' }, relativeTime : { future : 'баъди %s', past : '%s пеш', s : 'якчанд сония', m : 'як дақиқа', mm : '%d дақиқа', h : 'як соат', hh : '%d соат', d : 'як рӯз', dd : '%d рӯз', M : 'як моҳ', MM : '%d моҳ', y : 'як сол', yy : '%d сол' }, meridiemParse: /шаб|субҳ|рӯз|бегоҳ/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'шаб') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'субҳ') { return hour; } else if (meridiem === 'рӯз') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === 'бегоҳ') { return hour + 12; } }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return 'шаб'; } else if (hour < 11) { return 'субҳ'; } else if (hour < 16) { return 'рӯз'; } else if (hour < 19) { return 'бегоҳ'; } else { return 'шаб'; } }, dayOfMonthOrdinalParse: /\d{1,2}-(ум|юм)/, ordinal: function (number) { var a = number % 10, b = number >= 100 ? 100 : null; return number + (suffixes$3[number] || suffixes$3[a] || suffixes$3[b]); }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('th', { months : 'มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม'.split('_'), monthsShort : 'ม.ค._ก.พ._มี.ค._เม.ย._พ.ค._มิ.ย._ก.ค._ส.ค._ก.ย._ต.ค._พ.ย._ธ.ค.'.split('_'), monthsParseExact: true, weekdays : 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์'.split('_'), weekdaysShort : 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์'.split('_'), // yes, three characters difference weekdaysMin : 'อา._จ._อ._พ._พฤ._ศ._ส.'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY เวลา H:mm', LLLL : 'วันddddที่ D MMMM YYYY เวลา H:mm' }, meridiemParse: /ก่อนเที่ยง|หลังเที่ยง/, isPM: function (input) { return input === 'หลังเที่ยง'; }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return 'ก่อนเที่ยง'; } else { return 'หลังเที่ยง'; } }, calendar : { sameDay : '[วันนี้ เวลา] LT', nextDay : '[พรุ่งนี้ เวลา] LT', nextWeek : 'dddd[หน้า เวลา] LT', lastDay : '[เมื่อวานนี้ เวลา] LT', lastWeek : '[วัน]dddd[ที่แล้ว เวลา] LT', sameElse : 'L' }, relativeTime : { future : 'อีก %s', past : '%sที่แล้ว', s : 'ไม่กี่วินาที', ss : '%d วินาที', m : '1 นาที', mm : '%d นาที', h : '1 ชั่วโมง', hh : '%d ชั่วโมง', d : '1 วัน', dd : '%d วัน', M : '1 เดือน', MM : '%d เดือน', y : '1 ปี', yy : '%d ปี' } }); //! moment.js locale configuration moment.defineLocale('tl-ph', { months : 'Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre'.split('_'), monthsShort : 'Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis'.split('_'), weekdays : 'Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado'.split('_'), weekdaysShort : 'Lin_Lun_Mar_Miy_Huw_Biy_Sab'.split('_'), weekdaysMin : 'Li_Lu_Ma_Mi_Hu_Bi_Sab'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'MM/D/YYYY', LL : 'MMMM D, YYYY', LLL : 'MMMM D, YYYY HH:mm', LLLL : 'dddd, MMMM DD, YYYY HH:mm' }, calendar : { sameDay: 'LT [ngayong araw]', nextDay: '[Bukas ng] LT', nextWeek: 'LT [sa susunod na] dddd', lastDay: 'LT [kahapon]', lastWeek: 'LT [noong nakaraang] dddd', sameElse: 'L' }, relativeTime : { future : 'sa loob ng %s', past : '%s ang nakalipas', s : 'ilang segundo', ss : '%d segundo', m : 'isang minuto', mm : '%d minuto', h : 'isang oras', hh : '%d oras', d : 'isang araw', dd : '%d araw', M : 'isang buwan', MM : '%d buwan', y : 'isang taon', yy : '%d taon' }, dayOfMonthOrdinalParse: /\d{1,2}/, ordinal : function (number) { return number; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration var numbersNouns = 'pagh_wa’_cha’_wej_loS_vagh_jav_Soch_chorgh_Hut'.split('_'); function translateFuture(output) { var time = output; time = (output.indexOf('jaj') !== -1) ? time.slice(0, -3) + 'leS' : (output.indexOf('jar') !== -1) ? time.slice(0, -3) + 'waQ' : (output.indexOf('DIS') !== -1) ? time.slice(0, -3) + 'nem' : time + ' pIq'; return time; } function translatePast(output) { var time = output; time = (output.indexOf('jaj') !== -1) ? time.slice(0, -3) + 'Hu’' : (output.indexOf('jar') !== -1) ? time.slice(0, -3) + 'wen' : (output.indexOf('DIS') !== -1) ? time.slice(0, -3) + 'ben' : time + ' ret'; return time; } function translate$9(number, withoutSuffix, string, isFuture) { var numberNoun = numberAsNoun(number); switch (string) { case 'ss': return numberNoun + ' lup'; case 'mm': return numberNoun + ' tup'; case 'hh': return numberNoun + ' rep'; case 'dd': return numberNoun + ' jaj'; case 'MM': return numberNoun + ' jar'; case 'yy': return numberNoun + ' DIS'; } } function numberAsNoun(number) { var hundred = Math.floor((number % 1000) / 100), ten = Math.floor((number % 100) / 10), one = number % 10, word = ''; if (hundred > 0) { word += numbersNouns[hundred] + 'vatlh'; } if (ten > 0) { word += ((word !== '') ? ' ' : '') + numbersNouns[ten] + 'maH'; } if (one > 0) { word += ((word !== '') ? ' ' : '') + numbersNouns[one]; } return (word === '') ? 'pagh' : word; } moment.defineLocale('tlh', { months : 'tera’ jar wa’_tera’ jar cha’_tera’ jar wej_tera’ jar loS_tera’ jar vagh_tera’ jar jav_tera’ jar Soch_tera’ jar chorgh_tera’ jar Hut_tera’ jar wa’maH_tera’ jar wa’maH wa’_tera’ jar wa’maH cha’'.split('_'), monthsShort : 'jar wa’_jar cha’_jar wej_jar loS_jar vagh_jar jav_jar Soch_jar chorgh_jar Hut_jar wa’maH_jar wa’maH wa’_jar wa’maH cha’'.split('_'), monthsParseExact : true, weekdays : 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'), weekdaysShort : 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'), weekdaysMin : 'lojmItjaj_DaSjaj_povjaj_ghItlhjaj_loghjaj_buqjaj_ghInjaj'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay: '[DaHjaj] LT', nextDay: '[wa’leS] LT', nextWeek: 'LLL', lastDay: '[wa’Hu’] LT', lastWeek: 'LLL', sameElse: 'L' }, relativeTime : { future : translateFuture, past : translatePast, s : 'puS lup', ss : translate$9, m : 'wa’ tup', mm : translate$9, h : 'wa’ rep', hh : translate$9, d : 'wa’ jaj', dd : translate$9, M : 'wa’ jar', MM : translate$9, y : 'wa’ DIS', yy : translate$9 }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); var suffixes$4 = { 1: '\'inci', 5: '\'inci', 8: '\'inci', 70: '\'inci', 80: '\'inci', 2: '\'nci', 7: '\'nci', 20: '\'nci', 50: '\'nci', 3: '\'üncü', 4: '\'üncü', 100: '\'üncü', 6: '\'ncı', 9: '\'uncu', 10: '\'uncu', 30: '\'uncu', 60: '\'ıncı', 90: '\'ıncı' }; moment.defineLocale('tr', { months : 'Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık'.split('_'), monthsShort : 'Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara'.split('_'), weekdays : 'Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi'.split('_'), weekdaysShort : 'Paz_Pts_Sal_Çar_Per_Cum_Cts'.split('_'), weekdaysMin : 'Pz_Pt_Sa_Ça_Pe_Cu_Ct'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay : '[bugün saat] LT', nextDay : '[yarın saat] LT', nextWeek : '[gelecek] dddd [saat] LT', lastDay : '[dün] LT', lastWeek : '[geçen] dddd [saat] LT', sameElse : 'L' }, relativeTime : { future : '%s sonra', past : '%s önce', s : 'birkaç saniye', ss : '%d saniye', m : 'bir dakika', mm : '%d dakika', h : 'bir saat', hh : '%d saat', d : 'bir gün', dd : '%d gün', M : 'bir ay', MM : '%d ay', y : 'bir yıl', yy : '%d yıl' }, ordinal: function (number, period) { switch (period) { case 'd': case 'D': case 'Do': case 'DD': return number; default: if (number === 0) { // special case for zero return number + '\'ıncı'; } var a = number % 10, b = number % 100 - a, c = number >= 100 ? 100 : null; return number + (suffixes$4[a] || suffixes$4[b] || suffixes$4[c]); } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration // After the year there should be a slash and the amount of years since December 26, 1979 in Roman numerals. // This is currently too difficult (maybe even impossible) to add. moment.defineLocale('tzl', { months : 'Januar_Fevraglh_Març_Avrïu_Mai_Gün_Julia_Guscht_Setemvar_Listopäts_Noemvar_Zecemvar'.split('_'), monthsShort : 'Jan_Fev_Mar_Avr_Mai_Gün_Jul_Gus_Set_Lis_Noe_Zec'.split('_'), weekdays : 'Súladi_Lúneçi_Maitzi_Márcuri_Xhúadi_Viénerçi_Sáturi'.split('_'), weekdaysShort : 'Súl_Lún_Mai_Már_Xhú_Vié_Sát'.split('_'), weekdaysMin : 'Sú_Lú_Ma_Má_Xh_Vi_Sá'.split('_'), longDateFormat : { LT : 'HH.mm', LTS : 'HH.mm.ss', L : 'DD.MM.YYYY', LL : 'D. MMMM [dallas] YYYY', LLL : 'D. MMMM [dallas] YYYY HH.mm', LLLL : 'dddd, [li] D. MMMM [dallas] YYYY HH.mm' }, meridiemParse: /d\'o|d\'a/i, isPM : function (input) { return 'd\'o' === input.toLowerCase(); }, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'd\'o' : 'D\'O'; } else { return isLower ? 'd\'a' : 'D\'A'; } }, calendar : { sameDay : '[oxhi à] LT', nextDay : '[demà à] LT', nextWeek : 'dddd [à] LT', lastDay : '[ieiri à] LT', lastWeek : '[sür el] dddd [lasteu à] LT', sameElse : 'L' }, relativeTime : { future : 'osprei %s', past : 'ja%s', s : processRelativeTime$7, ss : processRelativeTime$7, m : processRelativeTime$7, mm : processRelativeTime$7, h : processRelativeTime$7, hh : processRelativeTime$7, d : processRelativeTime$7, dd : processRelativeTime$7, M : processRelativeTime$7, MM : processRelativeTime$7, y : processRelativeTime$7, yy : processRelativeTime$7 }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); function processRelativeTime$7(number, withoutSuffix, key, isFuture) { var format = { 's': ['viensas secunds', '\'iensas secunds'], 'ss': [number + ' secunds', '' + number + ' secunds'], 'm': ['\'n míut', '\'iens míut'], 'mm': [number + ' míuts', '' + number + ' míuts'], 'h': ['\'n þora', '\'iensa þora'], 'hh': [number + ' þoras', '' + number + ' þoras'], 'd': ['\'n ziua', '\'iensa ziua'], 'dd': [number + ' ziuas', '' + number + ' ziuas'], 'M': ['\'n mes', '\'iens mes'], 'MM': [number + ' mesen', '' + number + ' mesen'], 'y': ['\'n ar', '\'iens ar'], 'yy': [number + ' ars', '' + number + ' ars'] }; return isFuture ? format[key][0] : (withoutSuffix ? format[key][0] : format[key][1]); } //! moment.js locale configuration moment.defineLocale('tzm-latn', { months : 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'), monthsShort : 'innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir'.split('_'), weekdays : 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), weekdaysShort : 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), weekdaysMin : 'asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { sameDay: '[asdkh g] LT', nextDay: '[aska g] LT', nextWeek: 'dddd [g] LT', lastDay: '[assant g] LT', lastWeek: 'dddd [g] LT', sameElse: 'L' }, relativeTime : { future : 'dadkh s yan %s', past : 'yan %s', s : 'imik', ss : '%d imik', m : 'minuḍ', mm : '%d minuḍ', h : 'saɛa', hh : '%d tassaɛin', d : 'ass', dd : '%d ossan', M : 'ayowr', MM : '%d iyyirn', y : 'asgas', yy : '%d isgasn' }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('tzm', { months : 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'), monthsShort : 'ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ'.split('_'), weekdays : 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), weekdaysShort : 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), weekdaysMin : 'ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ'.split('_'), longDateFormat : { LT : 'HH:mm', LTS: 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { sameDay: '[ⴰⵙⴷⵅ ⴴ] LT', nextDay: '[ⴰⵙⴽⴰ ⴴ] LT', nextWeek: 'dddd [ⴴ] LT', lastDay: '[ⴰⵚⴰⵏⵜ ⴴ] LT', lastWeek: 'dddd [ⴴ] LT', sameElse: 'L' }, relativeTime : { future : 'ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s', past : 'ⵢⴰⵏ %s', s : 'ⵉⵎⵉⴽ', ss : '%d ⵉⵎⵉⴽ', m : 'ⵎⵉⵏⵓⴺ', mm : '%d ⵎⵉⵏⵓⴺ', h : 'ⵙⴰⵄⴰ', hh : '%d ⵜⴰⵙⵙⴰⵄⵉⵏ', d : 'ⴰⵙⵙ', dd : '%d oⵙⵙⴰⵏ', M : 'ⴰⵢoⵓⵔ', MM : '%d ⵉⵢⵢⵉⵔⵏ', y : 'ⴰⵙⴳⴰⵙ', yy : '%d ⵉⵙⴳⴰⵙⵏ' }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js language configuration moment.defineLocale('ug-cn', { months: 'يانۋار_فېۋرال_مارت_ئاپرېل_ماي_ئىيۇن_ئىيۇل_ئاۋغۇست_سېنتەبىر_ئۆكتەبىر_نويابىر_دېكابىر'.split( '_' ), monthsShort: 'يانۋار_فېۋرال_مارت_ئاپرېل_ماي_ئىيۇن_ئىيۇل_ئاۋغۇست_سېنتەبىر_ئۆكتەبىر_نويابىر_دېكابىر'.split( '_' ), weekdays: 'يەكشەنبە_دۈشەنبە_سەيشەنبە_چارشەنبە_پەيشەنبە_جۈمە_شەنبە'.split( '_' ), weekdaysShort: 'يە_دۈ_سە_چا_پە_جۈ_شە'.split('_'), weekdaysMin: 'يە_دۈ_سە_چا_پە_جۈ_شە'.split('_'), longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'YYYY-MM-DD', LL: 'YYYY-يىلىM-ئاينىڭD-كۈنى', LLL: 'YYYY-يىلىM-ئاينىڭD-كۈنى، HH:mm', LLLL: 'dddd، YYYY-يىلىM-ئاينىڭD-كۈنى، HH:mm' }, meridiemParse: /يېرىم كېچە|سەھەر|چۈشتىن بۇرۇن|چۈش|چۈشتىن كېيىن|كەچ/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if ( meridiem === 'يېرىم كېچە' || meridiem === 'سەھەر' || meridiem === 'چۈشتىن بۇرۇن' ) { return hour; } else if (meridiem === 'چۈشتىن كېيىن' || meridiem === 'كەچ') { return hour + 12; } else { return hour >= 11 ? hour : hour + 12; } }, meridiem: function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 600) { return 'يېرىم كېچە'; } else if (hm < 900) { return 'سەھەر'; } else if (hm < 1130) { return 'چۈشتىن بۇرۇن'; } else if (hm < 1230) { return 'چۈش'; } else if (hm < 1800) { return 'چۈشتىن كېيىن'; } else { return 'كەچ'; } }, calendar: { sameDay: '[بۈگۈن سائەت] LT', nextDay: '[ئەتە سائەت] LT', nextWeek: '[كېلەركى] dddd [سائەت] LT', lastDay: '[تۆنۈگۈن] LT', lastWeek: '[ئالدىنقى] dddd [سائەت] LT', sameElse: 'L' }, relativeTime: { future: '%s كېيىن', past: '%s بۇرۇن', s: 'نەچچە سېكونت', ss: '%d سېكونت', m: 'بىر مىنۇت', mm: '%d مىنۇت', h: 'بىر سائەت', hh: '%d سائەت', d: 'بىر كۈن', dd: '%d كۈن', M: 'بىر ئاي', MM: '%d ئاي', y: 'بىر يىل', yy: '%d يىل' }, dayOfMonthOrdinalParse: /\d{1,2}(-كۈنى|-ئاي|-ھەپتە)/, ordinal: function (number, period) { switch (period) { case 'd': case 'D': case 'DDD': return number + '-كۈنى'; case 'w': case 'W': return number + '-ھەپتە'; default: return number; } }, preparse: function (string) { return string.replace(/،/g, ','); }, postformat: function (string) { return string.replace(/,/g, '،'); }, week: { // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效 dow: 1, // Monday is the first day of the week. doy: 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration function plural$6(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural$4(number, withoutSuffix, key) { var format = { 'ss': withoutSuffix ? 'секунда_секунди_секунд' : 'секунду_секунди_секунд', 'mm': withoutSuffix ? 'хвилина_хвилини_хвилин' : 'хвилину_хвилини_хвилин', 'hh': withoutSuffix ? 'година_години_годин' : 'годину_години_годин', 'dd': 'день_дні_днів', 'MM': 'місяць_місяці_місяців', 'yy': 'рік_роки_років' }; if (key === 'm') { return withoutSuffix ? 'хвилина' : 'хвилину'; } else if (key === 'h') { return withoutSuffix ? 'година' : 'годину'; } else { return number + ' ' + plural$6(format[key], +number); } } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота'.split('_'), 'accusative': 'неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу'.split('_'), 'genitive': 'неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи'.split('_') }; if (!m) { return weekdays['nominative']; } var nounCase = (/(\[[ВвУу]\]) ?dddd/).test(format) ? 'accusative' : ((/\[?(?:минулої|наступної)? ?\] ?dddd/).test(format) ? 'genitive' : 'nominative'); return weekdays[nounCase][m.day()]; } function processHoursFunction(str) { return function () { return str + 'о' + (this.hours() === 11 ? 'б' : '') + '] LT'; }; } moment.defineLocale('uk', { months : { 'format': 'січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня'.split('_'), 'standalone': 'січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень'.split('_') }, monthsShort : 'січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд'.split('_'), weekdays : weekdaysCaseReplace, weekdaysShort : 'нд_пн_вт_ср_чт_пт_сб'.split('_'), weekdaysMin : 'нд_пн_вт_ср_чт_пт_сб'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD.MM.YYYY', LL : 'D MMMM YYYY р.', LLL : 'D MMMM YYYY р., HH:mm', LLLL : 'dddd, D MMMM YYYY р., HH:mm' }, calendar : { sameDay: processHoursFunction('[Сьогодні '), nextDay: processHoursFunction('[Завтра '), lastDay: processHoursFunction('[Вчора '), nextWeek: processHoursFunction('[У] dddd ['), lastWeek: function () { switch (this.day()) { case 0: case 3: case 5: case 6: return processHoursFunction('[Минулої] dddd [').call(this); case 1: case 2: case 4: return processHoursFunction('[Минулого] dddd [').call(this); } }, sameElse: 'L' }, relativeTime : { future : 'за %s', past : '%s тому', s : 'декілька секунд', ss : relativeTimeWithPlural$4, m : relativeTimeWithPlural$4, mm : relativeTimeWithPlural$4, h : 'годину', hh : relativeTimeWithPlural$4, d : 'день', dd : relativeTimeWithPlural$4, M : 'місяць', MM : relativeTimeWithPlural$4, y : 'рік', yy : relativeTimeWithPlural$4 }, // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason meridiemParse: /ночі|ранку|дня|вечора/, isPM: function (input) { return /^(дня|вечора)$/.test(input); }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return 'ночі'; } else if (hour < 12) { return 'ранку'; } else if (hour < 17) { return 'дня'; } else { return 'вечора'; } }, dayOfMonthOrdinalParse: /\d{1,2}-(й|го)/, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': case 'w': case 'W': return number + '-й'; case 'D': return number + '-го'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration var months$7 = [ 'جنوری', 'فروری', 'مارچ', 'اپریل', 'مئی', 'جون', 'جولائی', 'اگست', 'ستمبر', 'اکتوبر', 'نومبر', 'دسمبر' ]; var days$1 = [ 'اتوار', 'پیر', 'منگل', 'بدھ', 'جمعرات', 'جمعہ', 'ہفتہ' ]; moment.defineLocale('ur', { months : months$7, monthsShort : months$7, weekdays : days$1, weekdaysShort : days$1, weekdaysMin : days$1, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd، D MMMM YYYY HH:mm' }, meridiemParse: /صبح|شام/, isPM : function (input) { return 'شام' === input; }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return 'صبح'; } return 'شام'; }, calendar : { sameDay : '[آج بوقت] LT', nextDay : '[کل بوقت] LT', nextWeek : 'dddd [بوقت] LT', lastDay : '[گذشتہ روز بوقت] LT', lastWeek : '[گذشتہ] dddd [بوقت] LT', sameElse : 'L' }, relativeTime : { future : '%s بعد', past : '%s قبل', s : 'چند سیکنڈ', ss : '%d سیکنڈ', m : 'ایک منٹ', mm : '%d منٹ', h : 'ایک گھنٹہ', hh : '%d گھنٹے', d : 'ایک دن', dd : '%d دن', M : 'ایک ماہ', MM : '%d ماہ', y : 'ایک سال', yy : '%d سال' }, preparse: function (string) { return string.replace(/،/g, ','); }, postformat: function (string) { return string.replace(/,/g, '،'); }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('uz-latn', { months : 'Yanvar_Fevral_Mart_Aprel_May_Iyun_Iyul_Avgust_Sentabr_Oktabr_Noyabr_Dekabr'.split('_'), monthsShort : 'Yan_Fev_Mar_Apr_May_Iyun_Iyul_Avg_Sen_Okt_Noy_Dek'.split('_'), weekdays : 'Yakshanba_Dushanba_Seshanba_Chorshanba_Payshanba_Juma_Shanba'.split('_'), weekdaysShort : 'Yak_Dush_Sesh_Chor_Pay_Jum_Shan'.split('_'), weekdaysMin : 'Ya_Du_Se_Cho_Pa_Ju_Sha'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'D MMMM YYYY, dddd HH:mm' }, calendar : { sameDay : '[Bugun soat] LT [da]', nextDay : '[Ertaga] LT [da]', nextWeek : 'dddd [kuni soat] LT [da]', lastDay : '[Kecha soat] LT [da]', lastWeek : '[O\'tgan] dddd [kuni soat] LT [da]', sameElse : 'L' }, relativeTime : { future : 'Yaqin %s ichida', past : 'Bir necha %s oldin', s : 'soniya', ss : '%d soniya', m : 'bir daqiqa', mm : '%d daqiqa', h : 'bir soat', hh : '%d soat', d : 'bir kun', dd : '%d kun', M : 'bir oy', MM : '%d oy', y : 'bir yil', yy : '%d yil' }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('uz', { months : 'январ_феврал_март_апрел_май_июн_июл_август_сентябр_октябр_ноябр_декабр'.split('_'), monthsShort : 'янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек'.split('_'), weekdays : 'Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба'.split('_'), weekdaysShort : 'Якш_Душ_Сеш_Чор_Пай_Жум_Шан'.split('_'), weekdaysMin : 'Як_Ду_Се_Чо_Па_Жу_Ша'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'D MMMM YYYY, dddd HH:mm' }, calendar : { sameDay : '[Бугун соат] LT [да]', nextDay : '[Эртага] LT [да]', nextWeek : 'dddd [куни соат] LT [да]', lastDay : '[Кеча соат] LT [да]', lastWeek : '[Утган] dddd [куни соат] LT [да]', sameElse : 'L' }, relativeTime : { future : 'Якин %s ичида', past : 'Бир неча %s олдин', s : 'фурсат', ss : '%d фурсат', m : 'бир дакика', mm : '%d дакика', h : 'бир соат', hh : '%d соат', d : 'бир кун', dd : '%d кун', M : 'бир ой', MM : '%d ой', y : 'бир йил', yy : '%d йил' }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('vi', { months : 'tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12'.split('_'), monthsShort : 'Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12'.split('_'), monthsParseExact : true, weekdays : 'chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy'.split('_'), weekdaysShort : 'CN_T2_T3_T4_T5_T6_T7'.split('_'), weekdaysMin : 'CN_T2_T3_T4_T5_T6_T7'.split('_'), weekdaysParseExact : true, meridiemParse: /sa|ch/i, isPM : function (input) { return /^ch$/i.test(input); }, meridiem : function (hours, minutes, isLower) { if (hours < 12) { return isLower ? 'sa' : 'SA'; } else { return isLower ? 'ch' : 'CH'; } }, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM [năm] YYYY', LLL : 'D MMMM [năm] YYYY HH:mm', LLLL : 'dddd, D MMMM [năm] YYYY HH:mm', l : 'DD/M/YYYY', ll : 'D MMM YYYY', lll : 'D MMM YYYY HH:mm', llll : 'ddd, D MMM YYYY HH:mm' }, calendar : { sameDay: '[Hôm nay lúc] LT', nextDay: '[Ngày mai lúc] LT', nextWeek: 'dddd [tuần tới lúc] LT', lastDay: '[Hôm qua lúc] LT', lastWeek: 'dddd [tuần rồi lúc] LT', sameElse: 'L' }, relativeTime : { future : '%s tới', past : '%s trước', s : 'vài giây', ss : '%d giây' , m : 'một phút', mm : '%d phút', h : 'một giờ', hh : '%d giờ', d : 'một ngày', dd : '%d ngày', M : 'một tháng', MM : '%d tháng', y : 'một năm', yy : '%d năm' }, dayOfMonthOrdinalParse: /\d{1,2}/, ordinal : function (number) { return number; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('x-pseudo', { months : 'J~áñúá~rý_F~ébrú~árý_~Márc~h_Áp~ríl_~Máý_~Júñé~_Júl~ý_Áú~gúst~_Sép~témb~ér_Ó~ctób~ér_Ñ~óvém~bér_~Décé~mbér'.split('_'), monthsShort : 'J~áñ_~Féb_~Már_~Ápr_~Máý_~Júñ_~Júl_~Áúg_~Sép_~Óct_~Ñóv_~Déc'.split('_'), monthsParseExact : true, weekdays : 'S~úñdá~ý_Mó~ñdáý~_Túé~sdáý~_Wéd~ñésd~áý_T~húrs~dáý_~Fríd~áý_S~átúr~dáý'.split('_'), weekdaysShort : 'S~úñ_~Móñ_~Túé_~Wéd_~Thú_~Frí_~Sát'.split('_'), weekdaysMin : 'S~ú_Mó~_Tú_~Wé_T~h_Fr~_Sá'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd, D MMMM YYYY HH:mm' }, calendar : { sameDay : '[T~ódá~ý át] LT', nextDay : '[T~ómó~rró~w át] LT', nextWeek : 'dddd [át] LT', lastDay : '[Ý~ést~érdá~ý át] LT', lastWeek : '[L~ást] dddd [át] LT', sameElse : 'L' }, relativeTime : { future : 'í~ñ %s', past : '%s á~gó', s : 'á ~féw ~sécó~ñds', ss : '%d s~écóñ~ds', m : 'á ~míñ~úté', mm : '%d m~íñú~tés', h : 'á~ñ hó~úr', hh : '%d h~óúrs', d : 'á ~dáý', dd : '%d d~áýs', M : 'á ~móñ~th', MM : '%d m~óñt~hs', y : 'á ~ýéár', yy : '%d ý~éárs' }, dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal : function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('yo', { months : 'Sẹ́rẹ́_Èrèlè_Ẹrẹ̀nà_Ìgbé_Èbibi_Òkùdu_Agẹmo_Ògún_Owewe_Ọ̀wàrà_Bélú_Ọ̀pẹ̀̀'.split('_'), monthsShort : 'Sẹ́r_Èrl_Ẹrn_Ìgb_Èbi_Òkù_Agẹ_Ògú_Owe_Ọ̀wà_Bél_Ọ̀pẹ̀̀'.split('_'), weekdays : 'Àìkú_Ajé_Ìsẹ́gun_Ọjọ́rú_Ọjọ́bọ_Ẹtì_Àbámẹ́ta'.split('_'), weekdaysShort : 'Àìk_Ajé_Ìsẹ́_Ọjr_Ọjb_Ẹtì_Àbá'.split('_'), weekdaysMin : 'Àì_Aj_Ìs_Ọr_Ọb_Ẹt_Àb'.split('_'), longDateFormat : { LT : 'h:mm A', LTS : 'h:mm:ss A', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY h:mm A', LLLL : 'dddd, D MMMM YYYY h:mm A' }, calendar : { sameDay : '[Ònì ni] LT', nextDay : '[Ọ̀la ni] LT', nextWeek : 'dddd [Ọsẹ̀ tón\'bọ] [ni] LT', lastDay : '[Àna ni] LT', lastWeek : 'dddd [Ọsẹ̀ tólọ́] [ni] LT', sameElse : 'L' }, relativeTime : { future : 'ní %s', past : '%s kọjá', s : 'ìsẹjú aayá die', ss :'aayá %d', m : 'ìsẹjú kan', mm : 'ìsẹjú %d', h : 'wákati kan', hh : 'wákati %d', d : 'ọjọ́ kan', dd : 'ọjọ́ %d', M : 'osù kan', MM : 'osù %d', y : 'ọdún kan', yy : 'ọdún %d' }, dayOfMonthOrdinalParse : /ọjọ́\s\d{1,2}/, ordinal : 'ọjọ́ %d', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('zh-cn', { months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), weekdaysShort : '周日_周一_周二_周三_周四_周五_周六'.split('_'), weekdaysMin : '日_一_二_三_四_五_六'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'YYYY/MM/DD', LL : 'YYYY年M月D日', LLL : 'YYYY年M月D日Ah点mm分', LLLL : 'YYYY年M月D日ddddAh点mm分', l : 'YYYY/M/D', ll : 'YYYY年M月D日', lll : 'YYYY年M月D日 HH:mm', llll : 'YYYY年M月D日dddd HH:mm' }, meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, meridiemHour: function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') { return hour; } else if (meridiem === '下午' || meridiem === '晚上') { return hour + 12; } else { // '中午' return hour >= 11 ? hour : hour + 12; } }, meridiem : function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 600) { return '凌晨'; } else if (hm < 900) { return '早上'; } else if (hm < 1130) { return '上午'; } else if (hm < 1230) { return '中午'; } else if (hm < 1800) { return '下午'; } else { return '晚上'; } }, calendar : { sameDay : '[今天]LT', nextDay : '[明天]LT', nextWeek : '[下]ddddLT', lastDay : '[昨天]LT', lastWeek : '[上]ddddLT', sameElse : 'L' }, dayOfMonthOrdinalParse: /\d{1,2}(日|月|周)/, ordinal : function (number, period) { switch (period) { case 'd': case 'D': case 'DDD': return number + '日'; case 'M': return number + '月'; case 'w': case 'W': return number + '周'; default: return number; } }, relativeTime : { future : '%s内', past : '%s前', s : '几秒', ss : '%d 秒', m : '1 分钟', mm : '%d 分钟', h : '1 小时', hh : '%d 小时', d : '1 天', dd : '%d 天', M : '1 个月', MM : '%d 个月', y : '1 年', yy : '%d 年' }, week : { // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效 dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); //! moment.js locale configuration moment.defineLocale('zh-hk', { months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), weekdaysShort : '週日_週一_週二_週三_週四_週五_週六'.split('_'), weekdaysMin : '日_一_二_三_四_五_六'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'YYYY/MM/DD', LL : 'YYYY年M月D日', LLL : 'YYYY年M月D日 HH:mm', LLLL : 'YYYY年M月D日dddd HH:mm', l : 'YYYY/M/D', ll : 'YYYY年M月D日', lll : 'YYYY年M月D日 HH:mm', llll : 'YYYY年M月D日dddd HH:mm' }, meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') { return hour; } else if (meridiem === '中午') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === '下午' || meridiem === '晚上') { return hour + 12; } }, meridiem : function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 600) { return '凌晨'; } else if (hm < 900) { return '早上'; } else if (hm < 1130) { return '上午'; } else if (hm < 1230) { return '中午'; } else if (hm < 1800) { return '下午'; } else { return '晚上'; } }, calendar : { sameDay : '[今天]LT', nextDay : '[明天]LT', nextWeek : '[下]ddddLT', lastDay : '[昨天]LT', lastWeek : '[上]ddddLT', sameElse : 'L' }, dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/, ordinal : function (number, period) { switch (period) { case 'd' : case 'D' : case 'DDD' : return number + '日'; case 'M' : return number + '月'; case 'w' : case 'W' : return number + '週'; default : return number; } }, relativeTime : { future : '%s內', past : '%s前', s : '幾秒', ss : '%d 秒', m : '1 分鐘', mm : '%d 分鐘', h : '1 小時', hh : '%d 小時', d : '1 天', dd : '%d 天', M : '1 個月', MM : '%d 個月', y : '1 年', yy : '%d 年' } }); //! moment.js locale configuration moment.defineLocale('zh-tw', { months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'), monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'), weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'), weekdaysShort : '週日_週一_週二_週三_週四_週五_週六'.split('_'), weekdaysMin : '日_一_二_三_四_五_六'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'YYYY/MM/DD', LL : 'YYYY年M月D日', LLL : 'YYYY年M月D日 HH:mm', LLLL : 'YYYY年M月D日dddd HH:mm', l : 'YYYY/M/D', ll : 'YYYY年M月D日', lll : 'YYYY年M月D日 HH:mm', llll : 'YYYY年M月D日dddd HH:mm' }, meridiemParse: /凌晨|早上|上午|中午|下午|晚上/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === '凌晨' || meridiem === '早上' || meridiem === '上午') { return hour; } else if (meridiem === '中午') { return hour >= 11 ? hour : hour + 12; } else if (meridiem === '下午' || meridiem === '晚上') { return hour + 12; } }, meridiem : function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 600) { return '凌晨'; } else if (hm < 900) { return '早上'; } else if (hm < 1130) { return '上午'; } else if (hm < 1230) { return '中午'; } else if (hm < 1800) { return '下午'; } else { return '晚上'; } }, calendar : { sameDay : '[今天]LT', nextDay : '[明天]LT', nextWeek : '[下]ddddLT', lastDay : '[昨天]LT', lastWeek : '[上]ddddLT', sameElse : 'L' }, dayOfMonthOrdinalParse: /\d{1,2}(日|月|週)/, ordinal : function (number, period) { switch (period) { case 'd' : case 'D' : case 'DDD' : return number + '日'; case 'M' : return number + '月'; case 'w' : case 'W' : return number + '週'; default : return number; } }, relativeTime : { future : '%s內', past : '%s前', s : '幾秒', ss : '%d 秒', m : '1 分鐘', mm : '%d 分鐘', h : '1 小時', hh : '%d 小時', d : '1 天', dd : '%d 天', M : '1 個月', MM : '%d 個月', y : '1 年', yy : '%d 年' } }); moment.locale('en'); return moment; })));
require(['jquery'], function($) { 'use strict'; $(function() { setTimeout(function() { // emulates 'document ready state' for selenium tests document['page-rendered'] = true; }, 100); }); });
(function() { "use strict"; angular.module('angular-carousel') .service('DeviceCapabilities', function() { // TODO: merge in a single function // detect supported CSS property function detectTransformProperty() { var transformProperty = 'transform', safariPropertyHack = 'webkitTransform'; if (typeof document.body.style[transformProperty] !== 'undefined') { ['webkit', 'moz', 'o', 'ms'].every(function (prefix) { var e = '-' + prefix + '-transform'; if (typeof document.body.style[e] !== 'undefined') { transformProperty = e; return false; } return true; }); } else if (typeof document.body.style[safariPropertyHack] !== 'undefined') { transformProperty = '-webkit-transform'; } else { transformProperty = undefined; } return transformProperty; } //Detect support of translate3d function detect3dSupport() { var el = document.createElement('p'), has3d, transforms = { 'webkitTransform': '-webkit-transform', 'msTransform': '-ms-transform', 'transform': 'transform' }; // Add it to the body to get the computed style document.body.insertBefore(el, null); for (var t in transforms) { if (el.style[t] !== undefined) { el.style[t] = 'translate3d(1px,1px,1px)'; has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]); } } document.body.removeChild(el); return (has3d !== undefined && has3d.length > 0 && has3d !== "none"); } return { has3d: detect3dSupport(), transformProperty: detectTransformProperty() }; }) .service('computeCarouselSlideStyle', function(DeviceCapabilities) { // compute transition transform properties for a given slide and global offset return function(slideIndex, offset, transitionType) { var style = { display: 'inline-block' }, opacity, absoluteLeft = (slideIndex * 100) + offset, slideTransformValue = DeviceCapabilities.has3d ? 'translate3d(' + absoluteLeft + '%, 0, 0)' : 'translate3d(' + absoluteLeft + '%, 0)', distance = ((100 - Math.abs(absoluteLeft)) / 100); if (!DeviceCapabilities.transformProperty) { // fallback to default slide if transformProperty is not available style['margin-left'] = absoluteLeft + '%'; } else { if (transitionType == 'fadeAndSlide') { style[DeviceCapabilities.transformProperty] = slideTransformValue; opacity = 0; if (Math.abs(absoluteLeft) < 100) { opacity = 0.3 + distance * 0.7; } style.opacity = opacity; } else if (transitionType == 'hexagon') { var transformFrom = 100, degrees = 0, maxDegrees = 60 * (distance - 1); transformFrom = offset < (slideIndex * -100) ? 100 : 0; degrees = offset < (slideIndex * -100) ? maxDegrees : -maxDegrees; style[DeviceCapabilities.transformProperty] = slideTransformValue + ' ' + 'rotateY(' + degrees + 'deg)'; style[DeviceCapabilities.transformProperty + '-origin'] = transformFrom + '% 50%'; } else if (transitionType == 'zoom') { style[DeviceCapabilities.transformProperty] = slideTransformValue; var scale = 1; if (Math.abs(absoluteLeft) < 100) { scale = 1 + ((1 - distance) * 2); } style[DeviceCapabilities.transformProperty] += ' scale(' + scale + ')'; style[DeviceCapabilities.transformProperty + '-origin'] = '50% 50%'; opacity = 0; if (Math.abs(absoluteLeft) < 100) { opacity = 0.3 + distance * 0.7; } style.opacity = opacity; } else { style[DeviceCapabilities.transformProperty] = slideTransformValue; } } return style; }; }) .service('createStyleString', function() { return function(object) { var styles = []; angular.forEach(object, function(value, key) { styles.push(key + ':' + value); }); return styles.join(';'); }; }) .directive('rnCarousel', ['$swipe', '$window', '$document', '$parse', '$compile', '$timeout', '$interval', 'computeCarouselSlideStyle', 'createStyleString', 'Tweenable', function($swipe, $window, $document, $parse, $compile, $timeout, $interval, computeCarouselSlideStyle, createStyleString, Tweenable) { // internal ids to allow multiple instances var carouselId = 0, // in absolute pixels, at which distance the slide stick to the edge on release rubberTreshold = 3; var requestAnimationFrame = $window.requestAnimationFrame || $window.webkitRequestAnimationFrame || $window.mozRequestAnimationFrame; function getItemIndex(collection, target, defaultIndex) { var result = defaultIndex; collection.every(function(item, index) { if (angular.equals(item, target)) { result = index; return false; } return true; }); return result; } return { restrict: 'A', scope: true, compile: function(tElement, tAttributes) { // use the compile phase to customize the DOM var firstChild = tElement[0].querySelector('li'), firstChildAttributes = (firstChild) ? firstChild.attributes : [], isRepeatBased = false, isBuffered = false, repeatItem, repeatCollection; // try to find an ngRepeat expression // at this point, the attributes are not yet normalized so we need to try various syntax ['ng-repeat', 'data-ng-repeat', 'ng:repeat', 'x-ng-repeat'].every(function(attr) { var repeatAttribute = firstChildAttributes[attr]; if (angular.isDefined(repeatAttribute)) { // ngRepeat regexp extracted from angular 1.2.7 src var exprMatch = repeatAttribute.value.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/), trackProperty = exprMatch[3]; repeatItem = exprMatch[1]; repeatCollection = exprMatch[2]; if (repeatItem) { if (angular.isDefined(tAttributes['rnCarouselBuffered'])) { // update the current ngRepeat expression and add a slice operator if buffered isBuffered = true; repeatAttribute.value = repeatItem + ' in ' + repeatCollection + '|carouselSlice:carouselBufferIndex:carouselBufferSize'; if (trackProperty) { repeatAttribute.value += ' track by ' + trackProperty; } } isRepeatBased = true; return false; } } return true; }); return function(scope, iElement, iAttributes, containerCtrl) { carouselId++; var defaultOptions = { transitionType: iAttributes.rnCarouselTransition || 'slide', transitionEasing: iAttributes.rnCarouselEasing || 'easeTo', transitionDuration: parseInt(iAttributes.rnCarouselDuration, 10) || 300, isSequential: true, autoSlideDuration: 3, bufferSize: 5, /* in container % how much we need to drag to trigger the slide change */ moveTreshold: 0.1 }; // TODO var options = angular.extend({}, defaultOptions); var pressed, startX, isIndexBound = false, offset = 0, destination, swipeMoved = false, //animOnIndexChange = true, currentSlides = [], elWidth = null, elX = null, animateTransitions = true, intialState = true, animating = false, mouseUpBound = false, locked = false; $swipe.bind(iElement, { start: swipeStart, move: swipeMove, end: swipeEnd, cancel: function(event) { swipeEnd({}, event); } }); function getSlidesDOM() { return iElement[0].querySelectorAll('ul[rn-carousel] > li'); } function documentMouseUpEvent(event) { // in case we click outside the carousel, trigger a fake swipeEnd swipeMoved = true; swipeEnd({ x: event.clientX, y: event.clientY }, event); } function updateSlidesPosition(offset) { // manually apply transformation to carousel childrens // todo : optim : apply only to visible items var x = scope.carouselBufferIndex * 100 + offset; angular.forEach(getSlidesDOM(), function(child, index) { child.style.cssText = createStyleString(computeCarouselSlideStyle(index, x, options.transitionType)); }); } scope.nextSlide = function(slideOptions) { var index = scope.carouselIndex + 1; if (index > currentSlides.length - 1) { index = 0; } if (!locked) { goToSlide(index, slideOptions); } }; scope.prevSlide = function(slideOptions) { var index = scope.carouselIndex - 1; if (index < 0) { index = currentSlides.length - 1; } goToSlide(index, slideOptions); }; function goToSlide(index, slideOptions) { //console.log('goToSlide', arguments); // move a to the given slide index if (index === undefined) { index = scope.carouselIndex; } slideOptions = slideOptions || {}; if (slideOptions.animate === false || options.transitionType === 'none') { locked = false; offset = index * -100; scope.carouselIndex = index; updateBufferIndex(); return; } locked = true; var tweenable = new Tweenable(); tweenable.tween({ from: { 'x': offset }, to: { 'x': index * -100 }, duration: options.transitionDuration, easing: options.transitionEasing, step: function(state) { updateSlidesPosition(state.x); }, finish: function() { scope.$apply(function() { scope.carouselIndex = index; offset = index * -100; updateBufferIndex(); $timeout(function () { locked = false; }, 0, false); }); } }); } function getContainerWidth() { var rect = iElement[0].getBoundingClientRect(); return rect.width ? rect.width : rect.right - rect.left; } function updateContainerWidth() { elWidth = getContainerWidth(); } function bindMouseUpEvent() { if (!mouseUpBound) { mouseUpBound = true; $document.bind('mouseup', documentMouseUpEvent); } } function unbindMouseUpEvent() { if (mouseUpBound) { mouseUpBound = false; $document.unbind('mouseup', documentMouseUpEvent); } } function swipeStart(coords, event) { // console.log('swipeStart', coords, event); if (locked || currentSlides.length <= 1) { return; } updateContainerWidth(); elX = iElement[0].querySelector('li').getBoundingClientRect().left; pressed = true; startX = coords.x; return false; } function swipeMove(coords, event) { //console.log('swipeMove', coords, event); var x, delta; bindMouseUpEvent(); if (pressed) { x = coords.x; delta = startX - x; if (delta > 2 || delta < -2) { swipeMoved = true; var moveOffset = offset + (-delta * 100 / elWidth); updateSlidesPosition(moveOffset); } } return false; } var init = true; scope.carouselIndex = 0; if (!isRepeatBased) { // fake array when no ng-repeat currentSlides = []; angular.forEach(getSlidesDOM(), function(node, index) { currentSlides.push({id: index}); }); } if (iAttributes.rnCarouselControls!==undefined) { // dont use a directive for this var nextSlideIndexCompareValue = isRepeatBased ? repeatCollection.replace('::', '') + '.length - 1' : currentSlides.length - 1; var tpl = '<div class="rn-carousel-controls">\n' + ' <span class="rn-carousel-control rn-carousel-control-prev" ng-click="prevSlide()" ng-if="carouselIndex > 0"></span>\n' + ' <span class="rn-carousel-control rn-carousel-control-next" ng-click="nextSlide()" ng-if="carouselIndex < ' + nextSlideIndexCompareValue + '"></span>\n' + '</div>'; iElement.append($compile(angular.element(tpl))(scope)); } if (iAttributes.rnCarouselAutoSlide!==undefined) { var duration = parseInt(iAttributes.rnCarouselAutoSlide, 10) || options.autoSlideDuration; scope.autoSlide = function() { if (scope.autoSlider) { $interval.cancel(scope.autoSlider); scope.autoSlider = null; } scope.autoSlider = $interval(function() { if (!locked && !pressed) { scope.nextSlide(); } }, duration * 1000); }; } if (iAttributes.rnCarouselIndex) { var updateParentIndex = function(value) { indexModel.assign(scope.$parent, value); }; var indexModel = $parse(iAttributes.rnCarouselIndex); if (angular.isFunction(indexModel.assign)) { /* check if this property is assignable then watch it */ scope.$watch('carouselIndex', function(newValue) { updateParentIndex(newValue); }); scope.$parent.$watch(indexModel, function(newValue, oldValue) { if (newValue !== undefined && newValue !== null) { if (currentSlides && newValue >= currentSlides.length) { newValue = currentSlides.length - 1; updateParentIndex(newValue); } else if (currentSlides && newValue < 0) { newValue = 0; updateParentIndex(newValue); } if (!locked) { goToSlide(newValue, { animate: !init }); } init = false; } }); isIndexBound = true; } else if (!isNaN(iAttributes.rnCarouselIndex)) { /* if user just set an initial number, set it */ goToSlide(parseInt(iAttributes.rnCarouselIndex, 10), { animate: false }); } } else { goToSlide(0, { animate: !init }); init = false; } if (iAttributes.rnCarouselLocked) { scope.$watch(iAttributes.rnCarouselLocked, function(newValue, oldValue) { // only bind swipe when it's not switched off if(newValue === true) { locked = true; } else { locked = false; } }); } if (isRepeatBased) { // use rn-carousel-deep-watch to fight the Angular $watchCollection weakness : https://github.com/angular/angular.js/issues/2621 // optional because it have some performance impacts (deep watch) var deepWatch = (iAttributes.rnCarouselDeepWatch!==undefined); scope[deepWatch?'$watch':'$watchCollection'](repeatCollection, function(newValue, oldValue) { //console.log('repeatCollection', currentSlides); currentSlides = newValue; // if deepWatch ON ,manually compare objects to guess the new position if (deepWatch && angular.isArray(newValue)) { var activeElement = oldValue[scope.carouselIndex]; var newIndex = getItemIndex(newValue, activeElement, scope.carouselIndex); goToSlide(newIndex, {animate: false}); } else { goToSlide(scope.carouselIndex, {animate: false}); } }, true); } function swipeEnd(coords, event, forceAnimation) { // console.log('swipeEnd', 'scope.carouselIndex', scope.carouselIndex); // Prevent clicks on buttons inside slider to trigger "swipeEnd" event on touchend/mouseup if (event && !swipeMoved) { return; } unbindMouseUpEvent(); pressed = false; swipeMoved = false; destination = startX - coords.x; if (destination===0) { return; } if (locked) { return; } offset += (-destination * 100 / elWidth); if (options.isSequential) { var minMove = options.moveTreshold * elWidth, absMove = -destination, slidesMove = -Math[absMove >= 0 ? 'ceil' : 'floor'](absMove / elWidth), shouldMove = Math.abs(absMove) > minMove; if (currentSlides && (slidesMove + scope.carouselIndex) >= currentSlides.length) { slidesMove = currentSlides.length - 1 - scope.carouselIndex; } if ((slidesMove + scope.carouselIndex) < 0) { slidesMove = -scope.carouselIndex; } var moveOffset = shouldMove ? slidesMove : 0; destination = (scope.carouselIndex + moveOffset); goToSlide(destination); } else { scope.$apply(function() { scope.carouselIndex = parseInt(-offset / 100, 10); updateBufferIndex(); }); } } scope.$on('$destroy', function() { unbindMouseUpEvent(); }); scope.carouselBufferIndex = 0; scope.carouselBufferSize = options.bufferSize; function updateBufferIndex() { // update and cap te buffer index var bufferIndex = 0; var bufferEdgeSize = (scope.carouselBufferSize - 1) / 2; if (isBuffered) { if (scope.carouselIndex <= bufferEdgeSize) { // first buffer part bufferIndex = 0; } else if (currentSlides && currentSlides.length < scope.carouselBufferSize) { // smaller than buffer bufferIndex = 0; } else if (currentSlides && scope.carouselIndex > currentSlides.length - scope.carouselBufferSize) { // last buffer part bufferIndex = currentSlides.length - scope.carouselBufferSize; } else { // compute buffer start bufferIndex = scope.carouselIndex - bufferEdgeSize; } scope.carouselBufferIndex = bufferIndex; $timeout(function() { updateSlidesPosition(offset); }, 0, false); } else { $timeout(function() { updateSlidesPosition(offset); }, 0, false); } } function onOrientationChange() { updateContainerWidth(); goToSlide(); } // handle orientation change var winEl = angular.element($window); winEl.bind('orientationchange', onOrientationChange); winEl.bind('resize', onOrientationChange); scope.$on('$destroy', function() { unbindMouseUpEvent(); winEl.unbind('orientationchange', onOrientationChange); winEl.unbind('resize', onOrientationChange); }); }; } }; } ]); })();
const set = require('regenerate')(0x1CDA); set.addRange(0x951, 0x952).addRange(0x964, 0x965).addRange(0xD00, 0xD03).addRange(0xD05, 0xD0C).addRange(0xD0E, 0xD10).addRange(0xD12, 0xD44).addRange(0xD46, 0xD48).addRange(0xD4A, 0xD4F).addRange(0xD54, 0xD63).addRange(0xD66, 0xD7F).addRange(0xA830, 0xA832); module.exports = set;