code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
/**
* Copyright (c) 2014, 2016, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
"use strict";var l={"EU":["EU","Evropa"]};(this?this:window)['DvtBaseMapManager']['_UNPROCESSED_MAPS'][2].push(["europe","continent",l]); | JDT2016-Hackathon/hr | src/main/resources/static/js/libs/oj/v2.0.1/resources/internal-deps/dvt/thematicMap/resourceBundles/EuropeContinentBundle_cs.js | JavaScript | apache-2.0 | 259 |
Proj4js.defs["EPSG:4960"] = ""; | debard/georchestra-ird | mapfishapp/src/main/webapp/lib/proj4js/lib/defs/EPSG4960.js | JavaScript | gpl-3.0 | 31 |
/**
* State-based routing for AngularJS 1.x
* @version v1.0.5
* @link https://ui-router.github.io
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('angular')) :
typeof define === 'function' && define.amd ? define(['exports', 'angular'], factory) :
(factory((global['@uirouter/angularjs-state-events'] = global['@uirouter/angularjs-state-events'] || {}),global.angular));
}(this, (function (exports,ng_from_import) { 'use strict';
var ng_from_global = angular;
var ng = (ng_from_import && ng_from_import.module) ? ng_from_import : ng_from_global;
/**
* # Legacy state events
*
* Polyfill implementation of the UI-Router 0.2.x state events.
*
* The 0.2.x state events are deprecated. We recommend moving to Transition Hooks instead, as they
* provide much more flexibility, support async, and provide the context (the Transition, etc) necessary
* to implement meaningful application behaviors.
*
* To enable these state events, include the `stateEvents.js` file in your project, e.g.,
* ```
* <script src="stateEvents.js"></script>
* ```
* and also make sure you depend on the `ui.router.state.events` angular module, e.g.,
* ```
* angular.module("myApplication", ['ui.router', 'ui.router.state.events']
* ```
*
* @module ng1_state_events
*/ /** */
/**
* An event broadcast on `$rootScope` when the state transition **begins**.
*
* ### Deprecation warning: use [[TransitionService.onStart]] instead
*
* You can use `event.preventDefault()`
* to prevent the transition from happening and then the transition promise will be
* rejected with a `'transition prevented'` value.
*
* Additional arguments to the event handler are provided:
* - `toState`: the Transition Target state
* - `toParams`: the Transition Target Params
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `options`: any Transition Options
* - `$transition$`: the [[Transition]]
*
* #### Example:
* ```js
* $rootScope.$on('$stateChangeStart', function(event, transition) {
* event.preventDefault();
* // transitionTo() promise will be rejected with
* // a 'transition prevented' error
* })
* ```
*
* @event $stateChangeStart
* @deprecated
*/
var $stateChangeStart;
/**
* An event broadcast on `$rootScope` if a transition is **cancelled**.
*
* ### Deprecation warning: use [[TransitionService.onStart]] instead
*
* Additional arguments to the event handler are provided:
* - `toState`: the Transition Target state
* - `toParams`: the Transition Target Params
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `options`: any Transition Options
* - `$transition$`: the [[Transition]] that was cancelled
*
* @event $stateChangeCancel
* @deprecated
*/
var $stateChangeCancel;
/**
* An event broadcast on `$rootScope` once the state transition is **complete**.
*
* ### Deprecation warning: use [[TransitionService.onStart]] and [[Transition.promise]], or [[Transition.onSuccess]]
*
* Additional arguments to the event handler are provided:
* - `toState`: the Transition Target state
* - `toParams`: the Transition Target Params
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `options`: any Transition Options
* - `$transition$`: the [[Transition]] that just succeeded
*
* @event $stateChangeSuccess
* @deprecated
*/
var $stateChangeSuccess;
/**
* An event broadcast on `$rootScope` when an **error occurs** during transition.
*
* ### Deprecation warning: use [[TransitionService.onStart]] and [[Transition.promise]], or [[Transition.onError]]
*
* It's important to note that if you
* have any errors in your resolve functions (javascript errors, non-existent services, etc)
* they will not throw traditionally. You must listen for this $stateChangeError event to
* catch **ALL** errors.
*
* Additional arguments to the event handler are provided:
* - `toState`: the Transition Target state
* - `toParams`: the Transition Target Params
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `error`: The reason the transition errored.
* - `options`: any Transition Options
* - `$transition$`: the [[Transition]] that errored
*
* @event $stateChangeError
* @deprecated
*/
var $stateChangeError;
/**
* An event broadcast on `$rootScope` when a requested state **cannot be found** using the provided state name.
*
* ### Deprecation warning: use [[StateService.onInvalid]] instead
*
* The event is broadcast allowing any handlers a single chance to deal with the error (usually by
* lazy-loading the unfound state). A `TargetState` object is passed to the listener handler,
* you can see its properties in the example. You can use `event.preventDefault()` to abort the
* transition and the promise returned from `transitionTo()` will be rejected with a
* `'transition aborted'` error.
*
* Additional arguments to the event handler are provided:
* - `unfoundState` Unfound State information. Contains: `to, toParams, options` properties.
* - `fromState`: the state the transition is coming from
* - `fromParams`: the parameters from the state the transition is coming from
* - `options`: any Transition Options
*
* #### Example:
* ```js
* // somewhere, assume lazy.state has not been defined
* $state.go("lazy.state", { a: 1, b: 2 }, { inherit: false });
*
* // somewhere else
* $scope.$on('$stateNotFound', function(event, transition) {
* function(event, unfoundState, fromState, fromParams){
* console.log(unfoundState.to); // "lazy.state"
* console.log(unfoundState.toParams); // {a:1, b:2}
* console.log(unfoundState.options); // {inherit:false} + default options
* });
* ```
*
* @event $stateNotFound
* @deprecated
*/
var $stateNotFound;
(function () {
var isFunction = ng.isFunction, isString = ng.isString;
function applyPairs(memo, keyValTuple) {
var key, value;
if (Array.isArray(keyValTuple))
key = keyValTuple[0], value = keyValTuple[1];
if (!isString(key))
throw new Error("invalid parameters to applyPairs");
memo[key] = value;
return memo;
}
function stateChangeStartHandler($transition$) {
if (!$transition$.options().notify || !$transition$.valid() || $transition$.ignored())
return;
var $injector = $transition$.injector();
var $stateEvents = $injector.get('$stateEvents');
var $rootScope = $injector.get('$rootScope');
var $state = $injector.get('$state');
var $urlRouter = $injector.get('$urlRouter');
var enabledEvents = $stateEvents.provider.enabled();
var toParams = $transition$.params("to");
var fromParams = $transition$.params("from");
if (enabledEvents.$stateChangeSuccess) {
var startEvent = $rootScope.$broadcast('$stateChangeStart', $transition$.to(), toParams, $transition$.from(), fromParams, $transition$.options(), $transition$);
if (startEvent.defaultPrevented) {
if (enabledEvents.$stateChangeCancel) {
$rootScope.$broadcast('$stateChangeCancel', $transition$.to(), toParams, $transition$.from(), fromParams, $transition$.options(), $transition$);
}
//Don't update and resync url if there's been a new transition started. see issue #2238, #600
if ($state.transition == null)
$urlRouter.update();
return false;
}
// right after global state is updated
var successOpts = { priority: 9999 };
$transition$.onSuccess({}, function () {
$rootScope.$broadcast('$stateChangeSuccess', $transition$.to(), toParams, $transition$.from(), fromParams, $transition$.options(), $transition$);
}, successOpts);
}
if (enabledEvents.$stateChangeError) {
$transition$.promise["catch"](function (error) {
if (error && (error.type === 2 /* RejectType.SUPERSEDED */ || error.type === 3 /* RejectType.ABORTED */))
return;
var evt = $rootScope.$broadcast('$stateChangeError', $transition$.to(), toParams, $transition$.from(), fromParams, error, $transition$.options(), $transition$);
if (!evt.defaultPrevented) {
$urlRouter.update();
}
});
}
}
stateNotFoundHandler.$inject = ['$to$', '$from$', '$state', '$rootScope', '$urlRouter'];
function stateNotFoundHandler($to$, $from$, injector) {
var $state = injector.get('$state');
var $rootScope = injector.get('$rootScope');
var $urlRouter = injector.get('$urlRouter');
var redirect = { to: $to$.identifier(), toParams: $to$.params(), options: $to$.options() };
var e = $rootScope.$broadcast('$stateNotFound', redirect, $from$.state(), $from$.params());
if (e.defaultPrevented || e.retry)
$urlRouter.update();
function redirectFn() {
return $state.target(redirect.to, redirect.toParams, redirect.options);
}
if (e.defaultPrevented) {
return false;
}
else if (e.retry || !!$state.get(redirect.to)) {
return e.retry && isFunction(e.retry.then) ? e.retry.then(redirectFn) : redirectFn();
}
}
$StateEventsProvider.$inject = ['$stateProvider'];
function $StateEventsProvider($stateProvider) {
$StateEventsProvider.prototype.instance = this;
var runtime = false;
var allEvents = ['$stateChangeStart', '$stateNotFound', '$stateChangeSuccess', '$stateChangeError'];
var enabledStateEvents = allEvents.map(function (e) { return [e, true]; }).reduce(applyPairs, {});
function assertNotRuntime() {
if (runtime)
throw new Error("Cannot enable events at runtime (use $stateEventsProvider");
}
/**
* Enables the deprecated UI-Router 0.2.x State Events
* [ '$stateChangeStart', '$stateNotFound', '$stateChangeSuccess', '$stateChangeError' ]
*/
this.enable = function () {
var events = [];
for (var _i = 0; _i < arguments.length; _i++) {
events[_i] = arguments[_i];
}
assertNotRuntime();
if (!events || !events.length)
events = allEvents;
events.forEach(function (event) { return enabledStateEvents[event] = true; });
};
/**
* Disables the deprecated UI-Router 0.2.x State Events
* [ '$stateChangeStart', '$stateNotFound', '$stateChangeSuccess', '$stateChangeError' ]
*/
this.disable = function () {
var events = [];
for (var _i = 0; _i < arguments.length; _i++) {
events[_i] = arguments[_i];
}
assertNotRuntime();
if (!events || !events.length)
events = allEvents;
events.forEach(function (event) { return delete enabledStateEvents[event]; });
};
this.enabled = function () { return enabledStateEvents; };
this.$get = $get;
$get.$inject = ['$transitions'];
function $get($transitions) {
runtime = true;
if (enabledStateEvents["$stateNotFound"])
$stateProvider.onInvalid(stateNotFoundHandler);
if (enabledStateEvents.$stateChangeStart)
$transitions.onBefore({}, stateChangeStartHandler, { priority: 1000 });
return {
provider: $StateEventsProvider.prototype.instance
};
}
}
ng.module('ui.router.state.events', ['ui.router.state'])
.provider("$stateEvents", $StateEventsProvider)
.run(['$stateEvents', function ($stateEvents) {
}]);
})();
exports.$stateChangeStart = $stateChangeStart;
exports.$stateChangeCancel = $stateChangeCancel;
exports.$stateChangeSuccess = $stateChangeSuccess;
exports.$stateChangeError = $stateChangeError;
exports.$stateNotFound = $stateNotFound;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=stateEvents.js.map
| angel-94/CALIFICACIONES | src/main/resources/static/app/bower_components/angular-ui-router/release/stateEvents.js | JavaScript | apache-2.0 | 12,613 |
var searchData=
[
['pcm_5fbytes_5fwritten',['pcm_bytes_written',['../structguac__audio__stream.html#a3db3ad0af5385d4ea20daece3e4e6d05',1,'guac_audio_stream']]],
['pcm_5fdata',['pcm_data',['../structguac__audio__stream.html#a7cfb92e31f72f1748aa0b3611ffdb0c8',1,'guac_audio_stream']]],
['pipe_5fhandler',['pipe_handler',['../structguac__client.html#acd62220caeae9c5da0291a30e29d5dfa',1,'guac_client']]],
['plugin_2dconstants_2eh',['plugin-constants.h',['../plugin-constants_8h.html',1,'']]],
['plugin_2dtypes_2eh',['plugin-types.h',['../plugin-types_8h.html',1,'']]],
['plugin_2eh',['plugin.h',['../plugin_8h.html',1,'']]],
['pool_2dtypes_2eh',['pool-types.h',['../pool-types_8h.html',1,'']]],
['pool_2eh',['pool.h',['../pool_8h.html',1,'']]],
['protocol_2dtypes_2eh',['protocol-types.h',['../protocol-types_8h.html',1,'']]],
['protocol_2eh',['protocol.h',['../protocol_8h.html',1,'']]]
];
| mike-jumper/incubator-guacamole-website | doc/0.9.7/libguac/search/all_d.js | JavaScript | apache-2.0 | 908 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* Function's scope chain is started when it is declared
*
* @path ch13/13.2/S13.2.2_A19_T2.js
* @description Function is declared in the object scope. Using "with" statement
*/
var a = 1;
var __obj = {a:2};
with (__obj)
{
result = (function(){return a;})();
}
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (result !== 2) {
$ERROR('#1: result === 2. Actual: result ==='+result);
}
//
//////////////////////////////////////////////////////////////////////////////
| hippich/typescript | tests/Fidelity/test262/suite/ch13/13.2/S13.2.2_A19_T2.js | JavaScript | apache-2.0 | 660 |
//// [objectRest2.ts]
// test for #12203
declare function connectionFromArray(objects: number, args: any): {};
function rootConnection(name: string) {
return {
resolve: async (context, args) => {
const { objects } = await { objects: 12 };
return {
...connectionFromArray(objects, args)
};
}
};
}
rootConnection('test');
//// [objectRest2.js]
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
function rootConnection(name) {
return {
resolve: (context, args) => __awaiter(this, void 0, void 0, function* () {
const { objects } = yield { objects: 12 };
return Object.assign({}, connectionFromArray(objects, args));
})
};
}
rootConnection('test');
| basarat/TypeScript | tests/baselines/reference/objectRest2.js | JavaScript | apache-2.0 | 1,307 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is JavaScript Engine testing utilities.
*
* The Initial Developer of the Original Code is
* Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2006
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Jesse Ruderman
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
//-----------------------------------------------------------------------------
var BUGNUMBER = 352742;
var summary = 'Array filter on {valueOf: Function}';
var actual = '';
var expect = '';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
print('If the test harness fails, this test fails.');
expect = 4;
z = {valueOf: Function};
actual = 2;
try {
[11].filter(z);
}
catch(e)
{
actual = 3;
print(e);
}
actual = 4;
reportCompare(expect, actual, summary);
exitFunc ('test');
}
| darkrsw/safe | tests/parser_tests/js/src/tests/js1_6/Array/regress-352742-01.js | JavaScript | bsd-3-clause | 2,528 |
$(function () {
'use strict';
var crossOriginImage = 'http://fengyuanchen.github.io/cropper/img/picture.jpg';
var $image = $(window.createCropperImage({
src: crossOriginImage
}));
$image.cropper({
built: function () {
var cropper = $image.data('cropper');
QUnit.test('options.checkCrossOrigin: true', function (assert) {
assert.ok(cropper.$clone.attr('crossOrigin') === 'anonymous');
assert.ok(cropper.$clone.attr('src').indexOf('timestamp') !== -1);
});
}
});
(function () {
var $image = $(window.createCropperImage({
src: crossOriginImage
}));
$image.cropper({
checkCrossOrigin: false,
built: function () {
var cropper = $image.data('cropper');
QUnit.test('options.checkCrossOrigin: false', function (assert) {
assert.ok(cropper.$clone.attr('crossOrigin') === undefined);
assert.ok(cropper.$clone.attr('src').indexOf('timestamp') === -1);
});
}
});
})();
(function () {
var $image = $(window.createCropperImage({
src: crossOriginImage,
crossOrigin: 'anonymous'
}));
$image.cropper({
built: function () {
var cropper = $image.data('cropper');
QUnit.test('options.checkCrossOrigin: exists crossOrigin attribute', function (assert) {
assert.ok(cropper.$clone.attr('crossOrigin') === 'anonymous');
assert.ok(cropper.$clone.attr('src').indexOf('timestamp') === -1);
});
}
});
})();
});
| lalo6666/crm | web/public/js/cropper-2.3.0/test/options/checkCrossOrigin.js | JavaScript | mit | 1,560 |
/*
This file is part of Ext JS 4.2
Copyright (c) 2011-2013 Sencha Inc
Contact: http://www.sencha.com/contact
GNU General Public License Usage
This file may be used under the terms of the GNU General Public License version 3.0 as
published by the Free Software Foundation and appearing in the file LICENSE included in the
packaging of this file.
Please review the following information to ensure the GNU General Public License version 3.0
requirements will be met: http://www.gnu.org/copyleft/gpl.html.
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-03-11 22:33:40 (aed16176e68b5e8aa1433452b12805c0ad913836)
*/
/**
* This is a base class for layouts that contain a single item that automatically expands to fill the layout's
* container. This class is intended to be extended or created via the layout:'fit'
* {@link Ext.container.Container#layout} config, and should generally not need to be created directly via the new keyword.
*
* Fit layout does not have any direct config options (other than inherited ones). To fit a panel to a container using
* Fit layout, simply set `layout: 'fit'` on the container and add a single panel to it.
*
* @example
* Ext.create('Ext.panel.Panel', {
* title: 'Fit Layout',
* width: 300,
* height: 150,
* layout:'fit',
* items: {
* title: 'Inner Panel',
* html: 'This is the inner panel content',
* bodyPadding: 20,
* border: false
* },
* renderTo: Ext.getBody()
* });
*
* If the container has multiple items, all of the items will all be equally sized. This is usually not
* desired, so to avoid this, place only a **single** item in the container. This sizing of all items
* can be used to provide a background {@link Ext.Img image} that is "behind" another item
* such as a {@link Ext.view.View dataview} if you also absolutely position the items.
*/
Ext.define('Ext.layout.container.Fit', {
/* Begin Definitions */
extend: 'Ext.layout.container.Container',
alternateClassName: 'Ext.layout.FitLayout',
alias: 'layout.fit',
/* End Definitions */
itemCls: Ext.baseCSSPrefix + 'fit-item',
targetCls: Ext.baseCSSPrefix + 'layout-fit',
type: 'fit',
/**
* @cfg {Object} defaultMargins
* If the individual contained items do not have a margins property specified or margin specified via CSS, the
* default margins from this property will be applied to each item.
*
* This property may be specified as an object containing margins to apply in the format:
*
* {
* top: (top margin),
* right: (right margin),
* bottom: (bottom margin),
* left: (left margin)
* }
*
* This property may also be specified as a string containing space-separated, numeric margin values. The order of
* the sides associated with each value matches the way CSS processes margin values:
*
* - If there is only one value, it applies to all sides.
* - If there are two values, the top and bottom borders are set to the first value and the right and left are
* set to the second.
* - If there are three values, the top is set to the first value, the left and right are set to the second,
* and the bottom is set to the third.
* - If there are four values, they apply to the top, right, bottom, and left, respectively.
*
*/
defaultMargins: {
top: 0,
right: 0,
bottom: 0,
left: 0
},
manageMargins: true,
sizePolicies: {
0: { readsWidth: 1, readsHeight: 1, setsWidth: 0, setsHeight: 0 },
1: { readsWidth: 0, readsHeight: 1, setsWidth: 1, setsHeight: 0 },
2: { readsWidth: 1, readsHeight: 0, setsWidth: 0, setsHeight: 1 },
3: { readsWidth: 0, readsHeight: 0, setsWidth: 1, setsHeight: 1 }
},
getItemSizePolicy: function (item, ownerSizeModel) {
// this layout's sizePolicy is derived from its owner's sizeModel:
var sizeModel = ownerSizeModel || this.owner.getSizeModel(),
mode = (sizeModel.width.shrinkWrap ? 0 : 1) |
(sizeModel.height.shrinkWrap ? 0 : 2);
return this.sizePolicies[mode];
},
beginLayoutCycle: function (ownerContext, firstCycle) {
var me = this,
// determine these before the lastSizeModels get updated:
resetHeight = me.lastHeightModel && me.lastHeightModel.calculated,
resetWidth = me.lastWidthModel && me.lastWidthModel.calculated,
resetSizes = resetWidth || resetHeight,
maxChildMinHeight = 0, maxChildMinWidth = 0,
c, childItems, i, item, length, margins, minHeight, minWidth, style, undef;
me.callParent(arguments);
// Clear any dimensions which we set before calculation, in case the current
// settings affect the available size. This particularly effects self-sizing
// containers such as fields, in which the target element is naturally sized,
// and should not be stretched by a sized child item.
if (resetSizes && ownerContext.targetContext.el.dom.tagName.toUpperCase() != 'TD') {
resetSizes = resetWidth = resetHeight = false;
}
childItems = ownerContext.childItems;
length = childItems.length;
for (i = 0; i < length; ++i) {
item = childItems[i];
// On the firstCycle, we determine the max of the minWidth/Height of the items
// since these can cause the container to grow scrollbars despite our attempts
// to fit the child to the container.
if (firstCycle) {
c = item.target;
minHeight = c.minHeight;
minWidth = c.minWidth;
if (minWidth || minHeight) {
margins = item.marginInfo || item.getMarginInfo();
// if the child item has undefined minWidth/Height, these will become
// NaN by adding the margins...
minHeight += margins.height;
minWidth += margins.height;
// if the child item has undefined minWidth/Height, these comparisons
// will evaluate to false... that is, "0 < NaN" == false...
if (maxChildMinHeight < minHeight) {
maxChildMinHeight = minHeight;
}
if (maxChildMinWidth < minWidth) {
maxChildMinWidth = minWidth;
}
}
}
if (resetSizes) {
style = item.el.dom.style;
if (resetHeight) {
style.height = '';
}
if (resetWidth) {
style.width = '';
}
}
}
if (firstCycle) {
ownerContext.maxChildMinHeight = maxChildMinHeight;
ownerContext.maxChildMinWidth = maxChildMinWidth;
}
// Cache the overflowX/Y flags, but make them false in shrinkWrap mode (since we
// won't be triggering overflow in that case) and false if we have no minSize (so
// no child to trigger an overflow).
c = ownerContext.target;
ownerContext.overflowX = (!ownerContext.widthModel.shrinkWrap &&
ownerContext.maxChildMinWidth &&
c.scrollFlags.x) || undef;
ownerContext.overflowY = (!ownerContext.heightModel.shrinkWrap &&
ownerContext.maxChildMinHeight &&
c.scrollFlags.y) || undef;
},
calculate : function (ownerContext) {
var me = this,
childItems = ownerContext.childItems,
length = childItems.length,
containerSize = me.getContainerSize(ownerContext),
info = {
length: length,
ownerContext: ownerContext,
targetSize: containerSize
},
shrinkWrapWidth = ownerContext.widthModel.shrinkWrap,
shrinkWrapHeight = ownerContext.heightModel.shrinkWrap,
overflowX = ownerContext.overflowX,
overflowY = ownerContext.overflowY,
scrollbars, scrollbarSize, padding, i, contentWidth, contentHeight;
if (overflowX || overflowY) {
// If we have children that have minHeight/Width, we may be forced to overflow
// and gain scrollbars. If so, we want to remove their space from the other
// axis so that we fit things inside the scrollbars rather than under them.
scrollbars = me.getScrollbarsNeeded(
overflowX && containerSize.width, overflowY && containerSize.height,
ownerContext.maxChildMinWidth, ownerContext.maxChildMinHeight);
if (scrollbars) {
scrollbarSize = Ext.getScrollbarSize();
if (scrollbars & 1) { // if we need the hscrollbar, remove its height
containerSize.height -= scrollbarSize.height;
}
if (scrollbars & 2) { // if we need the vscrollbar, remove its width
containerSize.width -= scrollbarSize.width;
}
}
}
// Size the child items to the container (if non-shrinkWrap):
for (i = 0; i < length; ++i) {
info.index = i;
me.fitItem(childItems[i], info);
}
if (shrinkWrapHeight || shrinkWrapWidth) {
padding = ownerContext.targetContext.getPaddingInfo();
if (shrinkWrapWidth) {
if (overflowY && !containerSize.gotHeight) {
// if we might overflow vertically and don't have the container height,
// we don't know if we will need a vscrollbar or not, so we must wait
// for that height so that we can determine the contentWidth...
me.done = false;
} else {
contentWidth = info.contentWidth + padding.width;
// the scrollbar flag (if set) will indicate that an overflow exists on
// the horz(1) or vert(2) axis... if not set, then there could never be
// an overflow...
if (scrollbars & 2) { // if we need the vscrollbar, add its width
contentWidth += scrollbarSize.width;
}
if (!ownerContext.setContentWidth(contentWidth)) {
me.done = false;
}
}
}
if (shrinkWrapHeight) {
if (overflowX && !containerSize.gotWidth) {
// if we might overflow horizontally and don't have the container width,
// we don't know if we will need a hscrollbar or not, so we must wait
// for that width so that we can determine the contentHeight...
me.done = false;
} else {
contentHeight = info.contentHeight + padding.height;
// the scrollbar flag (if set) will indicate that an overflow exists on
// the horz(1) or vert(2) axis... if not set, then there could never be
// an overflow...
if (scrollbars & 1) { // if we need the hscrollbar, add its height
contentHeight += scrollbarSize.height;
}
if (!ownerContext.setContentHeight(contentHeight)) {
me.done = false;
}
}
}
}
},
fitItem: function (itemContext, info) {
var me = this;
if (itemContext.invalid) {
me.done = false;
return;
}
info.margins = itemContext.getMarginInfo();
info.needed = info.got = 0;
me.fitItemWidth(itemContext, info);
me.fitItemHeight(itemContext, info);
// If not all required dimensions have been satisfied, we're not done.
if (info.got != info.needed) {
me.done = false;
}
},
fitItemWidth: function (itemContext, info) {
var contentWidth, width;
// Attempt to set only dimensions that are being controlled, not shrinkWrap dimensions
if (info.ownerContext.widthModel.shrinkWrap) {
// contentWidth must include the margins to be consistent with setItemWidth
width = itemContext.getProp('width') + info.margins.width;
// because we add margins, width will be NaN or a number (not undefined)
contentWidth = info.contentWidth;
if (contentWidth === undefined) {
info.contentWidth = width;
} else {
info.contentWidth = Math.max(contentWidth, width);
}
} else if (itemContext.widthModel.calculated) {
++info.needed;
if (info.targetSize.gotWidth) {
++info.got;
this.setItemWidth(itemContext, info);
}
}
this.positionItemX(itemContext, info);
},
fitItemHeight: function (itemContext, info) {
var contentHeight, height;
if (info.ownerContext.heightModel.shrinkWrap) {
// contentHeight must include the margins to be consistent with setItemHeight
height = itemContext.getProp('height') + info.margins.height;
// because we add margins, height will be NaN or a number (not undefined)
contentHeight = info.contentHeight;
if (contentHeight === undefined) {
info.contentHeight = height;
} else {
info.contentHeight = Math.max(contentHeight, height);
}
} else if (itemContext.heightModel.calculated) {
++info.needed;
if (info.targetSize.gotHeight) {
++info.got;
this.setItemHeight(itemContext, info);
}
}
this.positionItemY(itemContext, info);
},
positionItemX: function (itemContext, info) {
var margins = info.margins;
// Adjust position to account for configured margins or if we have multiple items
// (all items should overlap):
if (info.index || margins.left) {
itemContext.setProp('x', margins.left);
}
if (margins.width) {
// Need the margins for shrink-wrapping but old IE sometimes collapses the left margin into the padding
itemContext.setProp('margin-right', margins.width);
}
},
positionItemY: function (itemContext, info) {
var margins = info.margins;
if (info.index || margins.top) {
itemContext.setProp('y', margins.top);
}
if (margins.height) {
// Need the margins for shrink-wrapping but old IE sometimes collapses the top margin into the padding
itemContext.setProp('margin-bottom', margins.height);
}
},
setItemHeight: function (itemContext, info) {
itemContext.setHeight(info.targetSize.height - info.margins.height);
},
setItemWidth: function (itemContext, info) {
itemContext.setWidth(info.targetSize.width - info.margins.width);
}
});
| lightbase/WSCacicNeo | wscacicneo/static/ext-js/src/layout/container/Fit.js | JavaScript | gpl-2.0 | 15,702 |
var struct___m_m_v_a_d___f_l_a_g_s3 =
[
[ "LargePageCreating", "struct___m_m_v_a_d___f_l_a_g_s3.html#aaf3480d49bcc87fe7d648ad6061fbc1f", null ],
[ "LastSequentialTrim", "struct___m_m_v_a_d___f_l_a_g_s3.html#a2c1946858db395cb94d8686947411c33", null ],
[ "PreferredNode", "struct___m_m_v_a_d___f_l_a_g_s3.html#a972cba8eb82875f0aca674d4809b9d5f", null ],
[ "SequentialAccess", "struct___m_m_v_a_d___f_l_a_g_s3.html#a8865ee977a14e8d152d71c9eebd9ed0d", null ],
[ "Spare", "struct___m_m_v_a_d___f_l_a_g_s3.html#accbf9eed7385a927eb508f8f467daf0d", null ],
[ "Spare2", "struct___m_m_v_a_d___f_l_a_g_s3.html#ac22b54ee6ad708514d094f994c1526c9", null ],
[ "Spare3", "struct___m_m_v_a_d___f_l_a_g_s3.html#a5160890745965b707dcb90c35ce7e718", null ],
[ "Teb", "struct___m_m_v_a_d___f_l_a_g_s3.html#abbb6854bf15583de42fc9c80243dddc6", null ]
]; | dooooon/Blackbone | doc/driver/html/struct___m_m_v_a_d___f_l_a_g_s3.js | JavaScript | mit | 861 |
/* Copyright (c) 2012-2015 LevelUP contributors
* See list at <https://github.com/level/levelup#contributing>
* MIT License <https://github.com/level/levelup/blob/master/LICENSE.md>
*/
var async = require('async')
, common = require('./common')
, assert = require('referee').assert
, refute = require('referee').refute
, buster = require('bustermove')
buster.testCase('Binary API', {
'setUp': function (done) {
common.commonSetUp.call(this, function () {
common.loadBinaryTestData(function (err, data) {
refute(err)
this.testData = data
done()
}.bind(this))
}.bind(this))
}
, 'tearDown': common.commonTearDown
, 'sanity check on test data': function (done) {
assert(Buffer.isBuffer(this.testData))
common.checkBinaryTestData(this.testData, done)
}
, 'test put() and get() with binary value {valueEncoding:binary}': function (done) {
this.openTestDatabase(function (db) {
db.put('binarydata', this.testData, { valueEncoding: 'binary' }, function (err) {
refute(err)
db.get('binarydata', { valueEncoding: 'binary' }, function (err, value) {
refute(err)
assert(value)
common.checkBinaryTestData(value, done)
})
})
}.bind(this))
}
, 'test put() and get() with binary value {valueEncoding:binary} on createDatabase()': function (done) {
this.openTestDatabase({ createIfMissing: true, errorIfExists: true, valueEncoding: 'binary' }, function (db) {
db.put('binarydata', this.testData, function (err) {
refute(err)
db.get('binarydata', function (err, value) {
refute(err)
assert(value)
common.checkBinaryTestData(value, done)
})
})
}.bind(this))
}
, 'test put() and get() with binary key {valueEncoding:binary}': function (done) {
this.openTestDatabase(function (db) {
db.put(this.testData, 'binarydata', { valueEncoding: 'binary' }, function (err) {
refute(err)
db.get(this.testData, { valueEncoding: 'binary' }, function (err, value) {
refute(err)
assert(value instanceof Buffer, 'value is buffer')
assert.equals(value.toString(), 'binarydata')
done()
}.bind(this))
}.bind(this))
}.bind(this))
}
, 'test put() and get() with binary value {keyEncoding:utf8,valueEncoding:binary}': function (done) {
this.openTestDatabase(function (db) {
db.put('binarydata', this.testData, { keyEncoding: 'utf8', valueEncoding: 'binary' }, function (err) {
refute(err)
db.get('binarydata', { keyEncoding: 'utf8', valueEncoding: 'binary' }, function (err, value) {
refute(err)
assert(value)
common.checkBinaryTestData(value, done)
})
})
}.bind(this))
}
, 'test put() and get() with binary value {keyEncoding:utf8,valueEncoding:binary} on createDatabase()': function (done) {
this.openTestDatabase({ createIfMissing: true, errorIfExists: true, keyEncoding: 'utf8', valueEncoding: 'binary' }, function (db) {
db.put('binarydata', this.testData, function (err) {
refute(err)
db.get('binarydata', function (err, value) {
refute(err)
assert(value)
common.checkBinaryTestData(value, done)
})
})
}.bind(this))
}
, 'test put() and get() with binary key {keyEncoding:binary,valueEncoding:utf8}': function (done) {
this.openTestDatabase(function (db) {
db.put(this.testData, 'binarydata', { keyEncoding: 'binary', valueEncoding: 'utf8' }, function (err) {
refute(err)
db.get(this.testData, { keyEncoding: 'binary', valueEncoding: 'utf8' }, function (err, value) {
refute(err)
assert.equals(value, 'binarydata')
done()
}.bind(this))
}.bind(this))
}.bind(this))
}
, 'test put() and get() with binary key & value {valueEncoding:binary}': function (done) {
this.openTestDatabase(function (db) {
db.put(this.testData, this.testData, { valueEncoding: 'binary' }, function (err) {
refute(err)
db.get(this.testData, { valueEncoding: 'binary' }, function (err, value) {
refute(err)
common.checkBinaryTestData(value, done)
}.bind(this))
}.bind(this))
}.bind(this))
}
, 'test put() and del() and get() with binary key {valueEncoding:binary}': function (done) {
this.openTestDatabase(function (db) {
db.put(this.testData, 'binarydata', { valueEncoding: 'binary' }, function (err) {
refute(err)
db.del(this.testData, { valueEncoding: 'binary' }, function (err) {
refute(err)
db.get(this.testData, { valueEncoding: 'binary' }, function (err, value) {
assert(err)
refute(value)
done()
}.bind(this))
}.bind(this))
}.bind(this))
}.bind(this))
}
, 'batch() with multiple puts': function (done) {
this.openTestDatabase(function (db) {
db.batch(
[
{ type: 'put', key: 'foo', value: this.testData }
, { type: 'put', key: 'bar', value: this.testData }
, { type: 'put', key: 'baz', value: 'abazvalue' }
]
, { keyEncoding: 'utf8',valueEncoding: 'binary' }
, function (err) {
refute(err)
async.forEach(
['foo', 'bar', 'baz']
, function (key, callback) {
db.get(key, { valueEncoding: 'binary' }, function (err, value) {
refute(err)
if (key == 'baz') {
assert(value instanceof Buffer, 'value is buffer')
assert.equals(value.toString(), 'a' + key + 'value')
callback()
} else {
common.checkBinaryTestData(value, callback)
}
})
}
, done
)
}.bind(this)
)
}.bind(this))
}
})
| lastguest/levelup | test/binary-test.js | JavaScript | mit | 6,338 |
var searchData=
[
['bad',['Bad',['../union___m_e_m_o_r_y___w_o_r_k_i_n_g___s_e_t___e_x___b_l_o_c_k.html#ac0dacafab231c8eb42071594bbad8732',1,'_MEMORY_WORKING_SET_EX_BLOCK']]],
['balance',['Balance',['../union______unnamed710.html#a48ec1a90037c0d8282e29d099f2423d7',1,'___unnamed710::Balance()'],['../union______unnamed1666.html#a48ec1a90037c0d8282e29d099f2423d7',1,'___unnamed1666::Balance()'],['../union___m_m___a_v_l___n_o_d_e_1_1______unnamed1666.html#a48ec1a90037c0d8282e29d099f2423d7',1,'_MM_AVL_NODE::___unnamed1666::Balance()']]],
['balancedroot',['BalancedRoot',['../struct___m_m___a_v_l___t_a_b_l_e.html#a2dd2d289d07957b4ae19793699cf5c17',1,'_MM_AVL_TABLE::BalancedRoot()'],['../struct___m_m___a_v_l___t_a_b_l_e.html#a000247df449888107d0f1f9b1e5cfec1',1,'_MM_AVL_TABLE::BalancedRoot()'],['../struct___r_t_l___a_v_l___t_r_e_e.html#adca855c9887f22996c1146b07cbfe101',1,'_RTL_AVL_TREE::BalancedRoot()']]],
['banked',['Banked',['../union______unnamed1320.html#a7255c461bae32463938299adff2b4eef',1,'___unnamed1320']]],
['base',['base',['../struct___a_l_l_o_c_a_t_e___f_r_e_e___m_e_m_o_r_y.html#a94518ac1c8eb68c5924b848854d95be4',1,'_ALLOCATE_FREE_MEMORY::base()'],['../struct___p_r_o_t_e_c_t___m_e_m_o_r_y.html#a94518ac1c8eb68c5924b848854d95be4',1,'_PROTECT_MEMORY::base()'],['../struct___m_a_p___m_e_m_o_r_y___r_e_g_i_o_n.html#a94518ac1c8eb68c5924b848854d95be4',1,'_MAP_MEMORY_REGION::base()'],['../struct___u_n_m_a_p___m_e_m_o_r_y___r_e_g_i_o_n.html#a94518ac1c8eb68c5924b848854d95be4',1,'_UNMAP_MEMORY_REGION::base()'],['../struct___h_i_d_e___v_a_d.html#a94518ac1c8eb68c5924b848854d95be4',1,'_HIDE_VAD::base()'],['../struct___i_m_a_g_e___e_x_p_o_r_t___d_i_r_e_c_t_o_r_y.html#a30274734451b4e18628b06854566571f',1,'_IMAGE_EXPORT_DIRECTORY::Base()']]],
['baseaddress',['BaseAddress',['../struct___m_e_m_o_r_y___b_a_s_i_c___i_n_f_o_r_m_a_t_i_o_n.html#a27c6c16683bd65466d1e1a3f5f31b6cd',1,'_MEMORY_BASIC_INFORMATION']]],
['basedllname',['BaseDllName',['../struct___l_d_r___d_a_t_a___t_a_b_l_e___e_n_t_r_y.html#a35fdae1b597e8cb5d499c1c845d8fc92',1,'_LDR_DATA_TABLE_ENTRY::BaseDllName()'],['../struct___l_d_r___d_a_t_a___t_a_b_l_e___e_n_t_r_y32.html#a9e84d9d29523621b635b25ba1a57252a',1,'_LDR_DATA_TABLE_ENTRY32::BaseDllName()'],['../struct___k_l_d_r___d_a_t_a___t_a_b_l_e___e_n_t_r_y.html#a35fdae1b597e8cb5d499c1c845d8fc92',1,'_KLDR_DATA_TABLE_ENTRY::BaseDllName()']]],
['baseofcode',['BaseOfCode',['../struct___i_m_a_g_e___o_p_t_i_o_n_a_l___h_e_a_d_e_r64.html#a98a7b4d727ac73ef59d9c9d761db0b18',1,'_IMAGE_OPTIONAL_HEADER64::BaseOfCode()'],['../struct___i_m_a_g_e___o_p_t_i_o_n_a_l___h_e_a_d_e_r32.html#a98a7b4d727ac73ef59d9c9d761db0b18',1,'_IMAGE_OPTIONAL_HEADER32::BaseOfCode()']]],
['baseofdata',['BaseOfData',['../struct___i_m_a_g_e___o_p_t_i_o_n_a_l___h_e_a_d_e_r32.html#ae6939253ab11d032cebaedbe925f88b4',1,'_IMAGE_OPTIONAL_HEADER32']]],
['basepriority',['BasePriority',['../struct___s_y_s_t_e_m___t_h_r_e_a_d___i_n_f_o_r_m_a_t_i_o_n.html#a83350567ec26fc4723ac14b5864ae4f9',1,'_SYSTEM_THREAD_INFORMATION::BasePriority()'],['../struct___t_h_r_e_a_d___b_a_s_i_c___i_n_f_o_r_m_a_t_i_o_n.html#a83350567ec26fc4723ac14b5864ae4f9',1,'_THREAD_BASIC_INFORMATION::BasePriority()'],['../struct___s_y_s_t_e_m___p_r_o_c_e_s_s___i_n_f_o.html#a74dfc76c4b84f4184242cd09d7294207',1,'_SYSTEM_PROCESS_INFO::BasePriority()']]],
['bb_5fpool_5ftag',['BB_POOL_TAG',['../_private_8h.html#ab83381de72db4f5d852ba26949e2902e',1,'Private.h']]],
['bballocatefreememory',['BBAllocateFreeMemory',['../_routines_8c.html#a42365b4be752c575360961ef27188080',1,'BBAllocateFreeMemory(IN PALLOCATE_FREE_MEMORY pAllocFree, OUT PALLOCATE_FREE_MEMORY_RESULT pResult): Routines.c'],['../_routines_8h.html#a42365b4be752c575360961ef27188080',1,'BBAllocateFreeMemory(IN PALLOCATE_FREE_MEMORY pAllocFree, OUT PALLOCATE_FREE_MEMORY_RESULT pResult): Routines.c']]],
['bballocatefreephysical',['BBAllocateFreePhysical',['../_routines_8c.html#ae9177711ac60b53be9b0f766682fbcef',1,'Routines.c']]],
['bballocateindiscardedmemory',['BBAllocateInDiscardedMemory',['../_loader_private_8c.html#ad1ce9fbec376a5f490f951aa78cd65ce',1,'LoaderPrivate.c']]],
['bballocatesharedpage',['BBAllocateSharedPage',['../_remap_8c.html#a0835e6ed7b558cc2bbf101b4ebae9c05',1,'Remap.c']]],
['bbapcinject',['BBApcInject',['../_inject_8c.html#a298d498944304fc1a274bc5517fb2f27',1,'Inject.c']]],
['bbbuildprocessregionlistforrange',['BBBuildProcessRegionListForRange',['../_remap_8c.html#a11b75ba73289267143bd142c8e18750e',1,'Remap.c']]],
['bbcleanuphostprocess',['BBCleanupHostProcess',['../_remap_8c.html#ad6678da5eb92b81e33d87f7490951007',1,'BBCleanupHostProcess(IN PPROCESS_MAP_ENTRY pProcessEntry): Remap.c'],['../_remap_8h.html#ad6678da5eb92b81e33d87f7490951007',1,'BBCleanupHostProcess(IN PPROCESS_MAP_ENTRY pProcessEntry): Remap.c']]],
['bbcleanuppagelist',['BBCleanupPageList',['../_remap_8c.html#a50ca5d0ccc42e4adb2dcfd43c38f8f3b',1,'Remap.c']]],
['bbcleanupphysmementry',['BBCleanupPhysMemEntry',['../_routines_8c.html#aa45be6104ca49bf965d9b838c9e4cb5b',1,'BBCleanupPhysMemEntry(IN PMEM_PHYS_ENTRY pEntry, BOOLEAN attached): Routines.c'],['../_routines_8h.html#aa45be6104ca49bf965d9b838c9e4cb5b',1,'BBCleanupPhysMemEntry(IN PMEM_PHYS_ENTRY pEntry, BOOLEAN attached): Routines.c']]],
['bbcleanupprocessentry',['BBCleanupProcessEntry',['../_remap_8c.html#ac7c25319f3aeb357cc37a64f3cb13b53',1,'BBCleanupProcessEntry(IN PPROCESS_MAP_ENTRY pProcessEntry): Remap.c'],['../_remap_8h.html#ac7c25319f3aeb357cc37a64f3cb13b53',1,'BBCleanupProcessEntry(IN PPROCESS_MAP_ENTRY pProcessEntry): Remap.c']]],
['bbcleanupprocessphysentry',['BBCleanupProcessPhysEntry',['../_routines_8c.html#a1a9062d5492cdde5394e312db5024b95',1,'BBCleanupProcessPhysEntry(IN PMEM_PHYS_PROCESS_ENTRY pEntry, BOOLEAN attached): Routines.c'],['../_routines_8h.html#a1a9062d5492cdde5394e312db5024b95',1,'BBCleanupProcessPhysEntry(IN PMEM_PHYS_PROCESS_ENTRY pEntry, BOOLEAN attached): Routines.c']]],
['bbcleanupprocessphyslist',['BBCleanupProcessPhysList',['../_routines_8c.html#a37a1af1d4644bf5495a13b481b4249d1',1,'BBCleanupProcessPhysList(): Routines.c'],['../_routines_8h.html#a37a1af1d4644bf5495a13b481b4249d1',1,'BBCleanupProcessPhysList(): Routines.c']]],
['bbcleanupprocesstable',['BBCleanupProcessTable',['../_remap_8c.html#a45970f9f711d6e19c5ee03242eee5261',1,'BBCleanupProcessTable(): Remap.c'],['../_remap_8h.html#a45970f9f711d6e19c5ee03242eee5261',1,'BBCleanupProcessTable(): Remap.c']]],
['bbconsolidateregionlist',['BBConsolidateRegionList',['../_remap_8c.html#a98e0da85e5255e13acb7b79f28a110e2',1,'Remap.c']]],
['bbconvertprotection',['BBConvertProtection',['../_vad_routines_8c.html#a8f8948d3da3bf521e3be7d26d374f2a8',1,'BBConvertProtection(IN ULONG prot, IN BOOLEAN fromPTE): VadRoutines.c'],['../_vad_routines_8h.html#a8f8948d3da3bf521e3be7d26d374f2a8',1,'BBConvertProtection(IN ULONG prot, IN BOOLEAN fromPTE): VadRoutines.c']]],
['bbcopymemory',['BBCopyMemory',['../_routines_8c.html#a8830f846c47874f47b7dfbeb66fe8bf3',1,'BBCopyMemory(IN PCOPY_MEMORY pCopy): Routines.c'],['../_routines_8h.html#a8830f846c47874f47b7dfbeb66fe8bf3',1,'BBCopyMemory(IN PCOPY_MEMORY pCopy): Routines.c']]],
['bbdisabledep',['BBDisableDEP',['../_routines_8c.html#ac1d0ecdb4fbf4fbb8a469b09210fc2d0',1,'BBDisableDEP(IN PDISABLE_DEP pData): Routines.c'],['../_routines_8h.html#ac1d0ecdb4fbf4fbb8a469b09210fc2d0',1,'BBDisableDEP(IN PDISABLE_DEP pData): Routines.c']]],
['bbdispatch',['BBDispatch',['../_black_bone_drv_8h.html#a53530664e0da912e0b1122cd3be0476e',1,'BBDispatch(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp): Dispatch.c'],['../_dispatch_8c.html#a53530664e0da912e0b1122cd3be0476e',1,'BBDispatch(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp): Dispatch.c']]],
['bbexecuteinnewthread',['BBExecuteInNewThread',['../_inject_8c.html#a774a73ba0eed0cf7a204898f50f4b5a9',1,'BBExecuteInNewThread(IN PVOID pBaseAddress, IN PVOID pParam, IN ULONG flags, IN BOOLEAN wait, OUT PNTSTATUS pExitStatus): Inject.c'],['../_routines_8h.html#a774a73ba0eed0cf7a204898f50f4b5a9',1,'BBExecuteInNewThread(IN PVOID pBaseAddress, IN PVOID pParam, IN ULONG flags, IN BOOLEAN wait, OUT PNTSTATUS pExitStatus): Inject.c']]],
['bbfindpageentry',['BBFindPageEntry',['../_remap_8c.html#a66813163ee3a67afd8f20015d11aa3c9',1,'Remap.c']]],
['bbfindvad',['BBFindVAD',['../_vad_routines_8c.html#a76f3c0928b1dc18f1155a477adca9d41',1,'BBFindVAD(IN PEPROCESS pProcess, IN ULONG_PTR address, OUT PMMVAD_SHORT *pResult): VadRoutines.c'],['../_vad_routines_8h.html#a76f3c0928b1dc18f1155a477adca9d41',1,'BBFindVAD(IN PEPROCESS pProcess, IN ULONG_PTR address, OUT PMMVAD_SHORT *pResult): VadRoutines.c']]],
['bbgetmoduleexport',['BBGetModuleExport',['../_loader_8c.html#a04e18e8b7773f1a4c32ad9fee0e6717c',1,'BBGetModuleExport(IN PVOID pBase, IN PCCHAR name_ord): Loader.c'],['../_loader_8h.html#a04e18e8b7773f1a4c32ad9fee0e6717c',1,'BBGetModuleExport(IN PVOID pBase, IN PCCHAR name_ord): Loader.c'],['../_loader_private_8c.html#a04e18e8b7773f1a4c32ad9fee0e6717c',1,'BBGetModuleExport(IN PVOID pBase, IN PCCHAR name_ord): LoaderPrivate.c']]],
['bbgetnativecode',['BBGetNativeCode',['../_inject_8c.html#a1567b5115b3197809620e73ab1d7a4d6',1,'Inject.c']]],
['bbgetrequiredremapoutputsize',['BBGetRequiredRemapOutputSize',['../_remap_8c.html#a3e26085ed53a0a82250d5f519fa91e57',1,'BBGetRequiredRemapOutputSize(IN PLIST_ENTRY pList, OUT PULONG_PTR pSize): Remap.c'],['../_remap_8h.html#a3e26085ed53a0a82250d5f519fa91e57',1,'BBGetRequiredRemapOutputSize(IN PLIST_ENTRY pList, OUT PULONG_PTR pSize): Remap.c']]],
['bbgetsystemmodule',['BBGetSystemModule',['../_loader_8c.html#a0f480402673fa85e5efd11f2de760ba9',1,'BBGetSystemModule(IN PUNICODE_STRING pName, IN PVOID pAddress): Loader.c'],['../_loader_8h.html#a0f480402673fa85e5efd11f2de760ba9',1,'BBGetSystemModule(IN PUNICODE_STRING pName, IN PVOID pAddress): Loader.c'],['../_loader_private_8c.html#a0f480402673fa85e5efd11f2de760ba9',1,'BBGetSystemModule(IN PUNICODE_STRING pName, IN PVOID pAddress): LoaderPrivate.c']]],
['bbgetusermodulebase',['BBGetUserModuleBase',['../_loader_8c.html#a390ed9e940e4afd22ca0b82b3145394f',1,'BBGetUserModuleBase(IN PEPROCESS pProcess, IN PUNICODE_STRING ModuleName, IN BOOLEAN isWow64): Loader.c'],['../_loader_8h.html#a390ed9e940e4afd22ca0b82b3145394f',1,'BBGetUserModuleBase(IN PEPROCESS pProcess, IN PUNICODE_STRING ModuleName, IN BOOLEAN isWow64): Loader.c'],['../_loader_private_8c.html#a390ed9e940e4afd22ca0b82b3145394f',1,'BBGetUserModuleBase(IN PEPROCESS pProcess, IN PUNICODE_STRING ModuleName, IN BOOLEAN isWow64): LoaderPrivate.c']]],
['bbgetvadtype',['BBGetVadType',['../_vad_routines_8c.html#af0fd52b9e593b282b2e1a08cc1f1bc32',1,'BBGetVadType(IN PEPROCESS pProcess, IN ULONG_PTR address, OUT PMI_VAD_TYPE pType): VadRoutines.c'],['../_vad_routines_8h.html#af0fd52b9e593b282b2e1a08cc1f1bc32',1,'BBGetVadType(IN PEPROCESS pProcess, IN ULONG_PTR address, OUT PMI_VAD_TYPE pType): VadRoutines.c']]],
['bbgetwow64code',['BBGetWow64Code',['../_inject_8c.html#ac7bfb71fb0f25652a2ba2960bcd52916',1,'Inject.c']]],
['bbgrantaccess',['BBGrantAccess',['../_routines_8c.html#abdceca41c2142d453a6d239ffffcad36',1,'BBGrantAccess(IN PHANDLE_GRANT_ACCESS pAccess): Routines.c'],['../_routines_8h.html#abdceca41c2142d453a6d239ffffcad36',1,'BBGrantAccess(IN PHANDLE_GRANT_ACCESS pAccess): Routines.c']]],
['bbhandlesharedregion',['BBHandleSharedRegion',['../_remap_8c.html#a6244c80d71f22b3c7aad4582842d86a6',1,'Remap.c']]],
['bbhidevad',['BBHideVAD',['../_routines_8c.html#a219ed264f26ecb9460334d807bc066ed',1,'BBHideVAD(IN PHIDE_VAD pData): Routines.c'],['../_routines_8h.html#a219ed264f26ecb9460334d807bc066ed',1,'BBHideVAD(IN PHIDE_VAD pData): Routines.c']]],
['bbinitdynamicdata',['BBInitDynamicData',['../_black_bone_drv_8c.html#a1b931492b6729c9d586cd8902da3aa3a',1,'BlackBoneDrv.c']]],
['bbinitldrdata',['BBInitLdrData',['../_loader_8c.html#ad58dba8a31f0db044f654c9f8a928a8a',1,'BBInitLdrData(IN PKLDR_DATA_TABLE_ENTRY pThisModule): Loader.c'],['../_loader_8h.html#ad58dba8a31f0db044f654c9f8a928a8a',1,'BBInitLdrData(IN PKLDR_DATA_TABLE_ENTRY pThisModule): Loader.c'],['../_loader_private_8c.html#ad58dba8a31f0db044f654c9f8a928a8a',1,'BBInitLdrData(IN PKLDR_DATA_TABLE_ENTRY pThisModule): LoaderPrivate.c']]],
['bbinjectdll',['BBInjectDll',['../_inject_8c.html#a59abb89bd353b3ad36fdcf1c66e423ad',1,'BBInjectDll(IN PINJECT_DLL pData): Inject.c'],['../_routines_8h.html#a59abb89bd353b3ad36fdcf1c66e423ad',1,'BBInjectDll(IN PINJECT_DLL pData): Inject.c']]],
['bblookupphysmementry',['BBLookupPhysMemEntry',['../_routines_8c.html#a74ce79acc8d60775d29b050b5544f6be',1,'Routines.c']]],
['bblookupphysprocessentry',['BBLookupPhysProcessEntry',['../_routines_8c.html#a2d67fbedafe1e78d3dc630d712a3c0a0',1,'BBLookupPhysProcessEntry(IN HANDLE pid): Routines.c'],['../_routines_8h.html#a2d67fbedafe1e78d3dc630d712a3c0a0',1,'BBLookupPhysProcessEntry(IN HANDLE pid): Routines.c']]],
['bblookupprocessentry',['BBLookupProcessEntry',['../_remap_8c.html#ab9160b10f2c993aa5b93d95b83004a46',1,'BBLookupProcessEntry(IN HANDLE pid, IN BOOLEAN asHost): Remap.c'],['../_remap_8h.html#ab9160b10f2c993aa5b93d95b83004a46',1,'BBLookupProcessEntry(IN HANDLE pid, IN BOOLEAN asHost): Remap.c']]],
['bblookupprocessthread',['BBLookupProcessThread',['../_inject_8c.html#adc58d644fa0fd3422316b76e3ae0ef27',1,'Inject.c']]],
['bbmapmemory',['BBMapMemory',['../_remap_8c.html#a477ab35d84eaab6198cd8c2b36966df5',1,'BBMapMemory(IN PMAP_MEMORY pRemap, OUT PPROCESS_MAP_ENTRY *ppEntry): Remap.c'],['../_remap_8h.html#a477ab35d84eaab6198cd8c2b36966df5',1,'BBMapMemory(IN PMAP_MEMORY pRemap, OUT PPROCESS_MAP_ENTRY *ppEntry): Remap.c']]],
['bbmapmemoryregion',['BBMapMemoryRegion',['../_remap_8c.html#add6826b20572e5728507d4c040351cfd',1,'BBMapMemoryRegion(IN PMAP_MEMORY_REGION pRegion, OUT PMAP_MEMORY_REGION_RESULT pResult): Remap.c'],['../_remap_8h.html#add6826b20572e5728507d4c040351cfd',1,'BBMapMemoryRegion(IN PMAP_MEMORY_REGION pRegion, OUT PMAP_MEMORY_REGION_RESULT pResult): Remap.c']]],
['bbmapregionintocurrentprocess',['BBMapRegionIntoCurrentProcess',['../_remap_8c.html#ae74fd0959ad7136063b9ed02ee50740f',1,'Remap.c']]],
['bbmapregionlistintocurrentprocess',['BBMapRegionListIntoCurrentProcess',['../_remap_8c.html#a58da9a40f5285a92264e5f6960ecc38a',1,'Remap.c']]],
['bbmapsharedpage',['BBMapSharedPage',['../_remap_8c.html#a92d04abe3edc00718bd7758d73518f9f',1,'Remap.c']]],
['bbmapworker',['BBMapWorker',['../_loader_8c.html#a433fb08e81c29e16bb97a09c6ac9e231',1,'BBMapWorker(IN PVOID pArg): Loader.c'],['../_loader_private_8c.html#a433fb08e81c29e16bb97a09c6ac9e231',1,'BBMapWorker(IN PVOID pArg): LoaderPrivate.c']]],
['bbmmapdriver',['BBMMapDriver',['../_loader_8c.html#a56cd407ebacf8fcfbce76a6ff1e01c78',1,'BBMMapDriver(IN PUNICODE_STRING pPath): Loader.c'],['../_loader_8h.html#a56cd407ebacf8fcfbce76a6ff1e01c78',1,'BBMMapDriver(IN PUNICODE_STRING pPath): Loader.c'],['../_loader_private_8c.html#a56cd407ebacf8fcfbce76a6ff1e01c78',1,'BBMMapDriver(IN PUNICODE_STRING pPath): LoaderPrivate.c']]],
['bbpreparemdllist',['BBPrepareMDLList',['../_remap_8c.html#ac54bb573601aebf34fa18151d0163fd2',1,'Remap.c']]],
['bbpreparemdllistentry',['BBPrepareMDLListEntry',['../_remap_8c.html#a09fbafd63633eff0b0c23ee2ca803255',1,'BBPrepareMDLListEntry(IN PMAP_ENTRY pEntry): Remap.c'],['../_remap_8c.html#aa34fd8c82f1edae8f913704d00399c53',1,'BBPrepareMDLListEntry(IN OUT PMAP_ENTRY pEntry): Remap.c']]],
['bbprocessnotify',['BBProcessNotify',['../_notify_routine_8c.html#ac42926d35b43546c8117ea237836a246',1,'BBProcessNotify(IN HANDLE ParentId, IN HANDLE ProcessId, IN BOOLEAN Create): NotifyRoutine.c'],['../_routines_8h.html#ac42926d35b43546c8117ea237836a246',1,'BBProcessNotify(IN HANDLE ParentId, IN HANDLE ProcessId, IN BOOLEAN Create): NotifyRoutine.c']]],
['bbprotectmemory',['BBProtectMemory',['../_routines_8c.html#a722fad32324ad260db0dbb10c073ac05',1,'BBProtectMemory(IN PPROTECT_MEMORY pProtect): Routines.c'],['../_routines_8h.html#a722fad32324ad260db0dbb10c073ac05',1,'BBProtectMemory(IN PPROTECT_MEMORY pProtect): Routines.c']]],
['bbprotectvad',['BBProtectVAD',['../_vad_routines_8c.html#a2ffee644c4998c9354335bbf5fadca93',1,'BBProtectVAD(IN PEPROCESS pProcess, IN ULONG_PTR address, IN ULONG prot): VadRoutines.c'],['../_vad_routines_8h.html#a2ffee644c4998c9354335bbf5fadca93',1,'BBProtectVAD(IN PEPROCESS pProcess, IN ULONG_PTR address, IN ULONG prot): VadRoutines.c']]],
['bbqueueuserapc',['BBQueueUserApc',['../_inject_8c.html#a905bf6b798e47803777817f7c9481af5',1,'BBQueueUserApc(IN PETHREAD pThread, IN PVOID pUserFunc, IN PVOID Arg1): Inject.c'],['../_routines_8h.html#a905bf6b798e47803777817f7c9481af5',1,'BBQueueUserApc(IN PETHREAD pThread, IN PVOID pUserFunc, IN PVOID Arg1): Inject.c']]],
['bbresolvereferences',['BBResolveReferences',['../_loader_8c.html#a60c721a39629feecef7fc6f64c440c37',1,'BBResolveReferences(IN PVOID pImageBase): Loader.c'],['../_loader_8h.html#a60c721a39629feecef7fc6f64c440c37',1,'BBResolveReferences(IN PVOID pImageBase): Loader.c'],['../_loader_private_8c.html#a60c721a39629feecef7fc6f64c440c37',1,'BBResolveReferences(IN PVOID pImageBase): LoaderPrivate.c']]],
['bbsafehandleclose',['BBSafeHandleClose',['../_remap_8c.html#a7bc394ae8ea397352b69aea5b8f824ba',1,'Remap.c']]],
['bbsetprotection',['BBSetProtection',['../_routines_8c.html#a5b69503e6fe88ae6842f3135343f58ff',1,'BBSetProtection(IN PSET_PROC_PROTECTION pProtection): Routines.c'],['../_routines_8h.html#a5b69503e6fe88ae6842f3135343f58ff',1,'BBSetProtection(IN PSET_PROC_PROTECTION pProtection): Routines.c']]],
['bbunlinkvad',['BBUnlinkVAD',['../_vad_routines_8c.html#a8dbd24595aefe1bc5a5f529fb4ae9b2b',1,'BBUnlinkVAD(IN PEPROCESS pProcess, IN ULONG_PTR address): VadRoutines.c'],['../_vad_routines_8h.html#a8dbd24595aefe1bc5a5f529fb4ae9b2b',1,'BBUnlinkVAD(IN PEPROCESS pProcess, IN ULONG_PTR address): VadRoutines.c']]],
['bbunload',['BBUnload',['../_black_bone_drv_8c.html#afdd96046916066d613c6fbb7a8028040',1,'BlackBoneDrv.c']]],
['bbunmapmemory',['BBUnmapMemory',['../_remap_8c.html#a1cb21cac2fa196ad5abff8a9e90baee7',1,'BBUnmapMemory(IN PUNMAP_MEMORY pUnmap): Remap.c'],['../_remap_8h.html#a1cb21cac2fa196ad5abff8a9e90baee7',1,'BBUnmapMemory(IN PUNMAP_MEMORY pUnmap): Remap.c']]],
['bbunmapmemoryregion',['BBUnmapMemoryRegion',['../_remap_8c.html#a10ed588f0df58d216e8593eb5e4a686f',1,'BBUnmapMemoryRegion(IN PUNMAP_MEMORY_REGION pRegion): Remap.c'],['../_remap_8h.html#a10ed588f0df58d216e8593eb5e4a686f',1,'BBUnmapMemoryRegion(IN PUNMAP_MEMORY_REGION pRegion): Remap.c']]],
['bbunmapregionentry',['BBUnmapRegionEntry',['../_remap_8c.html#aca917f20fffef1a06b64d9f8747d5a21',1,'Remap.c']]],
['beingdebugged',['BeingDebugged',['../struct___p_e_b.html#a0fc6d63bf068599957ec1f886ae1bef1',1,'_PEB::BeingDebugged()'],['../struct___p_e_b32.html#a0fc6d63bf068599957ec1f886ae1bef1',1,'_PEB32::BeingDebugged()']]],
['blackbone_5fdevice_5ffile',['BLACKBONE_DEVICE_FILE',['../_black_bone_def_8h.html#a525c4ff077902a069981ba68609dba8e',1,'BlackBoneDef.h']]],
['blackbone_5fdevice_5fname',['BLACKBONE_DEVICE_NAME',['../_black_bone_def_8h.html#a2aba7eca1624b2012130294e31a46bc4',1,'BlackBoneDef.h']]],
['blackbonedef_2eh',['BlackBoneDef.h',['../_black_bone_def_8h.html',1,'']]],
['blackbonedrv_2ec',['BlackBoneDrv.c',['../_black_bone_drv_8c.html',1,'']]],
['blackbonedrv_2eh',['BlackBoneDrv.h',['../_black_bone_drv_8h.html',1,'']]],
['blocksize',['BlockSize',['../struct___p_o_o_l___h_e_a_d_e_r.html#ad5e3d9e7d22d3b445aac36de12d32d63',1,'_POOL_HEADER::BlockSize()'],['../struct___p_o_o_l___h_e_a_d_e_r.html#a10cce1b137e4b4fde22ebfdd5ca9a5e7',1,'_POOL_HEADER::BlockSize()']]],
['body',['Body',['../struct___o_b_j_e_c_t___h_e_a_d_e_r.html#a2dc0cbba948c330a64f244054b2e5f63',1,'_OBJECT_HEADER']]]
];
| dooooon/Blackbone | doc/driver/html/search/all_2.js | JavaScript | mit | 20,166 |
!function(e){"function"==typeof define&&define.amd?define(["jquery"],e):"object"==typeof module&&"object"==typeof module.exports?e(require("jquery")):e(jQuery)}(function(e){e.timeago.settings.strings={prefixAgo:"for",prefixFromNow:"om",suffixAgo:"siden",suffixFromNow:"",seconds:"mindre enn et minutt",minute:"ca. et minutt",minutes:"%d minutter",hour:"ca. en time",hours:"ca. %d timer",day:"en dag",days:"%d dager",month:"ca. en måned",months:"%d måneder",year:"ca. et år",years:"%d år"}}); | extend1994/cdnjs | ajax/libs/jquery-timeago/1.6.7/locales/jquery.timeago.no.min.js | JavaScript | mit | 495 |
import {
Mixin,
addListener,
removeListener,
hasListeners,
sendEvent,
} from '@ember/-internals/metal';
/**
@module @ember/object
*/
/**
This mixin allows for Ember objects to subscribe to and emit events.
```app/utils/person.js
import EmberObject from '@ember/object';
import Evented from '@ember/object/evented';
export default EmberObject.extend(Evented, {
greet() {
// ...
this.trigger('greet');
}
});
```
```javascript
var person = Person.create();
person.on('greet', function() {
console.log('Our person has greeted');
});
person.greet();
// outputs: 'Our person has greeted'
```
You can also chain multiple event subscriptions:
```javascript
person.on('greet', function() {
console.log('Our person has greeted');
}).one('greet', function() {
console.log('Offer one-time special');
}).off('event', this, forgetThis);
```
@class Evented
@public
*/
export default Mixin.create({
/**
Subscribes to a named event with given function.
```javascript
person.on('didLoad', function() {
// fired once the person has loaded
});
```
An optional target can be passed in as the 2nd argument that will
be set as the "this" for the callback. This is a good way to give your
function access to the object triggering the event. When the target
parameter is used the callback method becomes the third argument.
@method on
@param {String} name The name of the event
@param {Object} [target] The "this" binding for the callback
@param {Function|String} method A function or the name of a function to be called on `target`
@return this
@public
*/
on(name, target, method) {
addListener(this, name, target, method);
return this;
},
/**
Subscribes a function to a named event and then cancels the subscription
after the first time the event is triggered. It is good to use ``one`` when
you only care about the first time an event has taken place.
This function takes an optional 2nd argument that will become the "this"
value for the callback. When the target parameter is used the callback method
becomes the third argument.
@method one
@param {String} name The name of the event
@param {Object} [target] The "this" binding for the callback
@param {Function|String} method A function or the name of a function to be called on `target`
@return this
@public
*/
one(name, target, method) {
addListener(this, name, target, method, true);
return this;
},
/**
Triggers a named event for the object. Any additional arguments
will be passed as parameters to the functions that are subscribed to the
event.
```javascript
person.on('didEat', function(food) {
console.log('person ate some ' + food);
});
person.trigger('didEat', 'broccoli');
// outputs: person ate some broccoli
```
@method trigger
@param {String} name The name of the event
@param {Object...} args Optional arguments to pass on
@public
*/
trigger(name, ...args) {
sendEvent(this, name, args);
},
/**
Cancels subscription for given name, target, and method.
@method off
@param {String} name The name of the event
@param {Object} target The target of the subscription
@param {Function|String} method The function or the name of a function of the subscription
@return this
@public
*/
off(name, target, method) {
removeListener(this, name, target, method);
return this;
},
/**
Checks to see if object has any subscriptions for named event.
@method has
@param {String} name The name of the event
@return {Boolean} does the object have a subscription for event
@public
*/
has(name) {
return hasListeners(this, name);
},
});
| sly7-7/ember.js | packages/@ember/-internals/runtime/lib/mixins/evented.js | JavaScript | mit | 3,864 |
var assert = require('assert');
var fs = require('fs');
var glob = require('glob');
var path = require('path');
var __root = __dirname + '/..';
var phpjsutil = new require('../lib/phpjsutil');
var PhpjsUtil = phpjsutil({
injectDependencies: ['ini_set', 'ini_get'],
});
assert.deepEqualWithDifflet = require('deep-equal-with-difflet');
var files = {
"array_change_key_case": fs.readFileSync(__root + '/test/fixtures/func_array_change_key_case.js', 'utf-8'),
"pos" : fs.readFileSync(__root + '/test/fixtures/func_pos.js', 'utf-8'),
"current" : fs.readFileSync(__root + '/test/fixtures/func_current.js', 'utf-8'),
"is_binary" : fs.readFileSync(__root + '/test/fixtures/func_is_binary.js', 'utf-8')
};
PhpjsUtil.opener = function(name, cb) {
return cb(null, files[name]);
};
var fixture = JSON.parse(fs.readFileSync(__root + '/test/fixtures/fix_array_change_key_case.js', 'utf-8'));
describe('phpjsutil', function() {
describe('parse', function() {
it('should return exact fixture', function(done) {
PhpjsUtil.parse('array_change_key_case', files['array_change_key_case'], function(err, params) {
assert.equal(null, err);
// fs.writeFileSync(__root + '/test/fixtures/fix_array_change_key_case.js', JSON.stringify(params, null, ' '));
assert.deepEqualWithDifflet(params, fixture);
done();
});
});
});
});
| cigraphics/phpjs | test/test-phpjsutil.js | JavaScript | mit | 1,439 |
/*!
* Ajax Bootstrap Select
*
* Extends existing [Bootstrap Select] implementations by adding the ability to search via AJAX requests as you type. Originally for CROSCON.
*
* @version 1.4.1
* @author Adam Heim - https://github.com/truckingsim
* @link https://github.com/truckingsim/Ajax-Bootstrap-Select
* @copyright 2017 Adam Heim
* @license Released under the MIT license.
*
* Contributors:
* Mark Carver - https://github.com/markcarver
*
* Last build: 2017-07-21 1:08:53 PM GMT-0400
*/
!(function ($) {
/*!
* Spanish translation for the "es-ES" and "es" language codes.
* Diomedes Domínguez <[email protected]>
*/
$.fn.ajaxSelectPicker.locale["es-ES"]={currentlySelected:"Seleccionado",emptyTitle:"Seleccione y comience a escribir",errorText:"No se puede recuperar resultados",searchPlaceholder:"Buscar...",statusInitialized:"Empieza a escribir una consulta de búsqueda",statusNoResults:"Sin Resultados",statusSearching:"Buscando...",statusTooShort:"Introduzca más caracteres"},$.fn.ajaxSelectPicker.locale.es=$.fn.ajaxSelectPicker.locale["es-ES"];})(jQuery);
| holtkamp/cdnjs | ajax/libs/ajax-bootstrap-select/1.4.1/js/locale/ajax-bootstrap-select.es-ES.min.js | JavaScript | mit | 1,098 |
CKEDITOR.plugins.setLang("copyformatting","de-ch",{label:"Formatierung kopieren",notification:{copied:"Formatierung kopiert",applied:"Formatierung angewendet",canceled:"Formatierung abgebrochen",failed:"Formatierung fehlgeschlagen. Sie können Stile nicht anwenden, ohne sie zuerst zu kopieren."}}); | stweil/TYPO3.CMS | typo3/sysext/rte_ckeditor/Resources/Public/JavaScript/Contrib/plugins/copyformatting/lang/de-ch.js | JavaScript | gpl-2.0 | 302 |
"use strict";
// An RFC 2822 email header parser
var logger = require('./logger');
var utils = require('./utils');
var Iconv;
try { Iconv = require('iconv').Iconv }
catch (err) {
logger.logdebug("No iconv available - install with 'npm install iconv'");
}
function Header (options) {
this.headers = {};
this.headers_decoded = {};
this.header_list = [];
this.options = options;
};
exports.Header = Header;
exports.Iconv = Iconv;
Header.prototype.parse = function (lines) {
var self = this;
for (var i=0,l=lines.length; i < l; i++) {
var line = lines[i];
if (line.match(/^[ \t]/)) {
// continuation
this.header_list[this.header_list.length - 1] += line;
}
else {
this.header_list.push(line);
}
}
for (var i=0,l=this.header_list.length; i < l; i++) {
var match = this.header_list[i].match(/^([^:]*):\s*([\s\S]*)$/);
if (match) {
var key = match[1].toLowerCase();
var val = match[2];
this._add_header(key, val, "push");
}
else {
logger.logerror("Header did not look right: " + this.header_list[i]);
}
}
// Now add decoded versions
Object.keys(this.headers).forEach(function (key) {
self.headers[key].forEach(function (val) {
self._add_header_decode(key, val, "push");
})
})
};
function try_convert(data, encoding) {
try {
var converter = new Iconv(encoding, "UTF-8");
data = converter.convert(data);
}
catch (err) {
// TODO: raise a flag for this for possible scoring
logger.logwarn("initial iconv conversion from " + encoding + " to UTF-8 failed: " + err.message);
if (err.code !== 'EINVAL') {
try {
var converter = new Iconv(encoding, "UTF-8//TRANSLIT//IGNORE");
data = converter.convert(data);
}
catch (e) {
logger.logerror("iconv from " + encoding + " to UTF-8 failed: " + e.message);
}
}
}
return data;
}
function _decode_header (matched, encoding, cte, data) {
cte = cte.toUpperCase();
switch(cte) {
case 'Q':
data = utils.decode_qp(data.replace(/_/g, ' '));
break;
case 'B':
data = new Buffer(data, "base64");
break;
default:
logger.logerror("Invalid header encoding type: " + cte);
}
// convert with iconv if encoding != UTF-8
if (Iconv && !(/UTF-?8/i.test(encoding))) {
data = try_convert(data, encoding);
}
return data.toString();
}
Header.prototype.decode_header = function decode_header (val) {
// Fold continuations
val = val.replace(/\n[ \t]+/g, "\n ");
// remove end carriage return
val = val.replace(/\r?\n$/, '');
if (Iconv && !/^[\x00-\x7f]*$/.test(val)) {
// 8 bit values in the header
var matches = /\bcharset\s*=\s*["']?([\w_\-]*)/.exec(this.get('content-type'));
if (matches && !/UTF-?8/i.test(matches[1])) {
var encoding = matches[1];
var source = new Buffer(val, 'binary');
val = try_convert(source, encoding).toString();
}
}
if (! (/=\?/.test(val)) ) {
// no encoded stuff
return val;
}
val = val.replace(/=\?([\w_-]+)\?([bqBQ])\?(.*?)\?=/g, _decode_header);
return val;
}
Header.prototype.get = function (key) {
return (this.headers[key.toLowerCase()] || []).join("\n");
};
Header.prototype.get_all = function (key) {
return this.headers[key.toLowerCase()] || [];
};
Header.prototype.get_decoded = function (key) {
return (this.headers_decoded[key.toLowerCase()] || []).join("\n");
};
Header.prototype.remove = function (key) {
key = key.toLowerCase();
delete this.headers[key];
delete this.headers_decoded[key];
this._remove_more(key);
}
Header.prototype._remove_more = function (key) {
var key_len = key.length;
var to_remove;
for (var i=0,l=this.header_list.length; i < l; i++) {
if (this.header_list[i].substring(0, key_len).toLowerCase() === key) {
this.header_list.splice(i, 1);
return this._remove_more(key);
}
}
};
Header.prototype._add_header = function (key, value, method) {
this.headers[key] = this.headers[key] || [];
this.headers[key][method](value);
};
Header.prototype._add_header_decode = function (key, value, method) {
this.headers_decoded[key] = this.headers_decoded[key] || [];
this.headers_decoded[key][method](this.decode_header(value));
}
Header.prototype.add = function (key, value) {
value = value.replace(/(\r?\n)*$/, '');
this._add_header(key.toLowerCase(), value, "unshift");
this._add_header_decode(key.toLowerCase(), value, "unshift");
this.header_list.unshift(key + ': ' + value + '\n');
};
Header.prototype.add_end = function (key, value) {
value = value.replace(/(\r?\n)*$/, '');
this._add_header(key.toLowerCase(), value, "push");
this._add_header_decode(key.toLowerCase(), value, "push");
this.header_list.push(key + ': ' + value + '\n');
}
Header.prototype.lines = function () {
return this.header_list;
};
Header.prototype.toString = function () {
return this.header_list.join("\n");
};
| lucciano/Haraka | mailheader.js | JavaScript | mit | 5,423 |
(function () {
'use strict';
angular.module('com.module.events', []);
})();
| Jeff-Lewis/loopback-angular-admin | client/app/modules/events/app.events.js | JavaScript | mit | 80 |
'use strict';
var Utils = require('./utils')
, BelongsTo = require('./associations/belongs-to')
, BelongsToMany = require('./associations/belongs-to-many')
, InstanceValidator = require('./instance-validator')
, QueryTypes = require('./query-types')
, sequelizeErrors = require('./errors')
, Dottie = require('dottie')
, Promise = require('./promise')
, _ = require('lodash')
, defaultsOptions = { raw: true };
// private
var initValues = function(values, options) {
var defaults
, key;
values = values && _.clone(values) || {};
if (options.isNewRecord) {
defaults = {};
if (this.Model._hasDefaultValues) {
Utils._.each(this.Model._defaultValues, function(valueFn, key) {
if (defaults[key] === undefined) {
defaults[key] = valueFn();
}
});
}
// set id to null if not passed as value, a newly created dao has no id
// removing this breaks bulkCreate
// do after default values since it might have UUID as a default value
if (!defaults.hasOwnProperty(this.Model.primaryKeyAttribute)) {
defaults[this.Model.primaryKeyAttribute] = null;
}
if (this.Model._timestampAttributes.createdAt && defaults[this.Model._timestampAttributes.createdAt]) {
this.dataValues[this.Model._timestampAttributes.createdAt] = Utils.toDefaultValue(defaults[this.Model._timestampAttributes.createdAt]);
delete defaults[this.Model._timestampAttributes.createdAt];
}
if (this.Model._timestampAttributes.updatedAt && defaults[this.Model._timestampAttributes.updatedAt]) {
this.dataValues[this.Model._timestampAttributes.updatedAt] = Utils.toDefaultValue(defaults[this.Model._timestampAttributes.updatedAt]);
delete defaults[this.Model._timestampAttributes.updatedAt];
}
if (this.Model._timestampAttributes.deletedAt && defaults[this.Model._timestampAttributes.deletedAt]) {
this.dataValues[this.Model._timestampAttributes.deletedAt] = Utils.toDefaultValue(defaults[this.Model._timestampAttributes.deletedAt]);
delete defaults[this.Model._timestampAttributes.deletedAt];
}
if (Object.keys(defaults).length) {
for (key in defaults) {
if (values[key] === undefined) {
this.set(key, Utils.toDefaultValue(defaults[key]), defaultsOptions);
}
}
}
}
this.set(values, options);
};
/**
* This class represents an single instance, a database row. You might see it referred to as both Instance and instance. You should not
* instantiate the Instance class directly, instead you access it using the finder and creation methods on the model.
*
* Instance instances operate with the concept of a `dataValues` property, which stores the actual values represented by the instance.
* By default, the values from dataValues can also be accessed directly from the Instance, that is:
* ```js
* instance.field
* // is the same as
* instance.get('field')
* // is the same as
* instance.getDataValue('field')
* ```
* However, if getters and/or setters are defined for `field` they will be invoked, instead of returning the value from `dataValues`.
* Accessing properties directly or using `get` is preferred for regular use, `getDataValue` should only be used for custom getters.
*
* @see {Sequelize#define} for more information about getters and setters
* @class Instance
*/
var Instance = function(values, options) {
this.dataValues = {};
this._previousDataValues = {};
this._changed = {};
this.$modelOptions = this.Model.options;
this.$options = options || {};
this.hasPrimaryKeys = this.Model.options.hasPrimaryKeys;
this.__eagerlyLoadedAssociations = [];
/**
* Returns true if this instance has not yet been persisted to the database
* @property isNewRecord
* @return {Boolean}
*/
this.isNewRecord = options.isNewRecord;
/**
* Returns the Model the instance was created from.
* @see {Model}
* @property Model
* @return {Model}
*/
initValues.call(this, values, options);
};
/**
* A reference to the sequelize instance
* @see {Sequelize}
* @property sequelize
* @return {Sequelize}
*/
Object.defineProperty(Instance.prototype, 'sequelize', {
get: function() { return this.Model.modelManager.sequelize; }
});
/**
* Get an object representing the query for this instance, use with `options.where`
*
* @property where
* @return {Object}
*/
Instance.prototype.where = function() {
var where;
where = this.Model.primaryKeyAttributes.reduce(function (result, attribute) {
result[attribute] = this.get(attribute, {raw: true});
return result;
}.bind(this), {});
if (_.size(where) === 0) {
return this.$modelOptions.whereCollection;
}
return Utils.mapWhereFieldNames(where, this.$Model);
};
Instance.prototype.toString = function () {
return '[object SequelizeInstance:'+this.Model.name+']';
};
/**
* Get the value of the underlying data value
*
* @param {String} key
* @return {any}
*/
Instance.prototype.getDataValue = function(key) {
return this.dataValues[key];
};
/**
* Update the underlying data value
*
* @param {String} key
* @param {any} value
*/
Instance.prototype.setDataValue = function(key, value) {
var originalValue = this._previousDataValues[key];
if (!Utils.isPrimitive(value) || value !== originalValue) {
this.changed(key, true);
}
this.dataValues[key] = value;
};
/**
* If no key is given, returns all values of the instance, also invoking virtual getters.
*
* If key is given and a field or virtual getter is present for the key it will call that getter - else it will return the value for key.
*
* @param {String} [key]
* @param {Object} [options]
* @param {Boolean} [options.plain=false] If set to true, included instances will be returned as plain objects
* @return {Object|any}
*/
Instance.prototype.get = function(key, options) { // testhint options:none
if (options === undefined && typeof key === 'object') {
options = key;
key = undefined;
}
if (key) {
if (this._customGetters[key]) {
return this._customGetters[key].call(this, key);
}
if (options && options.plain && this.$options.include && this.$options.includeNames.indexOf(key) !== -1) {
if (Array.isArray(this.dataValues[key])) {
return this.dataValues[key].map(function (instance) {
return instance.get({plain: options.plain});
});
} else if (this.dataValues[key] instanceof Instance) {
return this.dataValues[key].get({plain: options.plain});
} else {
return this.dataValues[key];
}
}
return this.dataValues[key];
}
if (this._hasCustomGetters || (options && options.plain && this.$options.include) || (options && options.clone)) {
var values = {}
, _key;
if (this._hasCustomGetters) {
for (_key in this._customGetters) {
if (this._customGetters.hasOwnProperty(_key)) {
values[_key] = this.get(_key, options);
}
}
}
for (_key in this.dataValues) {
if (!values.hasOwnProperty(_key) && this.dataValues.hasOwnProperty(_key)) {
values[_key] = this.get(_key, options);
}
}
return values;
}
return this.dataValues;
};
/**
* Set is used to update values on the instance (the sequelize representation of the instance that is, remember that nothing will be persisted before you actually call `save`).
* In its most basic form `set` will update a value stored in the underlying `dataValues` object. However, if a custom setter function is defined for the key, that function
* will be called instead. To bypass the setter, you can pass `raw: true` in the options object.
*
* If set is called with an object, it will loop over the object, and call set recursively for each key, value pair. If you set raw to true, the underlying dataValues will either be
* set directly to the object passed, or used to extend dataValues, if dataValues already contain values.
*
* When set is called, the previous value of the field is stored and sets a changed flag(see `changed`).
*
* Set can also be used to build instances for associations, if you have values for those.
* When using set with associations you need to make sure the property key matches the alias of the association
* while also making sure that the proper include options have been set (from .build() or .find())
*
* If called with a dot.separated key on a JSON/JSONB attribute it will set the value nested and flag the entire object as changed.
*
* @see {Model#find} for more information about includes
* @param {String|Object} key
* @param {any} value
* @param {Object} [options]
* @param {Boolean} [options.raw=false] If set to true, field and virtual setters will be ignored
* @param {Boolean} [options.reset=false] Clear all previously set data values
* @alias setAttributes
*/
Instance.prototype.set = function(key, value, options) { // testhint options:none
var values
, originalValue
, keys
, i
, length;
if (typeof key === 'object' && key !== null) {
values = key;
options = value || {};
if (options.reset) {
this.dataValues = {};
}
// If raw, and we're not dealing with includes or special attributes, just set it straight on the dataValues object
if (options.raw && !(this.$options && this.$options.include) && !(options && options.attributes) && !this.Model._hasBooleanAttributes && !this.Model._hasDateAttributes) {
if (Object.keys(this.dataValues).length) {
this.dataValues = _.extend(this.dataValues, values);
} else {
this.dataValues = values;
}
// If raw, .changed() shouldn't be true
this._previousDataValues = _.clone(this.dataValues);
} else {
// Loop and call set
if (options.attributes) {
keys = options.attributes;
if (this.Model._hasVirtualAttributes) {
keys = keys.concat(this.Model._virtualAttributes);
}
if (this.$options.includeNames) {
keys = keys.concat(this.$options.includeNames);
}
for (i = 0, length = keys.length; i < length; i++) {
if (values[keys[i]] !== undefined) {
this.set(keys[i], values[keys[i]], options);
}
}
} else {
for (key in values) {
this.set(key, values[key], options);
}
}
if (options.raw) {
// If raw, .changed() shouldn't be true
this._previousDataValues = _.clone(this.dataValues);
}
}
} else {
if (!options)
options = {};
if (!options.raw) {
originalValue = this.dataValues[key];
}
// If not raw, and there's a customer setter
if (!options.raw && this._customSetters[key]) {
this._customSetters[key].call(this, value, key);
} else {
// Check if we have included models, and if this key matches the include model names/aliases
if (this.$options && this.$options.include && this.$options.includeNames.indexOf(key) !== -1) {
// Pass it on to the include handler
this._setInclude(key, value, options);
return this;
} else {
// Bunch of stuff we won't do when its raw
if (!options.raw) {
// If attribute is not in model definition, return
if (!this._isAttribute(key)) {
if (key.indexOf('.') > -1 && this.Model._isJsonAttribute(key.split('.')[0])) {
var previousDottieValue = Dottie.get(this.dataValues, key);
if (!_.isEqual(previousDottieValue, value)) {
Dottie.set(this.dataValues, key, value);
this.changed(key.split('.')[0], true);
}
}
return this;
}
// If attempting to set primary key and primary key is already defined, return
if (this.Model._hasPrimaryKeys && originalValue && this.Model._isPrimaryKey(key)) {
return this;
}
// If attempting to set read only attributes, return
if (!this.isNewRecord && this.Model._hasReadOnlyAttributes && this.Model._isReadOnlyAttribute(key)) {
return this;
}
// Convert date fields to real date objects
if (this.Model._hasDateAttributes && this.Model._isDateAttribute(key) && !!value && !value._isSequelizeMethod) {
if (!(value instanceof Date)) {
value = new Date(value);
}
if (!(originalValue instanceof Date)) {
originalValue = new Date(originalValue);
}
if (originalValue && value.getTime() === originalValue.getTime()) {
return this;
}
}
}
// Convert boolean-ish values to booleans
if (this.Model._hasBooleanAttributes && this.Model._isBooleanAttribute(key) && value !== null && value !== undefined && !value._isSequelizeMethod) {
if (Buffer.isBuffer(value) && value.length === 1) {
// Bit fields are returned as buffers
value = value[0];
}
if (_.isString(value)) {
// Only take action on valid boolean strings.
value = (value === 'true') ? true : (value === 'false') ? false : value;
} else if (_.isNumber(value)) {
// Only take action on valid boolean integers.
value = (value === 1) ? true : (value === 0) ? false : value;
}
}
if (!options.raw && ((!Utils.isPrimitive(value) && value !== null) || value !== originalValue)) {
this._previousDataValues[key] = originalValue;
this.changed(key, true);
}
this.dataValues[key] = value;
}
}
}
return this;
};
Instance.prototype.setAttributes = function(updates) {
return this.set(updates);
};
/**
* If changed is called with a string it will return a boolean indicating whether the value of that key in `dataValues` is different from the value in `_previousDataValues`.
*
* If changed is called without an argument, it will return an array of keys that have changed.
*
* If changed is called without an argument and no keys have changed, it will return `false`.
*
* @param {String} [key]
* @return {Boolean|Array}
*/
Instance.prototype.changed = function(key, value) {
if (key) {
if (value !== undefined) {
this._changed[key] = value;
return this;
}
return this._changed[key] || false;
}
var changed = Object.keys(this.dataValues).filter(function(key) {
return this.changed(key);
}.bind(this));
return changed.length ? changed : false;
};
/**
* Returns the previous value for key from `_previousDataValues`.
*
* If called without a key, returns the previous values for all values which have changed
*
* @param {String} [key]
* @return {any|Array<any>}
*/
Instance.prototype.previous = function(key) {
if (key) {
return this._previousDataValues[key];
}
return _.pickBy(this._previousDataValues, function(value, key) {
return this.changed(key);
}.bind(this));
};
Instance.prototype._setInclude = function(key, value, options) {
if (!Array.isArray(value)) value = [value];
if (value[0] instanceof Instance) {
value = value.map(function(instance) {
return instance.dataValues;
});
}
var include = this.$options.includeMap[key]
, association = include.association
, self = this
, accessor = key
, childOptions
, primaryKeyAttribute = include.model.primaryKeyAttribute
, isEmpty;
if (!isEmpty) {
childOptions = {
isNewRecord: this.isNewRecord,
include: include.include,
includeNames: include.includeNames,
includeMap: include.includeMap,
includeValidated: true,
raw: options.raw,
attributes: include.originalAttributes
};
}
if (include.originalAttributes === undefined || include.originalAttributes.length) {
if (association.isSingleAssociation) {
if (Array.isArray(value)) {
value = value[0];
}
isEmpty = (value && value[primaryKeyAttribute] === null) || (value === null);
self[accessor] = self.dataValues[accessor] = isEmpty ? null : include.model.build(value, childOptions);
} else {
isEmpty = value[0] && value[0][primaryKeyAttribute] === null;
self[accessor] = self.dataValues[accessor] = isEmpty ? [] : include.model.bulkBuild(value, childOptions);
}
}
};
/**
* Validate this instance, and if the validation passes, persist it to the database. It will only save changed fields, and do nothing if no fields have changed.
*
* On success, the callback will be called with this instance. On validation error, the callback will be called with an instance of `Sequelize.ValidationError`.
* This error will have a property for each of the fields for which validation failed, with the error message for that field.
*
* @param {Object} [options]
* @param {string[]} [options.fields] An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved.
* @param {Boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated.
* @param {Boolean} [options.validate=true] If false, validations won't be run.
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {Transaction} [options.transaction]
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
*
* @return {Promise<this|Errors.ValidationError>}
*/
Instance.prototype.save = function(options) {
if (arguments.length > 1) {
throw new Error('The second argument was removed in favor of the options object.');
}
options = this.$Model.$optClone(options || {});
options = _.defaults(options, {
hooks: true,
validate: true
});
if (!options.fields) {
if (this.isNewRecord) {
options.fields = Object.keys(this.Model.attributes);
} else {
options.fields = _.intersection(this.changed(), Object.keys(this.Model.attributes));
}
options.defaultFields = options.fields;
}
if (options.returning === undefined) {
if (options.association) {
options.returning = false;
} else if (this.isNewRecord) {
options.returning = true;
}
}
var self = this
, primaryKeyName = this.Model.primaryKeyAttribute
, primaryKeyAttribute = primaryKeyName && this.Model.rawAttributes[primaryKeyName]
, updatedAtAttr = this.Model._timestampAttributes.updatedAt
, createdAtAttr = this.Model._timestampAttributes.createdAt
, hook = self.isNewRecord ? 'Create' : 'Update'
, wasNewRecord = this.isNewRecord
, now = Utils.now(this.sequelize.options.dialect);
if (updatedAtAttr && options.fields.length >= 1 && options.fields.indexOf(updatedAtAttr) === -1) {
options.fields.push(updatedAtAttr);
}
if (options.silent === true && !(this.isNewRecord && this.get(updatedAtAttr, {raw: true}))) {
// UpdateAtAttr might have been added as a result of Object.keys(Model.attributes). In that case we have to remove it again
Utils._.remove(options.fields, function(val) {
return val === updatedAtAttr;
});
updatedAtAttr = false;
}
if (this.isNewRecord === true) {
if (createdAtAttr && options.fields.indexOf(createdAtAttr) === -1) {
options.fields.push(createdAtAttr);
}
if (primaryKeyAttribute && primaryKeyAttribute.defaultValue && options.fields.indexOf(primaryKeyName) < 0) {
options.fields.unshift(primaryKeyName);
}
}
if (this.isNewRecord === false) {
if (primaryKeyName && this.get(primaryKeyName, {raw: true}) === undefined) {
throw new Error('You attempted to save an instance with no primary key, this is not allowed since it would result in a global update');
}
}
if (updatedAtAttr && !options.silent && options.fields.indexOf(updatedAtAttr) !== -1) {
this.dataValues[updatedAtAttr] = this.Model.$getDefaultTimestamp(updatedAtAttr) || now;
}
if (this.isNewRecord && createdAtAttr && !this.dataValues[createdAtAttr]) {
this.dataValues[createdAtAttr] = this.Model.$getDefaultTimestamp(createdAtAttr) || now;
}
return Promise.bind(this).then(function() {
// Validate
if (options.validate) {
return Promise.bind(this).then(function () {
// hookValidate rejects with errors, validate returns with errors
if (options.hooks) return this.hookValidate(options);
return this.validate(options).then(function (err) {
if (err) throw err;
});
});
}
}).then(function() {
return Promise.bind(this).then(function() {
// Run before hook
if (options.hooks) {
var beforeHookValues = _.pick(this.dataValues, options.fields)
, afterHookValues
, hookChanged
, ignoreChanged = _.difference(this.changed(), options.fields); // In case of update where it's only supposed to update the passed values and the hook values
if (updatedAtAttr && options.fields.indexOf(updatedAtAttr) !== -1) {
ignoreChanged = _.without(ignoreChanged, updatedAtAttr);
}
return this.Model.runHooks('before' + hook, this, options).bind(this).then(function() {
if (options.defaultFields && !this.isNewRecord) {
afterHookValues = _.pick(this.dataValues, _.difference(this.changed(), ignoreChanged));
hookChanged = [];
Object.keys(afterHookValues).forEach(function (key) {
if (afterHookValues[key] !== beforeHookValues[key]) {
hookChanged.push(key);
}
});
options.fields = _.uniq(options.fields.concat(hookChanged));
}
if (hookChanged) {
if (options.validate) {
// Validate again
options.skip = _.difference(Object.keys(this.Model.rawAttributes), hookChanged);
return Promise.bind(this).then(function () {
// hookValidate rejects with errors, validate returns with errors
if (options.hooks) return this.hookValidate(options);
return this.validate(options).then(function (err) {
if (err) throw err;
});
}).then(function() {
delete options.skip;
});
}
}
});
}
}).then(function() {
if (!options.fields.length) return this;
if (!this.isNewRecord) return this;
if (!this.$options.include || !this.$options.include.length) return this;
// Nested creation for BelongsTo relations
return Promise.map(this.$options.include.filter(function (include) {
return include.association instanceof BelongsTo;
}), function (include) {
var instance = self.get(include.as);
if (!instance) return Promise.resolve();
return instance.save({
transaction: options.transaction,
logging: options.logging
}).then(function () {
return self[include.association.accessors.set](instance, {save: false, logging: options.logging});
});
});
})
.then(function() {
if (!options.fields.length) return this;
if (!this.changed() && !this.isNewRecord) return this;
var values = Utils.mapValueFieldNames(this.dataValues, options.fields, this.Model)
, query = null
, args = [];
if (self.isNewRecord) {
query = 'insert';
args = [self, self.$Model.getTableName(options), values, options];
} else {
var where = this.where();
where = Utils.mapValueFieldNames(where, Object.keys(where), this.Model);
query = 'update';
args = [self, self.$Model.getTableName(options), values, where, options];
}
return self.sequelize.getQueryInterface()[query].apply(self.sequelize.getQueryInterface(), args)
.then(function(result) {
// Transfer database generated values (defaults, autoincrement, etc)
Object.keys(self.Model.rawAttributes).forEach(function (attr) {
if (self.Model.rawAttributes[attr].field &&
values[self.Model.rawAttributes[attr].field] !== undefined &&
self.Model.rawAttributes[attr].field !== attr
) {
values[attr] = values[self.Model.rawAttributes[attr].field];
delete values[self.Model.rawAttributes[attr].field];
}
});
values = _.extend(values, result.dataValues);
result.dataValues = _.extend(result.dataValues, values);
return result;
})
.tap(function(result) {
// Run after hook
if (options.hooks) {
return self.Model.runHooks('after' + hook, result, options);
}
})
.then(function(result) {
options.fields.forEach(function (field) {
result._previousDataValues[field] = result.dataValues[field];
self.changed(field, false);
});
self.isNewRecord = false;
return result;
})
.tap(function() {
if (!wasNewRecord) return self;
if (!self.$options.include || !self.$options.include.length) return self;
// Nested creation for HasOne/HasMany/BelongsToMany relations
return Promise.map(self.$options.include.filter(function (include) {
return !(include.association instanceof BelongsTo);
}), function (include) {
var instances = self.get(include.as);
if (!instances) return Promise.resolve();
if (!Array.isArray(instances)) instances = [instances];
if (!instances.length) return Promise.resolve();
// Instances will be updated in place so we can safely treat HasOne like a HasMany
return Promise.map(instances, function (instance) {
if (include.association instanceof BelongsToMany) {
return instance.save({transaction: options.transaction, logging: options.logging}).then(function () {
var values = {};
values[include.association.foreignKey] = self.get(self.Model.primaryKeyAttribute, {raw: true});
values[include.association.otherKey] = instance.get(instance.Model.primaryKeyAttribute, {raw: true});
return include.association.throughModel.create(values, {transaction: options.transaction, logging: options.logging});
});
} else {
instance.set(include.association.foreignKey, self.get(self.Model.primaryKeyAttribute, {raw: true}));
return instance.save({transaction: options.transaction, logging: options.logging});
}
});
});
});
});
});
};
/*
* Refresh the current instance in-place, i.e. update the object with current data from the DB and return the same object.
* This is different from doing a `find(Instance.id)`, because that would create and return a new instance. With this method,
* all references to the Instance are updated with the new data and no new objects are created.
*
* @see {Model#find}
* @param {Object} [options] Options that are passed on to `Model.find`
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @return {Promise<this>}
*/
Instance.prototype.reload = function(options) {
options = _.defaults({}, options, {
where: this.where(),
include: this.$options.include || null
});
return this.Model.findOne(options).bind(this)
.tap(function (reload) {
if (!reload) {
throw new sequelizeErrors.InstanceError(
'Instance could not be reloaded because it does not exist anymore (find call returned null)'
);
}
})
.then(function(reload) {
// update the internal options of the instance
this.$options = reload.$options;
// re-set instance values
this.set(reload.dataValues, {
raw: true,
reset: true && !options.attributes
});
}).return(this);
};
/*
* Validate the attribute of this instance according to validation rules set in the model definition.
*
* Emits null if and only if validation successful; otherwise an Error instance containing { field name : [error msgs] } entries.
*
* @param {Object} [options] Options that are passed to the validator
* @param {Array} [options.skip] An array of strings. All properties that are in this array will not be validated
* @see {InstanceValidator}
*
* @return {Promise<undefined|Errors.ValidationError>}
*/
Instance.prototype.validate = function(options) {
return new InstanceValidator(this, options).validate();
};
Instance.prototype.hookValidate = function(options) {
return new InstanceValidator(this, options).hookValidate();
};
/**
* This is the same as calling `set` and then calling `save` but it only saves the
* exact values passed to it, making it more atomic and safer.
*
* @see {Instance#set}
* @see {Instance#save}
* @param {Object} updates See `set`
* @param {Object} options See `save`
*
* @return {Promise<this>}
* @alias updateAttributes
*/
Instance.prototype.update = function(values, options) {
var changedBefore = this.changed() || []
, sideEffects
, fields
, setOptions;
options = options || {};
if (Array.isArray(options)) options = {fields: options};
options = this.$Model.$optClone(options);
setOptions = this.$Model.$optClone(options);
setOptions.attributes = options.fields;
this.set(values, setOptions);
// Now we need to figure out which fields were actually affected by the setter.
sideEffects = _.without.apply(this, [this.changed() || []].concat(changedBefore));
fields = _.union(Object.keys(values), sideEffects);
if (!options.fields) {
options.fields = _.intersection(fields, this.changed());
options.defaultFields = options.fields;
}
return this.save(options);
};
Instance.prototype.updateAttributes = Instance.prototype.update;
/**
* Destroy the row corresponding to this instance. Depending on your setting for paranoid, the row will either be completely deleted, or have its deletedAt timestamp set to the current time.
*
* @param {Object} [options={}]
* @param {Boolean} [options.force=false] If set to true, paranoid models will actually be deleted
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {Transaction} [options.transaction]
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
*
* @return {Promise<undefined>}
*/
Instance.prototype.destroy = function(options) {
options = Utils._.extend({
hooks: true,
force: false
}, options);
return Promise.bind(this).then(function() {
// Run before hook
if (options.hooks) {
return this.Model.runHooks('beforeDestroy', this, options);
}
}).then(function() {
var where = this.where();
if (this.Model._timestampAttributes.deletedAt && options.force === false) {
var attribute = this.Model.rawAttributes[this.Model._timestampAttributes.deletedAt]
, field = attribute.field || this.Model._timestampAttributes.deletedAt
, values = {};
values[field] = new Date();
where[field] = attribute.hasOwnProperty('defaultValue') ? attribute.defaultValue : null;
this.setDataValue(field, values[field]);
return this.sequelize.getQueryInterface().update(this, this.$Model.getTableName(options), values, where, _.defaults({ hooks: false }, options));
} else {
return this.sequelize.getQueryInterface().delete(this, this.$Model.getTableName(options), where, _.assign({ type: QueryTypes.DELETE, limit: null }, options));
}
}).tap(function() {
// Run after hook
if (options.hooks) {
return this.Model.runHooks('afterDestroy', this, options);
}
}).then(function(result) {
return result;
});
};
/**
* Restore the row corresponding to this instance. Only available for paranoid models.
*
* @param {Object} [options={}]
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {Transaction} [options.transaction]
*
* @return {Promise<undefined>}
*/
Instance.prototype.restore = function(options) {
if (!this.Model._timestampAttributes.deletedAt) throw new Error('Model is not paranoid');
options = Utils._.extend({
hooks: true,
force: false
}, options);
return Promise.bind(this).then(function() {
// Run before hook
if (options.hooks) {
return this.Model.runHooks('beforeRestore', this, options);
}
}).then(function() {
var deletedAtCol = this.Model._timestampAttributes.deletedAt
, deletedAtAttribute = this.Model.rawAttributes[deletedAtCol]
, deletedAtDefaultValue = deletedAtAttribute.hasOwnProperty('defaultValue') ? deletedAtAttribute.defaultValue : null;
this.setDataValue(deletedAtCol, deletedAtDefaultValue);
return this.save(_.extend({}, options, {hooks : false, omitNull : false}));
}).tap(function() {
// Run after hook
if (options.hooks) {
return this.Model.runHooks('afterRestore', this, options);
}
});
};
/**
* Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a
* ```sql
* SET column = column + X
* ```
* query. To get the correct value after an increment into the Instance you should do a reload.
*
*```js
* instance.increment('number') // increment number by 1
* instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2
* instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42, and tries by 1.
* // `by` is ignored, since each column has its own value
* ```
*
* @see {Instance#reload}
* @param {String|Array|Object} fields If a string is provided, that column is incremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is incremented by the value given.
* @param {Object} [options]
* @param {Integer} [options.by=1] The number to increment by
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {Transaction} [options.transaction]
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
*
* @return {Promise<this>}
*/
Instance.prototype.increment = function(fields, options) {
var identifier = this.where()
, updatedAtAttr = this.Model._timestampAttributes.updatedAt
, values = {}
, where;
options = _.defaults({}, options, {
by: 1,
attributes: {},
where: {}
});
where = _.extend({}, options.where, identifier);
if (Utils._.isString(fields)) {
values[fields] = options.by;
} else if (Utils._.isArray(fields)) {
Utils._.each(fields, function(field) {
values[field] = options.by;
});
} else { // Assume fields is key-value pairs
values = fields;
}
if (updatedAtAttr && !values[updatedAtAttr]) {
options.attributes[updatedAtAttr] = this.Model.$getDefaultTimestamp(updatedAtAttr) || Utils.now(this.sequelize.options.dialect);
}
Object.keys(values).forEach(function(attr) {
// Field name mapping
if (this.Model.rawAttributes[attr] && this.Model.rawAttributes[attr].field && this.Model.rawAttributes[attr].field !== attr) {
values[this.Model.rawAttributes[attr].field] = values[attr];
delete values[attr];
}
}, this);
return this.sequelize.getQueryInterface().increment(this, this.$Model.getTableName(options), values, where, options).return(this);
};
/**
* Decrement the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The decrement is done using a
* ```sql
* SET column = column - X
* ```
* query. To get the correct value after an decrement into the Instance you should do a reload.
*
* ```js
* instance.decrement('number') // decrement number by 1
* instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2
* instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42, and tries by 1.
* // `by` is ignored, since each column has its own value
* ```
*
* @see {Instance#reload}
* @param {String|Array|Object} fields If a string is provided, that column is decremented by the value of `by` given in options. If an array is provided, the same is true for each column. If and object is provided, each column is decremented by the value given
* @param {Object} [options]
* @param {Integer} [options.by=1] The number to decrement by
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {Transaction} [options.transaction]
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
*
* @return {Promise}
*/
Instance.prototype.decrement = function(fields, options) {
options = _.defaults({}, options, {
by: 1
});
if (!Utils._.isString(fields) && !Utils._.isArray(fields)) { // Assume fields is key-value pairs
Utils._.each(fields, function(value, field) {
fields[field] = -value;
});
}
options.by = 0 - options.by;
return this.increment(fields, options);
};
/**
* Check whether all values of this and `other` Instance are the same
*
* @param {Instance} other
* @return {Boolean}
*/
Instance.prototype.equals = function(other) {
var result = true;
if (!other || !other.dataValues) {
return false;
}
Utils._.each(this.dataValues, function(value, key) {
if (Utils._.isDate(value) && Utils._.isDate(other.dataValues[key])) {
result = result && (value.getTime() === other.dataValues[key].getTime());
} else {
result = result && (value === other.dataValues[key]);
}
});
return result;
};
/**
* Check if this is equal to one of `others` by calling equals
*
* @param {Array} others
* @return {Boolean}
*/
Instance.prototype.equalsOneOf = function(others) {
var self = this;
return _.some(others, function(other) {
return self.equals(other);
});
};
Instance.prototype.setValidators = function(attribute, validators) {
this.validators[attribute] = validators;
};
/**
* Convert the instance to a JSON representation. Proxies to calling `get` with no keys. This means get all values gotten from the DB, and apply all custom getters.
*
* @see {Instance#get}
* @return {object}
*/
Instance.prototype.toJSON = function() {
return this.get({
plain: true
});
};
module.exports = Instance;
| ja-marin/Proyecto-Quiz | node_modules/sequelize/lib/instance.js | JavaScript | mit | 39,117 |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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.
/**
* @fileoverview Utilities for creating functions. Loosely inspired by the
* java classes: http://go/functions.java and http://go/predicate.java.
*
* @author [email protected] (Nick Santos)
*/
goog.provide('goog.functions');
/**
* Creates a function that always returns the same value.
* @param {*} retValue The value to return.
* @return {!Function} The new function.
*/
goog.functions.constant = function(retValue) {
return function() {
return retValue;
};
};
/**
* Always returns false.
* @type {function(...): boolean}
*/
goog.functions.FALSE = goog.functions.constant(false);
/**
* Always returns true.
* @type {function(...): boolean}
*/
goog.functions.TRUE = goog.functions.constant(true);
/**
* Always returns NULL.
* @type {function(...): null}
*/
goog.functions.NULL = goog.functions.constant(null);
/**
* A simple function that returns the first argument of whatever is passed
* into it.
* @param {*=} opt_returnValue The single value that will be returned.
* @param {...*} var_args Optional trailing arguments. These are ignored.
* @return {?} The first argument passed in, or undefined if nothing was passed.
* We can't know the type -- just pass it along without type.
*/
goog.functions.identity = function(opt_returnValue, var_args) {
return opt_returnValue;
};
/**
* Creates a function that always throws an error with the given message.
* @param {string} message The error message.
* @return {!Function} The error-throwing function.
*/
goog.functions.error = function(message) {
return function() {
throw Error(message);
};
};
/**
* Given a function, create a function that silently discards all additional
* arguments.
* @param {Function} f The original function.
* @return {!Function} A version of f that discards its arguments.
*/
goog.functions.lock = function(f) {
return function() {
return f.call(this);
};
};
/**
* Given a function, create a new function that swallows its return value
* and replaces it with a new one.
* @param {Function} f A function.
* @param {*} retValue A new return value.
* @return {!Function} A new function.
*/
goog.functions.withReturnValue = function(f, retValue) {
return goog.functions.sequence(f, goog.functions.constant(retValue));
};
/**
* Creates the composition of the functions passed in.
* For example, (goog.functions.compose(f, g))(a) is equivalent to f(g(a)).
* @param {...Function} var_args A list of functions.
* @return {!Function} The composition of all inputs.
*/
goog.functions.compose = function(var_args) {
var functions = arguments;
var length = functions.length;
return function() {
var result;
if (length) {
result = functions[length - 1].apply(this, arguments);
}
for (var i = length - 2; i >= 0; i--) {
result = functions[i].call(this, result);
}
return result;
};
};
/**
* Creates a function that calls the functions passed in in sequence, and
* returns the value of the last function. For example,
* (goog.functions.sequence(f, g))(x) is equivalent to f(x),g(x).
* @param {...Function} var_args A list of functions.
* @return {!Function} A function that calls all inputs in sequence.
*/
goog.functions.sequence = function(var_args) {
var functions = arguments;
var length = functions.length;
return function() {
var result;
for (var i = 0; i < length; i++) {
result = functions[i].apply(this, arguments);
}
return result;
};
};
/**
* Creates a function that returns true if each of its components evaluates
* to true. The components are evaluated in order, and the evaluation will be
* short-circuited as soon as a function returns false.
* For example, (goog.functions.and(f, g))(x) is equivalent to f(x) && g(x).
* @param {...Function} var_args A list of functions.
* @return {!Function} A function that ANDs its component functions.
*/
goog.functions.and = function(var_args) {
var functions = arguments;
var length = functions.length;
return function() {
for (var i = 0; i < length; i++) {
if (!functions[i].apply(this, arguments)) {
return false;
}
}
return true;
};
};
/**
* Creates a function that returns true if any of its components evaluates
* to true. The components are evaluated in order, and the evaluation will be
* short-circuited as soon as a function returns true.
* For example, (goog.functions.or(f, g))(x) is equivalent to f(x) || g(x).
* @param {...Function} var_args A list of functions.
* @return {!Function} A function that ORs its component functions.
*/
goog.functions.or = function(var_args) {
var functions = arguments;
var length = functions.length;
return function() {
for (var i = 0; i < length; i++) {
if (functions[i].apply(this, arguments)) {
return true;
}
}
return false;
};
};
/**
* Creates a function that returns the Boolean opposite of a provided function.
* For example, (goog.functions.not(f))(x) is equivalent to !f(x).
* @param {!Function} f The original function.
* @return {!Function} A function that delegates to f and returns opposite.
*/
goog.functions.not = function(f) {
return function() {
return !f.apply(this, arguments);
};
};
/**
* Generic factory function to construct an object given the constructor
* and the arguments. Intended to be bound to create object factories.
*
* Callers should cast the result to the appropriate type for proper type
* checking by the compiler.
* @param {!Function} constructor The constructor for the Object.
* @param {...*} var_args The arguments to be passed to the constructor.
* @return {!Object} A new instance of the class given in {@code constructor}.
*/
goog.functions.create = function(constructor, var_args) {
/** @constructor */
var temp = function() {};
temp.prototype = constructor.prototype;
// obj will have constructor's prototype in its chain and
// 'obj instanceof constructor' will be true.
var obj = new temp();
// obj is initialized by constructor.
// arguments is only array-like so lacks shift(), but can be used with
// the Array prototype function.
constructor.apply(obj, Array.prototype.slice.call(arguments, 1));
return obj;
};
| AppScale/appinventor | war/closure-library-20120710-r2029/closure/goog/functions/functions.js | JavaScript | mit | 6,887 |
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2012, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* Contributor(s):
*
*
*
* ***** END LICENSE BLOCK ***** */
/*
THIS FILE WAS AUTOGENERATED BY mode.tmpl.js
*/
define(function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var %language%HighlightRules = require("./%languageHighlightFilename%_highlight_rules").%language%HighlightRules;
// TODO: pick appropriate fold mode
var FoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
var highlighter = new %language%HighlightRules();
this.foldingRules = new FoldMode();
this.$tokenizer = new Tokenizer(highlighter.getRules());
};
oop.inherits(Mode, TextMode);
(function() {
// Extra logic goes here.
}).call(Mode.prototype);
exports.Mode = Mode;
}); | i5ting/mdpreview | vendor/ace-master/tool/mode.tmpl.js | JavaScript | mit | 2,457 |
let map = new Map
map.set(55, "hello")
map.get(55) //: string
for (let val of map.values())
val //: string
for (let key of map.keys())
key //: number
for (let [key, value] of map) {
key //: number
value //: string
}
for (let pair of map) {
pair //: [number, string]
;[key, value] = pair
key //: number
value //: string
}
map.forEach(function(val, key) {
val //: string
key //: number
})
| MarcelGerber/tern | test/cases/map.js | JavaScript | mit | 412 |
/*
* /MathJax/extensions/TeX/autobold.js
*
* Copyright (c) 2009-2017 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Extension["TeX/autobold"]={version:"2.7.2-beta.1"};MathJax.Hub.Register.StartupHook("TeX Jax Ready",function(){var a=MathJax.InputJax.TeX;a.prefilterHooks.Add(function(d){var c=d.script.parentNode.insertBefore(document.createElement("span"),d.script);c.visibility="hidden";c.style.fontFamily="Times, serif";c.appendChild(document.createTextNode("ABCXYZabcxyz"));var b=c.offsetWidth;c.style.fontWeight="bold";if(b&&c.offsetWidth===b){d.math="\\boldsymbol{"+d.math+"}"}c.parentNode.removeChild(c)});MathJax.Hub.Startup.signal.Post("TeX autobold Ready")});MathJax.Ajax.loadComplete("[MathJax]/extensions/TeX/autobold.js");
| zdchao/php_demo | mathjax/extensions/TeX/autobold.js | JavaScript | apache-2.0 | 1,297 |
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* First expression is evaluated first, and then second expression
*
* @path ch11/11.5/11.5.2/S11.5.2_A2.4_T2.js
* @description Checking with "throw"
*/
//CHECK#1
var x = function () { throw "x"; };
var y = function () { throw "y"; };
try {
x() / y();
$ERROR('#1.1: var x = function () { throw "x"; }; var y = function () { throw "y"; }; x() / y() throw "x". Actual: ' + (x() / y()));
} catch (e) {
if (e === "y") {
$ERROR('#1.2: First expression is evaluated first, and then second expression');
} else {
if (e !== "x") {
$ERROR('#1.3: var x = function () { throw "x"; }; var y = function () { throw "y"; }; x() / y() throw "x". Actual: ' + (e));
}
}
}
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch11/11.5/11.5.2/S11.5.2_A2.4_T2.js | JavaScript | bsd-3-clause | 762 |
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* The form (?! Disjunction ) specifies a zero-width negative lookahead.
* In order for it to succeed, the pattern inside Disjunction must fail to match at the current position.
* The current position is not advanced before matching the sequel
*
* @path ch15/15.10/15.10.2/15.10.2.8/S15.10.2.8_A2_T2.js
* @description Execute /Java(?!Script)([A-Z]\w*)/.exec("using of JavaBeans technology") and check results
*/
__executed = /Java(?!Script)([A-Z]\w*)/.exec("using of JavaBeans technology");
__expected = ["JavaBeans", "Beans"];
__expected.index = 9;
__expected.input = "using of JavaBeans technology";
//CHECK#1
if (__executed.length !== __expected.length) {
$ERROR('#1: __executed = /Java(?!Script)([A-Z]\\w*)/.exec("using of JavaBeans technology"); __executed.length === ' + __expected.length + '. Actual: ' + __executed.length);
}
//CHECK#2
if (__executed.index !== __expected.index) {
$ERROR('#2: __executed = /Java(?!Script)([A-Z]\\w*)/.exec("using of JavaBeans technology"); __executed.index === ' + __expected.index + '. Actual: ' + __executed.index);
}
//CHECK#3
if (__executed.input !== __expected.input) {
$ERROR('#3: __executed = /Java(?!Script)([A-Z]\\w*)/.exec("using of JavaBeans technology"); __executed.input === ' + __expected.input + '. Actual: ' + __executed.input);
}
//CHECK#4
for(var index=0; index<__expected.length; index++) {
if (__executed[index] !== __expected[index]) {
$ERROR('#4: __executed = /Java(?!Script)([A-Z]\\w*)/.exec("using of JavaBeans technology"); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]);
}
}
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch15/15.10/15.10.2/15.10.2.8/S15.10.2.8_A2_T2.js | JavaScript | bsd-3-clause | 1,669 |
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* The production x /= y is the same as x = x / y
*
* @path ch11/11.13/11.13.2/S11.13.2_A4.2_T2.4.js
* @description Type(x) is different from Type(y) and both types vary between Number (primitive or object) and Undefined
*/
//CHECK#1
x = 1;
x /= undefined;
if (isNaN(x) !== true) {
$ERROR('#1: x = 1; x /= undefined; x === Not-a-Number. Actual: ' + (x));
}
//CHECK#2
x = undefined;
x /= 1;
if (isNaN(x) !== true) {
$ERROR('#2: x = undefined; x /= 1; x === Not-a-Number. Actual: ' + (x));
}
//CHECK#3
x = new Number(1);
x /= undefined;
if (isNaN(x) !== true) {
$ERROR('#3: x = new Number(1); x /= undefined; x === Not-a-Number. Actual: ' + (x));
}
//CHECK#4
x = undefined;
x /= new Number(1);
if (isNaN(x) !== true) {
$ERROR('#4: x = undefined; x /= new Number(1); x === Not-a-Number. Actual: ' + (x));
}
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch11/11.13/11.13.2/S11.13.2_A4.2_T2.4.js | JavaScript | bsd-3-clause | 886 |
ace.define("ace/snippets/scheme",["require","exports","module"],function(e,t,n){"use strict";t.snippetText=undefined,t.scope="scheme"}); (function() {
ace.require(["ace/snippets/scheme"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
| Heigvd/Wegas | wegas-resources/src/main/webapp/lib/ace/src-min-noconflict/snippets/scheme.js | JavaScript | mit | 466 |
define(
//begin v1.x content
{
"field-second": "秒",
"field-year-relative+-1": "昨年",
"field-week": "週",
"field-month-relative+-1": "先月",
"field-day-relative+-1": "昨日",
"months-format-narrow": [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12"
],
"field-day-relative+-2": "一昨日",
"months-standAlone-narrow": [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12"
],
"months-standAlone-wide": [
"カイトラ",
"ヴァイサカ",
"ジャイスタ",
"アーサダ",
"スラバナ",
"バードラ",
"アスビナ",
"カルディカ",
"アヴラハヤナ",
"パウサ",
"マーガ",
"パルグナ"
],
"field-year": "年",
"field-week-relative+0": "今週",
"months-standAlone-abbr": [
"カイトラ",
"ヴァイサカ",
"ジャイスタ",
"アーサダ",
"スラバナ",
"バードラ",
"アスビナ",
"カルディカ",
"アヴラハヤナ",
"パウサ",
"マーガ",
"パルグナ"
],
"field-week-relative+1": "翌週",
"field-minute": "分",
"field-week-relative+-1": "先週",
"field-day-relative+0": "今日",
"field-hour": "時",
"field-day-relative+1": "明日",
"field-day-relative+2": "明後日",
"field-day": "日",
"field-month-relative+0": "今月",
"field-month-relative+1": "翌月",
"field-dayperiod": "午前/午後",
"field-month": "月",
"months-format-wide": [
"カイトラ",
"ヴァイサカ",
"ジャイスタ",
"アーサダ",
"スラバナ",
"バードラ",
"アスビナ",
"カルディカ",
"アヴラハヤナ",
"パウサ",
"マーガ",
"パルグナ"
],
"field-era": "時代",
"field-year-relative+0": "今年",
"field-year-relative+1": "翌年",
"months-format-abbr": [
"カイトラ",
"ヴァイサカ",
"ジャイスタ",
"アーサダ",
"スラバナ",
"バードラ",
"アスビナ",
"カルディカ",
"アヴラハヤナ",
"パウサ",
"マーガ",
"パルグナ"
],
"eraAbbr": [
"サカ"
],
"field-weekday": "曜日",
"field-zone": "タイムゾーン"
}
//end v1.x content
); | algogr/Site | web/js/dojo/dojo/cldr/nls/ja/indian.js | JavaScript | mit | 2,137 |
define([
"dojo/_base/lang",
"./_PickerChooser!DatePicker"
], function(lang, DatePicker){
// module:
// dojox/mobile/DatePicker
// TODO: need to list all the properties/methods in the interface provided by
// SpinWheelDatePicker / ValuePickerDatePicker
/*=====
return function(){
// summary:
// A wrapper widget around SpinWheelDatePicker or ValuePickerDatePicker.
// It should be used with the automatic theme loader, dojox/mobile/deviceTheme.
// Returns ValuePickerDatePicker when the current theme is "android" or "holodark".
// Returns SpinWheelDatePicker otherwise.
};
=====*/
return lang.setObject("dojox.mobile.DatePicker", DatePicker);
});
| avz-cmf/zaboy-middleware | www/js/dojox/mobile/DatePicker.js | JavaScript | gpl-3.0 | 678 |
// META: global=window,worker
// META: script=../resources/utils.js
function checkFetchResponse(url, data, mime, fetchMode, method) {
var cut = (url.length >= 40) ? "[...]" : "";
var desc = "Fetching " + (method ? "[" + method + "] " : "") + url.substring(0, 40) + cut + " is OK";
var init = {"method": method || "GET"};
if (fetchMode) {
init.mode = fetchMode;
desc += " (" + fetchMode + ")";
}
promise_test(function(test) {
return fetch(url, init).then(function(resp) {
assert_equals(resp.status, 200, "HTTP status is 200");
assert_equals(resp.statusText, "OK", "HTTP statusText is OK");
assert_equals(resp.type, "basic", "response type is basic");
assert_equals(resp.headers.get("Content-Type"), mime, "Content-Type is " + resp.headers.get("Content-Type"));
return resp.text();
}).then(function(body) {
assert_equals(body, data, "Response's body is correct");
});
}, desc);
}
checkFetchResponse("data:,response%27s%20body", "response's body", "text/plain;charset=US-ASCII");
checkFetchResponse("data:,response%27s%20body", "response's body", "text/plain;charset=US-ASCII", "same-origin");
checkFetchResponse("data:,response%27s%20body", "response's body", "text/plain;charset=US-ASCII", "cors");
checkFetchResponse("data:text/plain;base64,cmVzcG9uc2UncyBib2R5", "response's body", "text/plain");
checkFetchResponse("data:image/png;base64,cmVzcG9uc2UncyBib2R5",
"response's body",
"image/png");
checkFetchResponse("data:,response%27s%20body", "response's body", "text/plain;charset=US-ASCII", null, "POST");
checkFetchResponse("data:,response%27s%20body", "", "text/plain;charset=US-ASCII", null, "HEAD");
function checkKoUrl(url, method, desc) {
var cut = (url.length >= 40) ? "[...]" : "";
desc = "Fetching [" + method + "] " + url.substring(0, 45) + cut + " is KO"
promise_test(function(test) {
return promise_rejects_js(test, TypeError, fetch(url, {"method": method}));
}, desc);
}
checkKoUrl("data:notAdataUrl.com", "GET");
| scheib/chromium | third_party/blink/web_tests/external/wpt/fetch/api/basic/scheme-data.any.js | JavaScript | bsd-3-clause | 2,055 |
// ==UserScript==
// @id iitc-plugin-highlight-portals-my-level@vita10gy
// @name IITC plugin: highlight portals by my level
// @category Highlighter
// @version 0.1.2.@@DATETIMEVERSION@@
// @namespace https://github.com/jonatkins/ingress-intel-total-conversion
// @updateURL @@UPDATEURL@@
// @downloadURL @@DOWNLOADURL@@
// @description [@@BUILDNAME@@-@@BUILDDATE@@] Use the portal fill color to denote if the portal is either at and above, or at and below your level.
// @include https://www.ingress.com/intel*
// @include http://www.ingress.com/intel*
// @match https://www.ingress.com/intel*
// @match http://www.ingress.com/intel*
// @include https://www.ingress.com/mission/*
// @include http://www.ingress.com/mission/*
// @match https://www.ingress.com/mission/*
// @match http://www.ingress.com/mission/*
// @grant none
// ==/UserScript==
@@PLUGINSTART@@
// PLUGIN START ////////////////////////////////////////////////////////
// use own namespace for plugin
window.plugin.portalHighlighterPortalsMyLevel = function() {};
window.plugin.portalHighlighterPortalsMyLevel.belowLevel = function(data) {
window.plugin.portalHighlighterPortalsMyLevel.colorLevel(true,data);
}
window.plugin.portalHighlighterPortalsMyLevel.aboveLevel = function(data) {
window.plugin.portalHighlighterPortalsMyLevel.colorLevel(false,data);
}
window.plugin.portalHighlighterPortalsMyLevel.colorLevel = function(below,data) {
var portal_level = data.portal.options.level;
// as portal levels can never be higher than L8, clamp the player level to this for highlight purposes
var player_level = Math.min(PLAYER.level,8);
var opacity = .6;
if((below && portal_level <= player_level) ||
(!below && portal_level >= player_level)) {
data.portal.setStyle({fillColor: 'red', fillOpacity: opacity});
}
}
var setup = function() {
window.addPortalHighlighter('Below My Level', window.plugin.portalHighlighterPortalsMyLevel.belowLevel);
window.addPortalHighlighter('Above My Level', window.plugin.portalHighlighterPortalsMyLevel.aboveLevel);
}
// PLUGIN END //////////////////////////////////////////////////////////
@@PLUGINEND@@
| adostes/ingress-intel-total-conversion | plugins/portal-highlighter-portals-my-level.user.js | JavaScript | isc | 2,270 |
/**
* Get the parent template instance
* @param {Number} [levels] How many levels to go up. Default is 1
* @returns {Blaze.TemplateInstance}
*/
Blaze.TemplateInstance.prototype.parentTemplate = function(levels) {
let view = Blaze.currentView;
if (typeof levels === 'undefined') {
levels = 1;
}
while (view) {
if (view.name.substring(0, 9) === 'Template.' && !(levels--)) {
return view.templateInstance();
}
view = view.parentView;
}
};
| pitamar/Rocket.Chat | packages/rocketchat-ui/client/lib/parentTemplate.js | JavaScript | mit | 457 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/licenses/publicdomain/
*/
function obj() {
var o = {all: 1, nowrite: 1, noconfig: 1, noble: 1};
Object.defineProperty(o, 'nowrite', {writable: false});
Object.defineProperty(o, 'noconfig', {configurable: false});
Object.defineProperty(o, 'noble', {writable: false, configurable: false});
return o;
}
assertEq(testLenientAndStrict('var o = obj(); o.all = 2; o.all',
returns(2), returns(2)),
true);
assertEq(testLenientAndStrict('var o = obj(); o.nowrite = 2; o.nowrite',
returns(1), raisesException(TypeError)),
true);
assertEq(testLenientAndStrict('var o = obj(); o.noconfig = 2; o.noconfig',
returns(2), returns(2)),
true);
assertEq(testLenientAndStrict('var o = obj(); o.noble = 2; o.noble',
returns(1), raisesException(TypeError)),
true);
assertEq(testLenientAndStrict('obj().nowrite++',
returns(1), raisesException(TypeError)),
true);
assertEq(testLenientAndStrict('++obj().nowrite',
returns(2), raisesException(TypeError)),
true);
assertEq(testLenientAndStrict('obj().nowrite--',
returns(1), raisesException(TypeError)),
true);
assertEq(testLenientAndStrict('--obj().nowrite',
returns(0), raisesException(TypeError)),
true);
function arr() {
return Object.defineProperties([1, 1, 1, 1],
{ 1: { writable: false },
2: { configurable: false },
3: { writable: false, configurable: false }});
}
assertEq(testLenientAndStrict('var a = arr(); a[0] = 2; a[0]',
returns(2), returns(2)),
true);
assertEq(testLenientAndStrict('var a = arr(); a[1] = 2; a[1]',
returns(1), raisesException(TypeError)),
true);
assertEq(testLenientAndStrict('var a = arr(); a[2] = 2; a[2]',
returns(2), returns(2)),
true);
assertEq(testLenientAndStrict('var a = arr(); a[3] = 2; a[3]',
returns(1), raisesException(TypeError)),
true);
assertEq(testLenientAndStrict('arr()[1]++',
returns(1), raisesException(TypeError)),
true);
assertEq(testLenientAndStrict('++arr()[1]',
returns(2), raisesException(TypeError)),
true);
assertEq(testLenientAndStrict('arr()[1]--',
returns(1), raisesException(TypeError)),
true);
assertEq(testLenientAndStrict('--arr()[1]',
returns(0), raisesException(TypeError)),
true);
reportCompare(true, true);
| darkrsw/safe | tests/parser_tests/js/src/tests/ecma_5/strict/8.12.5.js | JavaScript | bsd-3-clause | 3,022 |
/* */
"use strict";
exports.__esModule = true;
var _defineProperty = require('../core-js/object/define-property');
var _defineProperty2 = _interopRequireDefault(_defineProperty);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
exports.default = function(obj, key, value) {
if (key in obj) {
(0, _defineProperty2.default)(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
};
| entoj/entoj-core | test/__fixtures__/Application/Compact/entoj/jspm_packages/npm/[email protected]/helpers/defineProperty.js | JavaScript | apache-2.0 | 541 |
const test = require('tap').test
, testCommon = require('abstract-leveldown/testCommon')
, leveldown = require('../')
var db
test('setUp common', testCommon.setUp)
test('setUp db', function (t) {
db = leveldown(testCommon.location())
db.open(t.end.bind(t))
})
test('test argument-less getProperty() throws', function (t) {
t.throws(
db.getProperty.bind(db)
, { name: 'Error', message: 'getProperty() requires a valid `property` argument' }
, 'no-arg getProperty() throws'
)
t.end()
})
test('test non-string getProperty() throws', function (t) {
t.throws(
db.getProperty.bind(db, {})
, { name: 'Error', message: 'getProperty() requires a valid `property` argument' }
, 'no-arg getProperty() throws'
)
t.end()
})
test('test invalid getProperty() returns empty string', function (t) {
t.equal(db.getProperty('foo'), '', 'invalid property')
t.equal(db.getProperty('leveldb.foo'), '', 'invalid leveldb.* property')
t.end()
})
test('test invalid getProperty("leveldb.num-files-at-levelN") returns numbers', function (t) {
for (var i = 0; i < 7; i++)
t.equal(db.getProperty('leveldb.num-files-at-level' + i), '0', '"leveldb.num-files-at-levelN" === "0"')
t.end()
})
test('test invalid getProperty("leveldb.stats")', function (t) {
t.ok(db.getProperty('leveldb.stats').split('\n').length > 3, 'leveldb.stats has > 3 newlines')
t.end()
})
test('test invalid getProperty("leveldb.sstables")', function (t) {
var expected = [0,1,2,3,4,5,6].map(function (l) { return '--- level ' + l + ' ---' }).join('\n') + '\n'
t.equal(db.getProperty('leveldb.sstables'), expected, 'leveldb.sstables')
t.end()
})
test('tearDown', function (t) {
db.close(testCommon.tearDown.bind(null, t))
}) | santiagogil/mis-e-recursos | node_modules/pouchdb/node_modules/leveldown/test/getproperty-test.js | JavaScript | gpl-3.0 | 1,760 |
export default function debounce(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:166;function r(){for(var r=arguments.length,o=new Array(r),u=0;u<r;u++)o[u]=arguments[u];var a=this;clearTimeout(t),t=setTimeout(function(){e.apply(a,o)},n)}return r.clear=function(){clearTimeout(t)},r}; | cdnjs/cdnjs | ajax/libs/material-ui/5.0.0-alpha.2/esm/utils/debounce.min.js | JavaScript | mit | 302 |
/*! hyperform.js.org */
var hyperform = (function () {
'use strict';
var registry = Object.create(null);
/**
* run all actions registered for a hook
*
* Every action gets called with a state object as `this` argument and with the
* hook's call arguments as call arguments.
*
* @return mixed the returned value of the action calls or undefined
*/
function call_hook(hook) {
var result;
var call_args = Array.prototype.slice.call(arguments, 1);
if (hook in registry) {
result = registry[hook].reduce(function (args) {
return function (previousResult, currentAction) {
var interimResult = currentAction.apply({
state: previousResult,
hook: hook
}, args);
return interimResult !== undefined ? interimResult : previousResult;
};
}(call_args), result);
}
return result;
}
/**
* Filter a value through hooked functions
*
* Allows for additional parameters:
* js> do_filter('foo', null, current_element)
*/
function do_filter(hook, initial_value) {
var result = initial_value;
var call_args = Array.prototype.slice.call(arguments, 1);
if (hook in registry) {
result = registry[hook].reduce(function (previousResult, currentAction) {
call_args[0] = previousResult;
var interimResult = currentAction.apply({
state: previousResult,
hook: hook
}, call_args);
return interimResult !== undefined ? interimResult : previousResult;
}, result);
}
return result;
}
/**
* remove an action again
*/
function remove_hook(hook, action) {
if (hook in registry) {
for (var i = 0; i < registry[hook].length; i++) {
if (registry[hook][i] === action) {
registry[hook].splice(i, 1);
break;
}
}
}
}
/**
* add an action to a hook
*/
function add_hook(hook, action, position) {
if (!(hook in registry)) {
registry[hook] = [];
}
if (position === undefined) {
position = registry[hook].length;
}
registry[hook].splice(position, 0, action);
}
/**
* return either the data of a hook call or the result of action, if the
* former is undefined
*
* @return function a function wrapper around action
*/
function return_hook_or (hook, action) {
return function () {
var data = call_hook(hook, Array.prototype.slice.call(arguments));
if (data !== undefined) {
return data;
}
return action.apply(this, arguments);
};
}
/* the following code is borrowed from the WebComponents project, licensed
* under the BSD license. Source:
* <https://github.com/webcomponents/webcomponentsjs/blob/5283db1459fa2323e5bfc8b9b5cc1753ed85e3d0/src/WebComponents/dom.js#L53-L78>
*/
// defaultPrevented is broken in IE.
// https://connect.microsoft.com/IE/feedback/details/790389/event-defaultprevented-returns-false-after-preventdefault-was-called
var workingDefaultPrevented = function () {
var e = document.createEvent('Event');
e.initEvent('foo', true, true);
e.preventDefault();
return e.defaultPrevented;
}();
if (!workingDefaultPrevented) {
(function () {
var origPreventDefault = window.Event.prototype.preventDefault;
window.Event.prototype.preventDefault = function () {
if (!this.cancelable) {
return;
}
origPreventDefault.call(this);
Object.defineProperty(this, 'defaultPrevented', {
get: function get() {
return true;
},
configurable: true
});
};
})();
}
/* end of borrowed code */
function create_event(name) {
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _ref$bubbles = _ref.bubbles;
var bubbles = _ref$bubbles === undefined ? true : _ref$bubbles;
var _ref$cancelable = _ref.cancelable;
var cancelable = _ref$cancelable === undefined ? false : _ref$cancelable;
var event = document.createEvent('Event');
event.initEvent(name, bubbles, cancelable);
return event;
}
function trigger_event (element, event) {
var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var _ref2$bubbles = _ref2.bubbles;
var bubbles = _ref2$bubbles === undefined ? true : _ref2$bubbles;
var _ref2$cancelable = _ref2.cancelable;
var cancelable = _ref2$cancelable === undefined ? false : _ref2$cancelable;
var payload = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
if (!(event instanceof window.Event)) {
event = create_event(event, { bubbles: bubbles, cancelable: cancelable });
}
for (var key in payload) {
if (payload.hasOwnProperty(key)) {
event[key] = payload[key];
}
}
element.dispatchEvent(event);
return event;
}
/* and datetime-local? Spec says “Nah!” */
var dates = ['datetime', 'date', 'month', 'week', 'time'];
var plain_numbers = ['number', 'range'];
/* everything that returns something meaningful for valueAsNumber and
* can have the step attribute */
var numbers = dates.concat(plain_numbers, 'datetime-local');
/* the spec says to only check those for syntax in validity.typeMismatch.
* ¯\_(ツ)_/¯ */
var type_checked = ['email', 'url'];
/* check these for validity.badInput */
var input_checked = ['email', 'date', 'month', 'week', 'time', 'datetime', 'datetime-local', 'number', 'range', 'color'];
var text_types = ['text', 'search', 'tel', 'password'].concat(type_checked);
/* input element types, that are candidates for the validation API.
* Missing from this set are: button, hidden, menu (from <button>), reset and
* the types for non-<input> elements. */
var validation_candidates = ['checkbox', 'color', 'file', 'image', 'radio', 'submit'].concat(numbers, text_types);
/* all known types of <input> */
var inputs = ['button', 'hidden', 'reset'].concat(validation_candidates);
/* apparently <select> and <textarea> have types of their own */
var non_inputs = ['select-one', 'select-multiple', 'textarea'];
/* shim layer for the Element.matches method */
var ep = window.Element.prototype;
var native_matches = ep.matches || ep.matchesSelector || ep.msMatchesSelector || ep.webkitMatchesSelector;
function matches (element, selector) {
return native_matches.call(element, selector);
}
/**
* mark an object with a '__hyperform=true' property
*
* We use this to distinguish our properties from the native ones. Usage:
* js> mark(obj);
* js> assert(obj.__hyperform === true)
*/
function mark (obj) {
if (['object', 'function'].indexOf(typeof obj) > -1) {
delete obj.__hyperform;
Object.defineProperty(obj, '__hyperform', {
configurable: true,
enumerable: false,
value: true
});
}
return obj;
}
/**
* the internal storage for messages
*/
var store = new WeakMap();
/* jshint -W053 */
var message_store = {
set: function set(element, message) {
var is_custom = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
if (element instanceof window.HTMLFieldSetElement) {
var wrapped_form = get_wrapper(element);
if (wrapped_form && !wrapped_form.settings.extendFieldset) {
/* make this a no-op for <fieldset> in strict mode */
return message_store;
}
}
if (typeof message === 'string') {
message = new String(message);
}
if (is_custom) {
message.is_custom = true;
}
mark(message);
store.set(element, message);
/* allow the :invalid selector to match */
if ('_original_setCustomValidity' in element) {
element._original_setCustomValidity(message.toString());
}
return message_store;
},
get: function get(element) {
var message = store.get(element);
if (message === undefined && '_original_validationMessage' in element) {
/* get the browser's validation message, if we have none. Maybe it
* knows more than we. */
message = new String(element._original_validationMessage);
}
return message ? message : new String('');
},
delete: function _delete(element) {
if ('_original_setCustomValidity' in element) {
element._original_setCustomValidity('');
}
return store.delete(element);
}
};
/**
* counter that will be incremented with every call
*
* Will enforce uniqueness, as long as no more than 1 hyperform scripts
* are loaded. (In that case we still have the "random" part below.)
*/
var uid = 0;
/**
* generate a random ID
*
* @see https://gist.github.com/gordonbrander/2230317
*/
function generate_id () {
var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'hf_';
return prefix + uid++ + Math.random().toString(36).substr(2);
}
var warningsCache = new WeakMap();
var DefaultRenderer = {
/**
* called when a warning should become visible
*/
attachWarning: function attachWarning(warning, element) {
/* should also work, if element is last,
* http://stackoverflow.com/a/4793630/113195 */
element.parentNode.insertBefore(warning, element.nextSibling);
},
/**
* called when a warning should vanish
*/
detachWarning: function detachWarning(warning, element) {
warning.parentNode.removeChild(warning);
},
/**
* called when feedback to an element's state should be handled
*
* i.e., showing and hiding warnings
*/
showWarning: function showWarning(element) {
var sub_radio = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var msg = message_store.get(element).toString();
var warning = warningsCache.get(element);
if (msg) {
if (!warning) {
var wrapper = get_wrapper(element);
warning = document.createElement('div');
warning.className = wrapper && wrapper.settings.classes.warning || 'hf-warning';
warning.id = generate_id();
warning.setAttribute('aria-live', 'polite');
warningsCache.set(element, warning);
}
element.setAttribute('aria-errormessage', warning.id);
warning.textContent = msg;
Renderer.attachWarning(warning, element);
} else if (warning && warning.parentNode) {
element.removeAttribute('aria-errormessage');
Renderer.detachWarning(warning, element);
}
if (!sub_radio && element.type === 'radio' && element.form) {
/* render warnings for all other same-name radios, too */
Array.prototype.filter.call(document.getElementsByName(element.name), function (radio) {
return radio.name === element.name && radio.form === element.form;
}).map(function (radio) {
return Renderer.showWarning(radio, 'sub_radio');
});
}
}
};
var Renderer = {
attachWarning: DefaultRenderer.attachWarning,
detachWarning: DefaultRenderer.detachWarning,
showWarning: DefaultRenderer.showWarning,
set: function set(renderer, action) {
if (renderer.indexOf('_') > -1) {
/* global console */
// TODO delete before next non-patch version
console.log('Renderer.set: please use camelCase names. ' + renderer + ' will be removed in the next non-patch release.');
renderer = renderer.replace(/_([a-z])/g, function (g) {
return g[1].toUpperCase();
});
}
if (!action) {
action = DefaultRenderer[renderer];
}
Renderer[renderer] = action;
}
};
/**
* check element's validity and report an error back to the user
*/
function reportValidity(element) {
/* if this is a <form>, report validity of all child inputs */
if (element instanceof window.HTMLFormElement) {
return Array.prototype.map.call(element.elements, reportValidity).every(function (b) {
return b;
});
}
/* we copy checkValidity() here, b/c we have to check if the "invalid"
* event was canceled. */
var valid = ValidityState(element).valid;
var event;
if (valid) {
var wrapped_form = get_wrapper(element);
if (wrapped_form && wrapped_form.settings.validEvent) {
event = trigger_event(element, 'valid', { cancelable: true });
}
} else {
event = trigger_event(element, 'invalid', { cancelable: true });
}
if (!event || !event.defaultPrevented) {
Renderer.showWarning(element);
}
return valid;
}
/**
* submit a form, because `element` triggered it
*
* This method also dispatches a submit event on the form prior to the
* submission. The event contains the trigger element as `submittedVia`.
*
* If the element is a button with a name, the name=value pair will be added
* to the submitted data.
*/
function submit_form_via(element) {
/* apparently, the submit event is not triggered in most browsers on
* the submit() method, so we do it manually here to model a natural
* submit as closely as possible.
* Now to the fun fact: If you trigger a submit event from a form, what
* do you think should happen?
* 1) the form will be automagically submitted by the browser, or
* 2) nothing.
* And as you already suspected, the correct answer is: both! Firefox
* opts for 1), Chrome for 2). Yay! */
var event_got_cancelled;
var submit_event = create_event('submit', { cancelable: true });
/* force Firefox to not submit the form, then fake preventDefault() */
submit_event.preventDefault();
Object.defineProperty(submit_event, 'defaultPrevented', {
value: false,
writable: true
});
Object.defineProperty(submit_event, 'preventDefault', {
value: function value() {
return submit_event.defaultPrevented = event_got_cancelled = true;
},
writable: true
});
trigger_event(element.form, submit_event, {}, { submittedVia: element });
if (!event_got_cancelled) {
add_submit_field(element);
window.HTMLFormElement.prototype.submit.call(element.form);
window.setTimeout(function () {
return remove_submit_field(element);
});
}
}
/**
* if a submit button was clicked, add its name=value by means of a type=hidden
* input field
*/
function add_submit_field(button) {
if (['image', 'submit'].indexOf(button.type) > -1 && button.name) {
var wrapper = get_wrapper(button.form) || {};
var submit_helper = wrapper.submit_helper;
if (submit_helper) {
if (submit_helper.parentNode) {
submit_helper.parentNode.removeChild(submit_helper);
}
} else {
submit_helper = document.createElement('input');
submit_helper.type = 'hidden';
wrapper.submit_helper = submit_helper;
}
submit_helper.name = button.name;
submit_helper.value = button.value;
button.form.appendChild(submit_helper);
}
}
/**
* remove a possible helper input, that was added by `add_submit_field`
*/
function remove_submit_field(button) {
if (['image', 'submit'].indexOf(button.type) > -1 && button.name) {
var wrapper = get_wrapper(button.form) || {};
var submit_helper = wrapper.submit_helper;
if (submit_helper && submit_helper.parentNode) {
submit_helper.parentNode.removeChild(submit_helper);
}
}
}
/**
* check a form's validity and submit it
*
* The method triggers a cancellable `validate` event on the form. If the
* event is cancelled, form submission will be aborted, too.
*
* If the form is found to contain invalid fields, focus the first field.
*/
function check(button) {
/* trigger a "validate" event on the form to be submitted */
var val_event = trigger_event(button.form, 'validate', { cancelable: true });
if (val_event.defaultPrevented) {
/* skip the whole submit thing, if the validation is canceled. A user
* can still call form.submit() afterwards. */
return;
}
var valid = true;
var first_invalid;
Array.prototype.map.call(button.form.elements, function (element) {
if (!reportValidity(element)) {
valid = false;
if (!first_invalid && 'focus' in element) {
first_invalid = element;
}
}
});
if (valid) {
submit_form_via(button);
} else if (first_invalid) {
/* focus the first invalid element, if validation went south */
first_invalid.focus();
}
}
/**
* test if node is a submit button
*/
function is_submit_button(node) {
return (
/* must be an input or button element... */
(node.nodeName === 'INPUT' || node.nodeName === 'BUTTON') && (
/* ...and have a submitting type */
node.type === 'image' || node.type === 'submit')
);
}
/**
* test, if the click event would trigger a submit
*/
function is_submitting_click(event, button) {
return (
/* prevented default: won't trigger a submit */
!event.defaultPrevented && (
/* left button or middle button (submits in Chrome) */
!('button' in event) || event.button < 2) &&
/* must be a submit button... */
is_submit_button(button) &&
/* the button needs a form, that's going to be submitted */
button.form &&
/* again, if the form should not be validated, we're out of the game */
!button.form.hasAttribute('novalidate')
);
}
/**
* test, if the keypress event would trigger a submit
*/
function is_submitting_keypress(event) {
return (
/* prevented default: won't trigger a submit */
!event.defaultPrevented && (
/* ...and <Enter> was pressed... */
event.keyCode === 13 &&
/* ...on an <input> that is... */
event.target.nodeName === 'INPUT' &&
/* ...a standard text input field (not checkbox, ...) */
text_types.indexOf(event.target.type) > -1 ||
/* or <Enter> or <Space> was pressed... */
(event.keyCode === 13 || event.keyCode === 32) &&
/* ...on a submit button */
is_submit_button(event.target)) &&
/* there's a form... */
event.target.form &&
/* ...and the form allows validation */
!event.target.form.hasAttribute('novalidate')
);
}
/**
* catch clicks to children of <button>s
*/
function get_clicked_button(element) {
if (is_submit_button(element)) {
return element;
} else if (matches(element, 'button:not([type]) *, button[type="submit"] *')) {
return get_clicked_button(element.parentNode);
} else {
return null;
}
}
/**
* return event handler to catch explicit submission by click on a button
*/
function get_click_handler() {
var ignore = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
return function (event) {
var button = get_clicked_button(event.target);
if (button && is_submitting_click(event, button)) {
event.preventDefault();
if (ignore || button.hasAttribute('formnovalidate')) {
/* if validation should be ignored, we're not interested in any checks */
submit_form_via(button);
} else {
check(button);
}
}
};
}
var click_handler = get_click_handler();
var ignored_click_handler = get_click_handler(true);
/**
* catch implicit submission by pressing <Enter> in some situations
*/
function get_keypress_handler(ignore) {
return function keypress_handler(event) {
if (is_submitting_keypress(event)) {
event.preventDefault();
var wrapper = get_wrapper(event.target.form) || { settings: {} };
if (wrapper.settings.preventImplicitSubmit) {
/* user doesn't want an implicit submit. Cancel here. */
return;
}
/* check, that there is no submit button in the form. Otherwise
* that should be clicked. */
var el = event.target.form.elements.length;
var submit;
for (var i = 0; i < el; i++) {
if (['image', 'submit'].indexOf(event.target.form.elements[i].type) > -1) {
submit = event.target.form.elements[i];
break;
}
}
if (submit) {
submit.click();
} else if (ignore) {
submit_form_via(event.target);
} else {
check(event.target);
}
}
};
}
var keypress_handler = get_keypress_handler();
var ignored_keypress_handler = get_keypress_handler(true);
/**
* catch all relevant events _prior_ to a form being submitted
*
* @param bool ignore bypass validation, when an attempt to submit the
* form is detected. True, when the wrapper's revalidate
* setting is 'never'.
*/
function catch_submit(listening_node) {
var ignore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
if (ignore) {
listening_node.addEventListener('click', ignored_click_handler);
listening_node.addEventListener('keypress', ignored_keypress_handler);
} else {
listening_node.addEventListener('click', click_handler);
listening_node.addEventListener('keypress', keypress_handler);
}
}
/**
* decommission the event listeners from catch_submit() again
*/
function uncatch_submit(listening_node) {
listening_node.removeEventListener('click', ignored_click_handler);
listening_node.removeEventListener('keypress', ignored_keypress_handler);
listening_node.removeEventListener('click', click_handler);
listening_node.removeEventListener('keypress', keypress_handler);
}
/**
* remove `property` from element and restore _original_property, if present
*/
function uninstall_property (element, property) {
try {
delete element[property];
} catch (e) {
/* Safari <= 9 and PhantomJS will end up here :-( Nothing to do except
* warning */
var wrapper = get_wrapper(element);
if (wrapper && wrapper.settings.debug) {
/* global console */
console.log('[hyperform] cannot uninstall custom property ' + property);
}
return false;
}
var original_descriptor = Object.getOwnPropertyDescriptor(element, '_original_' + property);
if (original_descriptor) {
Object.defineProperty(element, property, original_descriptor);
}
}
/**
* add `property` to an element
*
* js> installer(element, 'foo', { value: 'bar' });
* js> assert(element.foo === 'bar');
*/
function install_property (element, property, descriptor) {
descriptor.configurable = true;
descriptor.enumerable = true;
if ('value' in descriptor) {
descriptor.writable = true;
}
var original_descriptor = Object.getOwnPropertyDescriptor(element, property);
if (original_descriptor) {
if (original_descriptor.configurable === false) {
/* Safari <= 9 and PhantomJS will end up here :-( Nothing to do except
* warning */
var wrapper = get_wrapper(element);
if (wrapper && wrapper.settings.debug) {
/* global console */
console.log('[hyperform] cannot install custom property ' + property);
}
return false;
}
/* we already installed that property... */
if (original_descriptor.get && original_descriptor.get.__hyperform || original_descriptor.value && original_descriptor.value.__hyperform) {
return;
}
/* publish existing property under new name, if it's not from us */
Object.defineProperty(element, '_original_' + property, original_descriptor);
}
delete element[property];
Object.defineProperty(element, property, descriptor);
return true;
}
function is_field (element) {
return element instanceof window.HTMLButtonElement || element instanceof window.HTMLInputElement || element instanceof window.HTMLSelectElement || element instanceof window.HTMLTextAreaElement || element instanceof window.HTMLFieldSetElement || element === window.HTMLButtonElement.prototype || element === window.HTMLInputElement.prototype || element === window.HTMLSelectElement.prototype || element === window.HTMLTextAreaElement.prototype || element === window.HTMLFieldSetElement.prototype;
}
/**
* set a custom validity message or delete it with an empty string
*/
function setCustomValidity(element, msg) {
message_store.set(element, msg, true);
}
function sprintf (str) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var args_length = args.length;
var global_index = 0;
return str.replace(/%([0-9]+\$)?([sl])/g, function (match, position, type) {
var local_index = global_index;
if (position) {
local_index = Number(position.replace(/\$$/, '')) - 1;
}
global_index += 1;
var arg = '';
if (args_length > local_index) {
arg = args[local_index];
}
if (arg instanceof Date || typeof arg === 'number' || arg instanceof Number) {
/* try getting a localized representation of dates and numbers, if the
* browser supports this */
if (type === 'l') {
arg = (arg.toLocaleString || arg.toString).call(arg);
} else {
arg = arg.toString();
}
}
return arg;
});
}
/* For a given date, get the ISO week number
*
* Source: http://stackoverflow.com/a/6117889/113195
*
* Based on information at:
*
* http://www.merlyn.demon.co.uk/weekcalc.htm#WNR
*
* Algorithm is to find nearest thursday, it's year
* is the year of the week number. Then get weeks
* between that date and the first day of that year.
*
* Note that dates in one year can be weeks of previous
* or next year, overlap is up to 3 days.
*
* e.g. 2014/12/29 is Monday in week 1 of 2015
* 2012/1/1 is Sunday in week 52 of 2011
*/
function get_week_of_year (d) {
/* Copy date so don't modify original */
d = new Date(+d);
d.setUTCHours(0, 0, 0);
/* Set to nearest Thursday: current date + 4 - current day number
* Make Sunday's day number 7 */
d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7));
/* Get first day of year */
var yearStart = new Date(d.getUTCFullYear(), 0, 1);
/* Calculate full weeks to nearest Thursday */
var weekNo = Math.ceil(((d - yearStart) / 86400000 + 1) / 7);
/* Return array of year and week number */
return [d.getUTCFullYear(), weekNo];
}
function pad(num) {
var size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
var s = num + '';
while (s.length < size) {
s = '0' + s;
}
return s;
}
/**
* calculate a string from a date according to HTML5
*/
function date_to_string(date, element_type) {
if (!(date instanceof Date)) {
return null;
}
switch (element_type) {
case 'datetime':
return date_to_string(date, 'date') + 'T' + date_to_string(date, 'time');
case 'datetime-local':
return sprintf('%s-%s-%sT%s:%s:%s.%s', date.getFullYear(), pad(date.getMonth() + 1), pad(date.getDate()), pad(date.getHours()), pad(date.getMinutes()), pad(date.getSeconds()), pad(date.getMilliseconds(), 3)).replace(/(:00)?\.000$/, '');
case 'date':
return sprintf('%s-%s-%s', date.getUTCFullYear(), pad(date.getUTCMonth() + 1), pad(date.getUTCDate()));
case 'month':
return sprintf('%s-%s', date.getUTCFullYear(), pad(date.getUTCMonth() + 1));
case 'week':
var params = get_week_of_year(date);
return sprintf.call(null, '%s-W%s', params[0], pad(params[1]));
case 'time':
return sprintf('%s:%s:%s.%s', pad(date.getUTCHours()), pad(date.getUTCMinutes()), pad(date.getUTCSeconds()), pad(date.getUTCMilliseconds(), 3)).replace(/(:00)?\.000$/, '');
}
return null;
}
/**
* return a new Date() representing the ISO date for a week number
*
* @see http://stackoverflow.com/a/16591175/113195
*/
function get_date_from_week (week, year) {
var date = new Date(Date.UTC(year, 0, 1 + (week - 1) * 7));
if (date.getUTCDay() <= 4 /* thursday */) {
date.setUTCDate(date.getUTCDate() - date.getUTCDay() + 1);
} else {
date.setUTCDate(date.getUTCDate() + 8 - date.getUTCDay());
}
return date;
}
/**
* calculate a date from a string according to HTML5
*/
function string_to_date (string, element_type) {
var date = new Date(0);
var ms;
switch (element_type) {
case 'datetime':
if (!/^([0-9]{4,})-([0-9]{2})-([0-9]{2})T([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(string)) {
return null;
}
ms = RegExp.$7 || '000';
while (ms.length < 3) {
ms += '0';
}
date.setUTCFullYear(Number(RegExp.$1));
date.setUTCMonth(Number(RegExp.$2) - 1, Number(RegExp.$3));
date.setUTCHours(Number(RegExp.$4), Number(RegExp.$5), Number(RegExp.$6 || 0), Number(ms));
return date;
case 'date':
if (!/^([0-9]{4,})-([0-9]{2})-([0-9]{2})$/.test(string)) {
return null;
}
date.setUTCFullYear(Number(RegExp.$1));
date.setUTCMonth(Number(RegExp.$2) - 1, Number(RegExp.$3));
return date;
case 'month':
if (!/^([0-9]{4,})-([0-9]{2})$/.test(string)) {
return null;
}
date.setUTCFullYear(Number(RegExp.$1));
date.setUTCMonth(Number(RegExp.$2) - 1, 1);
return date;
case 'week':
if (!/^([0-9]{4,})-W(0[1-9]|[1234][0-9]|5[0-3])$/.test(string)) {
return null;
}
return get_date_from_week(Number(RegExp.$2), Number(RegExp.$1));
case 'time':
if (!/^([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(string)) {
return null;
}
ms = RegExp.$4 || '000';
while (ms.length < 3) {
ms += '0';
}
date.setUTCHours(Number(RegExp.$1), Number(RegExp.$2), Number(RegExp.$3 || 0), Number(ms));
return date;
}
return null;
}
/**
* calculate a date from a string according to HTML5
*/
function string_to_number (string, element_type) {
var rval = string_to_date(string, element_type);
if (rval !== null) {
return +rval;
}
/* not parseFloat, because we want NaN for invalid values like "1.2xxy" */
return Number(string);
}
/**
* get the element's type in a backwards-compatible way
*/
function get_type (element) {
if (element instanceof window.HTMLTextAreaElement) {
return 'textarea';
} else if (element instanceof window.HTMLSelectElement) {
return element.hasAttribute('multiple') ? 'select-multiple' : 'select-one';
} else if (element instanceof window.HTMLButtonElement) {
return (element.getAttribute('type') || 'submit').toLowerCase();
} else if (element instanceof window.HTMLInputElement) {
var attr = (element.getAttribute('type') || '').toLowerCase();
if (attr && inputs.indexOf(attr) > -1) {
return attr;
} else {
/* perhaps the DOM has in-depth knowledge. Take that before returning
* 'text'. */
return element.type || 'text';
}
}
return '';
}
/**
* the following validation messages are from Firefox source,
* http://mxr.mozilla.org/mozilla-central/source/dom/locales/en-US/chrome/dom/dom.properties
* released under MPL license, http://mozilla.org/MPL/2.0/.
*/
var catalog = {
en: {
TextTooLong: 'Please shorten this text to %l characters or less (you are currently using %l characters).',
ValueMissing: 'Please fill out this field.',
CheckboxMissing: 'Please check this box if you want to proceed.',
RadioMissing: 'Please select one of these options.',
FileMissing: 'Please select a file.',
SelectMissing: 'Please select an item in the list.',
InvalidEmail: 'Please enter an email address.',
InvalidURL: 'Please enter a URL.',
PatternMismatch: 'Please match the requested format.',
PatternMismatchWithTitle: 'Please match the requested format: %l.',
NumberRangeOverflow: 'Please select a value that is no more than %l.',
DateRangeOverflow: 'Please select a value that is no later than %l.',
TimeRangeOverflow: 'Please select a value that is no later than %l.',
NumberRangeUnderflow: 'Please select a value that is no less than %l.',
DateRangeUnderflow: 'Please select a value that is no earlier than %l.',
TimeRangeUnderflow: 'Please select a value that is no earlier than %l.',
StepMismatch: 'Please select a valid value. The two nearest valid values are %l and %l.',
StepMismatchOneValue: 'Please select a valid value. The nearest valid value is %l.',
BadInputNumber: 'Please enter a number.'
}
};
/**
* the global language Hyperform will use
*/
var language = 'en';
/**
* set the language for Hyperform’s messages
*/
function set_language(newlang) {
language = newlang;
}
/**
* add a lookup catalog "string: translation" for a language
*/
function add_translation(lang, new_catalog) {
if (!(lang in catalog)) {
catalog[lang] = {};
}
for (var key in new_catalog) {
if (new_catalog.hasOwnProperty(key)) {
catalog[lang][key] = new_catalog[key];
}
}
}
/**
* return `s` translated into the current language
*
* Defaults to English if the former has no translation for `s`.
*/
function _ (s) {
if (language in catalog && s in catalog[language]) {
return catalog[language][s];
} else if (s in catalog.en) {
return catalog.en[s];
}
return s;
}
var default_step = {
'datetime-local': 60,
datetime: 60,
time: 60
};
var step_scale_factor = {
'datetime-local': 1000,
datetime: 1000,
date: 86400000,
week: 604800000,
time: 1000
};
var default_step_base = {
week: -259200000
};
var default_min = {
range: 0
};
var default_max = {
range: 100
};
/**
* get previous and next valid values for a stepped input element
*/
function get_next_valid (element) {
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
var type = get_type(element);
var aMin = element.getAttribute('min');
var min = default_min[type] || NaN;
if (aMin) {
var pMin = string_to_number(aMin, type);
if (!isNaN(pMin)) {
min = pMin;
}
}
var aMax = element.getAttribute('max');
var max = default_max[type] || NaN;
if (aMax) {
var pMax = string_to_number(aMax, type);
if (!isNaN(pMax)) {
max = pMax;
}
}
var aStep = element.getAttribute('step');
var step = default_step[type] || 1;
if (aStep && aStep.toLowerCase() === 'any') {
/* quick return: we cannot calculate prev and next */
return [_('any value'), _('any value')];
} else if (aStep) {
var pStep = string_to_number(aStep, type);
if (!isNaN(pStep)) {
step = pStep;
}
}
var default_value = string_to_number(element.getAttribute('value'), type);
var value = string_to_number(element.value || element.getAttribute('value'), type);
if (isNaN(value)) {
/* quick return: we cannot calculate without a solid base */
return [_('any valid value'), _('any valid value')];
}
var step_base = !isNaN(min) ? min : !isNaN(default_value) ? default_value : default_step_base[type] || 0;
var scale = step_scale_factor[type] || 1;
var prev = step_base + Math.floor((value - step_base) / (step * scale)) * (step * scale) * n;
var next = step_base + (Math.floor((value - step_base) / (step * scale)) + 1) * (step * scale) * n;
if (prev < min) {
prev = null;
} else if (prev > max) {
prev = max;
}
if (next > max) {
next = null;
} else if (next < min) {
next = min;
}
/* convert to date objects, if appropriate */
if (dates.indexOf(type) > -1) {
prev = date_to_string(new Date(prev), type);
next = date_to_string(new Date(next), type);
}
return [prev, next];
}
/**
* implement the valueAsDate functionality
*
* @see https://html.spec.whatwg.org/multipage/forms.html#dom-input-valueasdate
*/
function valueAsDate(element) {
var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
var type = get_type(element);
if (dates.indexOf(type) > -1) {
if (value !== undefined) {
/* setter: value must be null or a Date() */
if (value === null) {
element.value = '';
} else if (value instanceof Date) {
if (isNaN(value.getTime())) {
element.value = '';
} else {
element.value = date_to_string(value, type);
}
} else {
throw new window.DOMException('valueAsDate setter encountered invalid value', 'TypeError');
}
return;
}
var value_date = string_to_date(element.value, type);
return value_date instanceof Date ? value_date : null;
} else if (value !== undefined) {
/* trying to set a date on a not-date input fails */
throw new window.DOMException('valueAsDate setter cannot set date on this element', 'InvalidStateError');
}
return null;
}
/**
* implement the valueAsNumber functionality
*
* @see https://html.spec.whatwg.org/multipage/forms.html#dom-input-valueasnumber
*/
function valueAsNumber(element) {
var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
var type = get_type(element);
if (numbers.indexOf(type) > -1) {
if (type === 'range' && element.hasAttribute('multiple')) {
/* @see https://html.spec.whatwg.org/multipage/forms.html#do-not-apply */
return NaN;
}
if (value !== undefined) {
/* setter: value must be NaN or a finite number */
if (isNaN(value)) {
element.value = '';
} else if (typeof value === 'number' && window.isFinite(value)) {
try {
/* try setting as a date, but... */
valueAsDate(element, new Date(value));
} catch (e) {
/* ... when valueAsDate is not responsible, ... */
if (!(e instanceof window.DOMException)) {
throw e;
}
/* ... set it via Number.toString(). */
element.value = value.toString();
}
} else {
throw new window.DOMException('valueAsNumber setter encountered invalid value', 'TypeError');
}
return;
}
return string_to_number(element.value, type);
} else if (value !== undefined) {
/* trying to set a number on a not-number input fails */
throw new window.DOMException('valueAsNumber setter cannot set number on this element', 'InvalidStateError');
}
return NaN;
}
/**
*
*/
function stepDown(element) {
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
if (numbers.indexOf(get_type(element)) === -1) {
throw new window.DOMException('stepDown encountered invalid type', 'InvalidStateError');
}
if ((element.getAttribute('step') || '').toLowerCase() === 'any') {
throw new window.DOMException('stepDown encountered step "any"', 'InvalidStateError');
}
var prev = get_next_valid(element, n)[0];
if (prev !== null) {
valueAsNumber(element, prev);
}
}
/**
*
*/
function stepUp(element) {
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
if (numbers.indexOf(get_type(element)) === -1) {
throw new window.DOMException('stepUp encountered invalid type', 'InvalidStateError');
}
if ((element.getAttribute('step') || '').toLowerCase() === 'any') {
throw new window.DOMException('stepUp encountered step "any"', 'InvalidStateError');
}
var next = get_next_valid(element, n)[1];
if (next !== null) {
valueAsNumber(element, next);
}
}
/**
* get the validation message for an element, empty string, if the element
* satisfies all constraints.
*/
function validationMessage(element) {
var msg = message_store.get(element);
if (!msg) {
return '';
}
/* make it a primitive again, since message_store returns String(). */
return msg.toString();
}
/**
* check, if an element will be subject to HTML5 validation at all
*/
function willValidate(element) {
return is_validation_candidate(element);
}
var gA = function gA(prop) {
return function () {
return do_filter('attr_get_' + prop, this.getAttribute(prop), this);
};
};
var sA = function sA(prop) {
return function (value) {
this.setAttribute(prop, do_filter('attr_set_' + prop, value, this));
};
};
var gAb = function gAb(prop) {
return function () {
return do_filter('attr_get_' + prop, this.hasAttribute(prop), this);
};
};
var sAb = function sAb(prop) {
return function (value) {
if (do_filter('attr_set_' + prop, value, this)) {
this.setAttribute(prop, prop);
} else {
this.removeAttribute(prop);
}
};
};
var gAn = function gAn(prop) {
return function () {
return do_filter('attr_get_' + prop, Math.max(0, Number(this.getAttribute(prop))), this);
};
};
var sAn = function sAn(prop) {
return function (value) {
value = do_filter('attr_set_' + prop, value, this);
if (/^[0-9]+$/.test(value)) {
this.setAttribute(prop, value);
}
};
};
function install_properties(element) {
var _arr = ['accept', 'max', 'min', 'pattern', 'placeholder', 'step'];
for (var _i = 0; _i < _arr.length; _i++) {
var prop = _arr[_i];
install_property(element, prop, {
get: gA(prop),
set: sA(prop)
});
}
var _arr2 = ['multiple', 'required', 'readOnly'];
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var _prop = _arr2[_i2];
install_property(element, _prop, {
get: gAb(_prop.toLowerCase()),
set: sAb(_prop.toLowerCase())
});
}
var _arr3 = ['minLength', 'maxLength'];
for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
var _prop2 = _arr3[_i3];
install_property(element, _prop2, {
get: gAn(_prop2.toLowerCase()),
set: sAn(_prop2.toLowerCase())
});
}
}
function uninstall_properties(element) {
var _arr4 = ['accept', 'max', 'min', 'pattern', 'placeholder', 'step', 'multiple', 'required', 'readOnly', 'minLength', 'maxLength'];
for (var _i4 = 0; _i4 < _arr4.length; _i4++) {
var prop = _arr4[_i4];
uninstall_property(element, prop);
}
}
var polyfills = {
checkValidity: {
value: mark(function () {
return checkValidity(this);
})
},
reportValidity: {
value: mark(function () {
return reportValidity(this);
})
},
setCustomValidity: {
value: mark(function (msg) {
return setCustomValidity(this, msg);
})
},
stepDown: {
value: mark(function () {
var n = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
return stepDown(this, n);
})
},
stepUp: {
value: mark(function () {
var n = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
return stepUp(this, n);
})
},
validationMessage: {
get: mark(function () {
return validationMessage(this);
})
},
validity: {
get: mark(function () {
return ValidityState(this);
})
},
valueAsDate: {
get: mark(function () {
return valueAsDate(this);
}),
set: mark(function (value) {
valueAsDate(this, value);
})
},
valueAsNumber: {
get: mark(function () {
return valueAsNumber(this);
}),
set: mark(function (value) {
valueAsNumber(this, value);
})
},
willValidate: {
get: mark(function () {
return willValidate(this);
})
}
};
function polyfill (element) {
if (is_field(element)) {
for (var prop in polyfills) {
install_property(element, prop, polyfills[prop]);
}
install_properties(element);
} else if (element instanceof window.HTMLFormElement || element === window.HTMLFormElement.prototype) {
install_property(element, 'checkValidity', polyfills.checkValidity);
install_property(element, 'reportValidity', polyfills.reportValidity);
}
}
function polyunfill (element) {
if (is_field(element)) {
uninstall_property(element, 'checkValidity');
uninstall_property(element, 'reportValidity');
uninstall_property(element, 'setCustomValidity');
uninstall_property(element, 'stepDown');
uninstall_property(element, 'stepUp');
uninstall_property(element, 'validationMessage');
uninstall_property(element, 'validity');
uninstall_property(element, 'valueAsDate');
uninstall_property(element, 'valueAsNumber');
uninstall_property(element, 'willValidate');
uninstall_properties(element);
} else if (element instanceof window.HTMLFormElement) {
uninstall_property(element, 'checkValidity');
uninstall_property(element, 'reportValidity');
}
}
var instances = new WeakMap();
/**
* wrap <form>s, window or document, that get treated with the global
* hyperform()
*/
function Wrapper(form, settings) {
/* do not allow more than one instance per form. Otherwise we'd end
* up with double event handlers, polyfills re-applied, ... */
var existing = instances.get(form);
if (existing) {
existing.settings = settings;
return existing;
}
this.form = form;
this.settings = settings;
this.revalidator = this.revalidate.bind(this);
instances.set(form, this);
catch_submit(form, settings.revalidate === 'never');
if (form === window || form.nodeType === 9) {
/* install on the prototypes, when called for the whole document */
this.install([window.HTMLButtonElement.prototype, window.HTMLInputElement.prototype, window.HTMLSelectElement.prototype, window.HTMLTextAreaElement.prototype, window.HTMLFieldSetElement.prototype]);
polyfill(window.HTMLFormElement);
} else if (form instanceof window.HTMLFormElement || form instanceof window.HTMLFieldSetElement) {
this.install(form.elements);
if (form instanceof window.HTMLFormElement) {
polyfill(form);
}
}
if (settings.revalidate === 'oninput' || settings.revalidate === 'hybrid') {
/* in a perfect world we'd just bind to "input", but support here is
* abysmal: http://caniuse.com/#feat=input-event */
form.addEventListener('keyup', this.revalidator);
form.addEventListener('change', this.revalidator);
}
if (settings.revalidate === 'onblur' || settings.revalidate === 'hybrid') {
/* useCapture=true, because `blur` doesn't bubble. See
* https://developer.mozilla.org/en-US/docs/Web/Events/blur#Event_delegation
* for a discussion */
form.addEventListener('blur', this.revalidator, true);
}
}
Wrapper.prototype = {
destroy: function destroy() {
uncatch_submit(this.form);
instances.delete(this.form);
this.form.removeEventListener('keyup', this.revalidator);
this.form.removeEventListener('change', this.revalidator);
this.form.removeEventListener('blur', this.revalidator, true);
if (this.form === window || this.form.nodeType === 9) {
this.uninstall([window.HTMLButtonElement.prototype, window.HTMLInputElement.prototype, window.HTMLSelectElement.prototype, window.HTMLTextAreaElement.prototype, window.HTMLFieldSetElement.prototype]);
polyunfill(window.HTMLFormElement);
} else if (this.form instanceof window.HTMLFormElement || this.form instanceof window.HTMLFieldSetElement) {
this.uninstall(this.form.elements);
if (this.form instanceof window.HTMLFormElement) {
polyunfill(this.form);
}
}
},
/**
* revalidate an input element
*/
revalidate: function revalidate(event) {
if (event.target instanceof window.HTMLButtonElement || event.target instanceof window.HTMLTextAreaElement || event.target instanceof window.HTMLSelectElement || event.target instanceof window.HTMLInputElement) {
if (this.settings.revalidate === 'hybrid') {
/* "hybrid" somewhat simulates what browsers do. See for example
* Firefox's :-moz-ui-invalid pseudo-class:
* https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-ui-invalid */
if (event.type === 'blur' && event.target.value !== event.target.defaultValue || ValidityState(event.target).valid) {
/* on blur, update the report when the value has changed from the
* default or when the element is valid (possibly removing a still
* standing invalidity report). */
reportValidity(event.target);
} else if (event.type === 'keyup' || event.type === 'change') {
if (ValidityState(event.target).valid) {
// report instantly, when an element becomes valid,
// postpone report to blur event, when an element is invalid
reportValidity(event.target);
}
}
} else {
reportValidity(event.target);
}
}
},
/**
* install the polyfills on each given element
*
* If you add elements dynamically, you have to call install() on them
* yourself:
*
* js> var form = hyperform(document.forms[0]);
* js> document.forms[0].appendChild(input);
* js> form.install(input);
*
* You can skip this, if you called hyperform on window or document.
*/
install: function install(els) {
if (els instanceof window.Element) {
els = [els];
}
var els_length = els.length;
for (var i = 0; i < els_length; i++) {
polyfill(els[i]);
}
},
uninstall: function uninstall(els) {
if (els instanceof window.Element) {
els = [els];
}
var els_length = els.length;
for (var i = 0; i < els_length; i++) {
polyunfill(els[i]);
}
}
};
/**
* try to get the appropriate wrapper for a specific element by looking up
* its parent chain
*
* @return Wrapper | undefined
*/
function get_wrapper(element) {
var wrapped;
if (element.form) {
/* try a shortcut with the element's <form> */
wrapped = instances.get(element.form);
}
/* walk up the parent nodes until document (including) */
while (!wrapped && element) {
wrapped = instances.get(element);
element = element.parentNode;
}
if (!wrapped) {
/* try the global instance, if exists. This may also be undefined. */
wrapped = instances.get(window);
}
return wrapped;
}
/**
* check if an element is a candidate for constraint validation
*
* @see https://html.spec.whatwg.org/multipage/forms.html#barred-from-constraint-validation
*/
function is_validation_candidate (element) {
/* allow a shortcut via filters, e.g. to validate type=hidden fields */
var filtered = do_filter('is_validation_candidate', null, element);
if (filtered !== null) {
return !!filtered;
}
/* it must be any of those elements */
if (element instanceof window.HTMLSelectElement || element instanceof window.HTMLTextAreaElement || element instanceof window.HTMLButtonElement || element instanceof window.HTMLInputElement) {
var type = get_type(element);
/* its type must be in the whitelist or missing (select, textarea) */
if (!type || non_inputs.indexOf(type) > -1 || validation_candidates.indexOf(type) > -1) {
/* it mustn't be disabled or readonly */
if (!element.hasAttribute('disabled') && !element.hasAttribute('readonly')) {
var wrapped_form = get_wrapper(element);
/* it hasn't got the (non-standard) attribute 'novalidate' or its
* parent form has got the strict parameter */
if (wrapped_form && wrapped_form.settings.novalidateOnElements || !element.hasAttribute('novalidate') || !element.noValidate) {
/* it isn't part of a <fieldset disabled> */
var p = element.parentNode;
while (p && p.nodeType === 1) {
if (p instanceof window.HTMLFieldSetElement && p.hasAttribute('disabled')) {
/* quick return, if it's a child of a disabled fieldset */
return false;
} else if (p.nodeName.toUpperCase() === 'DATALIST') {
/* quick return, if it's a child of a datalist
* Do not use HTMLDataListElement to support older browsers,
* too.
* @see https://html.spec.whatwg.org/multipage/forms.html#the-datalist-element:barred-from-constraint-validation
*/
return false;
} else if (p === element.form) {
/* the outer boundary. We can stop looking for relevant
* fieldsets. */
break;
}
p = p.parentNode;
}
/* then it's a candidate */
return true;
}
}
}
}
/* this is no HTML5 validation candidate... */
return false;
}
function format_date (date) {
var part = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined;
switch (part) {
case 'date':
return (date.toLocaleDateString || date.toDateString).call(date);
case 'time':
return (date.toLocaleTimeString || date.toTimeString).call(date);
case 'month':
return 'toLocaleDateString' in date ? date.toLocaleDateString(undefined, {
year: 'numeric',
month: '2-digit'
}) : date.toDateString();
// case 'week':
// TODO
default:
return (date.toLocaleString || date.toString).call(date);
}
}
/**
* patch String.length to account for non-BMP characters
*
* @see https://mathiasbynens.be/notes/javascript-unicode
* We do not use the simple [...str].length, because it needs a ton of
* polyfills in older browsers.
*/
function unicode_string_length (str) {
return str.match(/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/g).length;
}
/**
* internal storage for custom error messages
*/
var store$1 = new WeakMap();
/**
* register custom error messages per element
*/
var custom_messages = {
set: function set(element, validator, message) {
var messages = store$1.get(element) || {};
messages[validator] = message;
store$1.set(element, messages);
return custom_messages;
},
get: function get(element, validator) {
var _default = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
var messages = store$1.get(element);
if (messages === undefined || !(validator in messages)) {
var data_id = 'data-' + validator.replace(/[A-Z]/g, '-$&').toLowerCase();
if (element.hasAttribute(data_id)) {
/* if the element has a data-validator attribute, use this as fallback.
* E.g., if validator == 'valueMissing', the element can specify a
* custom validation message like this:
* <input data-value-missing="Oh noes!">
*/
return element.getAttribute(data_id);
}
return _default;
}
return messages[validator];
},
delete: function _delete(element) {
var validator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
if (!validator) {
return store$1.delete(element);
}
var messages = store$1.get(element) || {};
if (validator in messages) {
delete messages[validator];
store$1.set(element, messages);
return true;
}
return false;
}
};
var internal_registry = new WeakMap();
/**
* A registry for custom validators
*
* slim wrapper around a WeakMap to ensure the values are arrays
* (hence allowing > 1 validators per element)
*/
var custom_validator_registry = {
set: function set(element, validator) {
var current = internal_registry.get(element) || [];
current.push(validator);
internal_registry.set(element, current);
return custom_validator_registry;
},
get: function get(element) {
return internal_registry.get(element) || [];
},
delete: function _delete(element) {
return internal_registry.delete(element);
}
};
/**
* test whether the element suffers from bad input
*/
function test_bad_input (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || input_checked.indexOf(type) === -1) {
/* we're not interested, thanks! */
return true;
}
/* the browser hides some bad input from the DOM, e.g. malformed numbers,
* email addresses with invalid punycode representation, ... We try to resort
* to the original method here. The assumption is, that a browser hiding
* bad input will hopefully also always support a proper
* ValidityState.badInput */
if (!element.value) {
if ('_original_validity' in element && !element._original_validity.__hyperform) {
return !element._original_validity.badInput;
}
/* no value and no original badInput: Assume all's right. */
return true;
}
var result = true;
switch (type) {
case 'color':
result = /^#[a-f0-9]{6}$/.test(element.value);
break;
case 'number':
case 'range':
result = !isNaN(Number(element.value));
break;
case 'datetime':
case 'date':
case 'month':
case 'week':
case 'time':
result = string_to_date(element.value, type) !== null;
break;
case 'datetime-local':
result = /^([0-9]{4,})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(element.value);
break;
case 'tel':
/* spec says No! Phone numbers can have all kinds of formats, so this
* is expected to be a free-text field. */
// TODO we could allow a setting 'phone_regex' to be evaluated here.
break;
case 'email':
break;
}
return result;
}
/**
* test the max attribute
*
* we use Number() instead of parseFloat(), because an invalid attribute
* value like "123abc" should result in an error.
*/
function test_max (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || !element.value || !element.hasAttribute('max')) {
/* we're not responsible here */
return true;
}
var value = void 0,
max = void 0;
if (dates.indexOf(type) > -1) {
value = 1 * string_to_date(element.value, type);
max = 1 * (string_to_date(element.getAttribute('max'), type) || NaN);
} else {
value = Number(element.value);
max = Number(element.getAttribute('max'));
}
return isNaN(max) || value <= max;
}
/**
* test the maxlength attribute
*/
function test_maxlength (element) {
if (!is_validation_candidate(element) || !element.value || text_types.indexOf(get_type(element)) === -1 || !element.hasAttribute('maxlength') || !element.getAttribute('maxlength') // catch maxlength=""
) {
return true;
}
var maxlength = parseInt(element.getAttribute('maxlength'), 10);
/* check, if the maxlength value is usable at all.
* We allow maxlength === 0 to basically disable input (Firefox does, too).
*/
if (isNaN(maxlength) || maxlength < 0) {
return true;
}
return unicode_string_length(element.value) <= maxlength;
}
/**
* test the min attribute
*
* we use Number() instead of parseFloat(), because an invalid attribute
* value like "123abc" should result in an error.
*/
function test_min (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || !element.value || !element.hasAttribute('min')) {
/* we're not responsible here */
return true;
}
var value = void 0,
min = void 0;
if (dates.indexOf(type) > -1) {
value = 1 * string_to_date(element.value, type);
min = 1 * (string_to_date(element.getAttribute('min'), type) || NaN);
} else {
value = Number(element.value);
min = Number(element.getAttribute('min'));
}
return isNaN(min) || value >= min;
}
/**
* test the minlength attribute
*/
function test_minlength (element) {
if (!is_validation_candidate(element) || !element.value || text_types.indexOf(get_type(element)) === -1 || !element.hasAttribute('minlength') || !element.getAttribute('minlength') // catch minlength=""
) {
return true;
}
var minlength = parseInt(element.getAttribute('minlength'), 10);
/* check, if the minlength value is usable at all. */
if (isNaN(minlength) || minlength < 0) {
return true;
}
return unicode_string_length(element.value) >= minlength;
}
/**
* test the pattern attribute
*/
function test_pattern (element) {
return !is_validation_candidate(element) || !element.value || !element.hasAttribute('pattern') || new RegExp('^(?:' + element.getAttribute('pattern') + ')$').test(element.value);
}
/**
* test the required attribute
*/
function test_required (element) {
if (!is_validation_candidate(element) || !element.hasAttribute('required')) {
/* nothing to do */
return true;
}
/* we don't need get_type() for element.type, because "checkbox" and "radio"
* are well supported. */
switch (element.type) {
case 'checkbox':
return element.checked;
//break;
case 'radio':
/* radio inputs have "required" fulfilled, if _any_ other radio
* with the same name in this form is checked. */
return !!(element.checked || element.form && Array.prototype.filter.call(document.getElementsByName(element.name), function (radio) {
return radio.name === element.name && radio.form === element.form && radio.checked;
}).length > 0);
//break;
default:
return !!element.value;
}
}
/**
* test the step attribute
*/
function test_step (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || !element.value || numbers.indexOf(type) === -1 || (element.getAttribute('step') || '').toLowerCase() === 'any') {
/* we're not responsible here. Note: If no step attribute is given, we
* need to validate against the default step as per spec. */
return true;
}
var step = element.getAttribute('step');
if (step) {
step = string_to_number(step, type);
} else {
step = default_step[type] || 1;
}
if (step <= 0 || isNaN(step)) {
/* error in specified "step". We cannot validate against it, so the value
* is true. */
return true;
}
var scale = step_scale_factor[type] || 1;
var value = string_to_number(element.value, type);
var min = string_to_number(element.getAttribute('min') || element.getAttribute('value') || '', type);
if (isNaN(min)) {
min = default_step_base[type] || 0;
}
if (type === 'month') {
/* type=month has month-wide steps. See
* https://html.spec.whatwg.org/multipage/forms.html#month-state-%28type=month%29
*/
min = new Date(min).getUTCFullYear() * 12 + new Date(min).getUTCMonth();
value = new Date(value).getUTCFullYear() * 12 + new Date(value).getUTCMonth();
}
var result = Math.abs(min - value) % (step * scale);
return result < 0.00000001 ||
/* crappy floating-point arithmetics! */
result > step * scale - 0.00000001;
}
var ws_on_start_or_end = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
/**
* trim a string of whitespace
*
* We don't use String.trim() to remove the need to polyfill it.
*/
function trim (str) {
return str.replace(ws_on_start_or_end, '');
}
/**
* split a string on comma and trim the components
*
* As specified at
* https://html.spec.whatwg.org/multipage/infrastructure.html#split-a-string-on-commas
* plus removing empty entries.
*/
function comma_split (str) {
return str.split(',').map(function (item) {
return trim(item);
}).filter(function (b) {
return b;
});
}
/* we use a dummy <a> where we set the href to test URL validity
* The definition is out of the "global" scope so that JSDOM can be instantiated
* after loading Hyperform for tests.
*/
var url_canary;
/* see https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address */
var email_pattern = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
/**
* test the type-inherent syntax
*/
function test_type (element) {
var type = get_type(element);
if (!is_validation_candidate(element) || type !== 'file' && !element.value || type !== 'file' && type_checked.indexOf(type) === -1) {
/* we're not responsible for this element */
return true;
}
var is_valid = true;
switch (type) {
case 'url':
if (!url_canary) {
url_canary = document.createElement('a');
}
var value = trim(element.value);
url_canary.href = value;
is_valid = url_canary.href === value || url_canary.href === value + '/';
break;
case 'email':
if (element.hasAttribute('multiple')) {
is_valid = comma_split(element.value).every(function (value) {
return email_pattern.test(value);
});
} else {
is_valid = email_pattern.test(trim(element.value));
}
break;
case 'file':
if ('files' in element && element.files.length && element.hasAttribute('accept')) {
var patterns = comma_split(element.getAttribute('accept')).map(function (pattern) {
if (/^(audio|video|image)\/\*$/.test(pattern)) {
pattern = new RegExp('^' + RegExp.$1 + '/.+$');
}
return pattern;
});
if (!patterns.length) {
break;
}
fileloop: for (var i = 0; i < element.files.length; i++) {
/* we need to match a whitelist, so pre-set with false */
var file_valid = false;
patternloop: for (var j = 0; j < patterns.length; j++) {
var file = element.files[i];
var pattern = patterns[j];
var fileprop = file.type;
if (typeof pattern === 'string' && pattern.substr(0, 1) === '.') {
if (file.name.search('.') === -1) {
/* no match with any file ending */
continue patternloop;
}
fileprop = file.name.substr(file.name.lastIndexOf('.'));
}
if (fileprop.search(pattern) === 0) {
/* we found one match and can quit looking */
file_valid = true;
break patternloop;
}
}
if (!file_valid) {
is_valid = false;
break fileloop;
}
}
}
}
return is_valid;
}
/**
* boilerplate function for all tests but customError
*/
function check$1(test, react) {
return function (element) {
var invalid = !test(element);
if (invalid) {
react(element);
}
return invalid;
};
}
/**
* create a common function to set error messages
*/
function set_msg(element, msgtype, _default) {
message_store.set(element, custom_messages.get(element, msgtype, _default));
}
var badInput = check$1(test_bad_input, function (element) {
return set_msg(element, 'badInput', _('Please match the requested type.'));
});
function customError(element) {
/* check, if there are custom validators in the registry, and call
* them. */
var custom_validators = custom_validator_registry.get(element);
var cvl = custom_validators.length;
var valid = true;
if (cvl) {
for (var i = 0; i < cvl; i++) {
var result = custom_validators[i](element);
if (result !== undefined && !result) {
valid = false;
/* break on first invalid response */
break;
}
}
}
/* check, if there are other validity messages already */
if (valid) {
var msg = message_store.get(element);
valid = !(msg.toString() && 'is_custom' in msg);
}
return !valid;
}
var patternMismatch = check$1(test_pattern, function (element) {
set_msg(element, 'patternMismatch', element.title ? sprintf(_('PatternMismatchWithTitle'), element.title) : _('PatternMismatch'));
});
/**
* TODO: when rangeOverflow and rangeUnderflow are both called directly and
* successful, the inRange and outOfRange classes won't get removed, unless
* element.validityState.valid is queried, too.
*/
var rangeOverflow = check$1(test_max, function (element) {
var type = get_type(element);
var wrapper = get_wrapper(element);
var outOfRangeClass = wrapper && wrapper.settings.classes.outOfRange || 'hf-out-of-range';
var inRangeClass = wrapper && wrapper.settings.classes.inRange || 'hf-in-range';
var msg = void 0;
switch (type) {
case 'date':
case 'datetime':
case 'datetime-local':
msg = sprintf(_('DateRangeOverflow'), format_date(string_to_date(element.getAttribute('max'), type), type));
break;
case 'time':
msg = sprintf(_('TimeRangeOverflow'), format_date(string_to_date(element.getAttribute('max'), type), type));
break;
// case 'number':
default:
msg = sprintf(_('NumberRangeOverflow'), string_to_number(element.getAttribute('max'), type));
break;
}
set_msg(element, 'rangeOverflow', msg);
element.classList.add(outOfRangeClass);
element.classList.remove(inRangeClass);
});
var rangeUnderflow = check$1(test_min, function (element) {
var type = get_type(element);
var wrapper = get_wrapper(element);
var outOfRangeClass = wrapper && wrapper.settings.classes.outOfRange || 'hf-out-of-range';
var inRangeClass = wrapper && wrapper.settings.classes.inRange || 'hf-in-range';
var msg = void 0;
switch (type) {
case 'date':
case 'datetime':
case 'datetime-local':
msg = sprintf(_('DateRangeUnderflow'), format_date(string_to_date(element.getAttribute('min'), type), type));
break;
case 'time':
msg = sprintf(_('TimeRangeUnderflow'), format_date(string_to_date(element.getAttribute('min'), type), type));
break;
// case 'number':
default:
msg = sprintf(_('NumberRangeUnderflow'), string_to_number(element.getAttribute('min'), type));
break;
}
set_msg(element, 'rangeUnderflow', msg);
element.classList.add(outOfRangeClass);
element.classList.remove(inRangeClass);
});
var stepMismatch = check$1(test_step, function (element) {
var list = get_next_valid(element);
var min = list[0];
var max = list[1];
var sole = false;
var msg = void 0;
if (min === null) {
sole = max;
} else if (max === null) {
sole = min;
}
if (sole !== false) {
msg = sprintf(_('StepMismatchOneValue'), sole);
} else {
msg = sprintf(_('StepMismatch'), min, max);
}
set_msg(element, 'stepMismatch', msg);
});
var tooLong = check$1(test_maxlength, function (element) {
set_msg(element, 'tooLong', sprintf(_('TextTooLong'), element.getAttribute('maxlength'), unicode_string_length(element.value)));
});
var tooShort = check$1(test_minlength, function (element) {
set_msg(element, 'tooShort', sprintf(_('Please lengthen this text to %l characters or more (you are currently using %l characters).'), element.getAttribute('minlength'), unicode_string_length(element.value)));
});
var typeMismatch = check$1(test_type, function (element) {
var msg = _('Please use the appropriate format.');
var type = get_type(element);
if (type === 'email') {
if (element.hasAttribute('multiple')) {
msg = _('Please enter a comma separated list of email addresses.');
} else {
msg = _('InvalidEmail');
}
} else if (type === 'url') {
msg = _('InvalidURL');
} else if (type === 'file') {
msg = _('Please select a file of the correct type.');
}
set_msg(element, 'typeMismatch', msg);
});
var valueMissing = check$1(test_required, function (element) {
var msg = _('ValueMissing');
var type = get_type(element);
if (type === 'checkbox') {
msg = _('CheckboxMissing');
} else if (type === 'radio') {
msg = _('RadioMissing');
} else if (type === 'file') {
if (element.hasAttribute('multiple')) {
msg = _('Please select one or more files.');
} else {
msg = _('FileMissing');
}
} else if (element instanceof window.HTMLSelectElement) {
msg = _('SelectMissing');
}
set_msg(element, 'valueMissing', msg);
});
var validity_state_checkers = {
badInput: badInput,
customError: customError,
patternMismatch: patternMismatch,
rangeOverflow: rangeOverflow,
rangeUnderflow: rangeUnderflow,
stepMismatch: stepMismatch,
tooLong: tooLong,
tooShort: tooShort,
typeMismatch: typeMismatch,
valueMissing: valueMissing
};
/**
* the validity state constructor
*/
var ValidityState = function ValidityState(element) {
if (!(element instanceof window.HTMLElement)) {
throw new Error('cannot create a ValidityState for a non-element');
}
var cached = ValidityState.cache.get(element);
if (cached) {
return cached;
}
if (!(this instanceof ValidityState)) {
/* working around a forgotten `new` */
return new ValidityState(element);
}
this.element = element;
ValidityState.cache.set(element, this);
};
/**
* the prototype for new validityState instances
*/
var ValidityStatePrototype = {};
ValidityState.prototype = ValidityStatePrototype;
ValidityState.cache = new WeakMap();
/**
* copy functionality from the validity checkers to the ValidityState
* prototype
*/
for (var prop in validity_state_checkers) {
Object.defineProperty(ValidityStatePrototype, prop, {
configurable: true,
enumerable: true,
get: function (func) {
return function () {
return func(this.element);
};
}(validity_state_checkers[prop]),
set: undefined
});
}
/**
* the "valid" property calls all other validity checkers and returns true,
* if all those return false.
*
* This is the major access point for _all_ other API methods, namely
* (check|report)Validity().
*/
Object.defineProperty(ValidityStatePrototype, 'valid', {
configurable: true,
enumerable: true,
get: function get() {
var wrapper = get_wrapper(this.element);
var validClass = wrapper && wrapper.settings.classes.valid || 'hf-valid';
var invalidClass = wrapper && wrapper.settings.classes.invalid || 'hf-invalid';
var userInvalidClass = wrapper && wrapper.settings.classes.userInvalid || 'hf-user-invalid';
var userValidClass = wrapper && wrapper.settings.classes.userValid || 'hf-user-valid';
var inRangeClass = wrapper && wrapper.settings.classes.inRange || 'hf-in-range';
var outOfRangeClass = wrapper && wrapper.settings.classes.outOfRange || 'hf-out-of-range';
var validatedClass = wrapper && wrapper.settings.classes.validated || 'hf-validated';
this.element.classList.add(validatedClass);
if (is_validation_candidate(this.element)) {
for (var _prop in validity_state_checkers) {
if (validity_state_checkers[_prop](this.element)) {
this.element.classList.add(invalidClass);
this.element.classList.remove(validClass);
this.element.classList.remove(userValidClass);
if (this.element.value !== this.element.defaultValue) {
this.element.classList.add(userInvalidClass);
} else {
this.element.classList.remove(userInvalidClass);
}
this.element.setAttribute('aria-invalid', 'true');
return false;
}
}
}
message_store.delete(this.element);
this.element.classList.remove(invalidClass, userInvalidClass, outOfRangeClass);
this.element.classList.add(validClass, inRangeClass);
if (this.element.value !== this.element.defaultValue) {
this.element.classList.add(userValidClass);
} else {
this.element.classList.remove(userValidClass);
}
this.element.setAttribute('aria-invalid', 'false');
return true;
},
set: undefined
});
/**
* mark the validity prototype, because that is what the client-facing
* code deals with mostly, not the property descriptor thing */
mark(ValidityStatePrototype);
/**
* check an element's validity with respect to it's form
*/
var checkValidity = return_hook_or('checkValidity', function (element) {
/* if this is a <form>, check validity of all child inputs */
if (element instanceof window.HTMLFormElement) {
return Array.prototype.map.call(element.elements, checkValidity).every(function (b) {
return b;
});
}
/* default is true, also for elements that are no validation candidates */
var valid = ValidityState(element).valid;
if (valid) {
var wrapped_form = get_wrapper(element);
if (wrapped_form && wrapped_form.settings.validEvent) {
trigger_event(element, 'valid');
}
} else {
trigger_event(element, 'invalid', { cancelable: true });
}
return valid;
});
var version = '0.9.2';
/* deprecate the old snake_case names
* TODO: delme before next non-patch release
*/
function w(name) {
var deprecated_message = 'Please use camelCase method names! The name "%s" is deprecated and will be removed in the next non-patch release.';
/* global console */
console.log(sprintf(deprecated_message, name));
}
/**
* public hyperform interface:
*/
function hyperform(form) {
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var classes = _ref.classes;
var _ref$debug = _ref.debug;
var debug = _ref$debug === undefined ? false : _ref$debug;
var extend_fieldset = _ref.extend_fieldset;
var extendFieldset = _ref.extendFieldset;
var novalidate_on_elements = _ref.novalidate_on_elements;
var novalidateOnElements = _ref.novalidateOnElements;
var prevent_implicit_submit = _ref.prevent_implicit_submit;
var preventImplicitSubmit = _ref.preventImplicitSubmit;
var revalidate = _ref.revalidate;
var _ref$strict = _ref.strict;
var strict = _ref$strict === undefined ? false : _ref$strict;
var valid_event = _ref.valid_event;
var validEvent = _ref.validEvent;
if (!classes) {
classes = {};
}
// TODO: clean up before next non-patch release
if (extendFieldset === undefined) {
if (extend_fieldset === undefined) {
extendFieldset = !strict;
} else {
w('extend_fieldset');
extendFieldset = extend_fieldset;
}
}
if (novalidateOnElements === undefined) {
if (novalidate_on_elements === undefined) {
novalidateOnElements = !strict;
} else {
w('novalidate_on_elements');
novalidateOnElements = novalidate_on_elements;
}
}
if (preventImplicitSubmit === undefined) {
if (prevent_implicit_submit === undefined) {
preventImplicitSubmit = false;
} else {
w('prevent_implicit_submit');
preventImplicitSubmit = prevent_implicit_submit;
}
}
if (revalidate === undefined) {
/* other recognized values: 'oninput', 'onblur', 'onsubmit' and 'never' */
revalidate = strict ? 'onsubmit' : 'hybrid';
}
if (validEvent === undefined) {
if (valid_event === undefined) {
validEvent = !strict;
} else {
w('valid_event');
validEvent = valid_event;
}
}
var settings = { debug: debug, strict: strict, preventImplicitSubmit: preventImplicitSubmit, revalidate: revalidate,
validEvent: validEvent, extendFieldset: extendFieldset, classes: classes };
if (form instanceof window.NodeList || form instanceof window.HTMLCollection || form instanceof Array) {
return Array.prototype.map.call(form, function (element) {
return hyperform(element, settings);
});
}
return new Wrapper(form, settings);
}
hyperform.version = version;
hyperform.checkValidity = checkValidity;
hyperform.reportValidity = reportValidity;
hyperform.setCustomValidity = setCustomValidity;
hyperform.stepDown = stepDown;
hyperform.stepUp = stepUp;
hyperform.validationMessage = validationMessage;
hyperform.ValidityState = ValidityState;
hyperform.valueAsDate = valueAsDate;
hyperform.valueAsNumber = valueAsNumber;
hyperform.willValidate = willValidate;
hyperform.setLanguage = function (lang) {
set_language(lang);return hyperform;
};
hyperform.addTranslation = function (lang, catalog) {
add_translation(lang, catalog);return hyperform;
};
hyperform.setRenderer = function (renderer, action) {
Renderer.set(renderer, action);return hyperform;
};
hyperform.addValidator = function (element, validator) {
custom_validator_registry.set(element, validator);return hyperform;
};
hyperform.setMessage = function (element, validator, message) {
custom_messages.set(element, validator, message);return hyperform;
};
hyperform.addHook = function (hook, action, position) {
add_hook(hook, action, position);return hyperform;
};
hyperform.removeHook = function (hook, action) {
remove_hook(hook, action);return hyperform;
};
// TODO: Remove in next non-patch version
hyperform.set_language = function (lang) {
w('set_language');set_language(lang);return hyperform;
};
hyperform.add_translation = function (lang, catalog) {
w('add_translation');add_translation(lang, catalog);return hyperform;
};
hyperform.set_renderer = function (renderer, action) {
w('set_renderer');Renderer.set(renderer, action);return hyperform;
};
hyperform.add_validator = function (element, validator) {
w('add_validator');custom_validator_registry.set(element, validator);return hyperform;
};
hyperform.set_message = function (element, validator, message) {
w('set_message');custom_messages.set(element, validator, message);return hyperform;
};
hyperform.add_hook = function (hook, action, position) {
w('add_hook');add_hook(hook, action, position);return hyperform;
};
hyperform.remove_hook = function (hook, action) {
w('remove_hook');remove_hook(hook, action);return hyperform;
};
return hyperform;
}()); | extend1994/cdnjs | ajax/libs/hyperform/0.9.2/hyperform.js | JavaScript | mit | 132,435 |
// (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
angular.module('mm.addons.mod_resource')
/**
* Helper to gather some common resouce functions.
*
* @module mm.addons.mod_resource
* @ngdoc service
* @name $mmaModResourceHelper
*/
.factory('$mmaModResourceHelper', function($mmUtil, $mmaModResource, $mmCourse) {
var self = {};
/**
* Opens a file of the resource activity.
*
* @module mm.addons.mod_resource
* @ngdoc method
* @name $mmaModResourceHelper#openFile
* @param {String} module Module where to get the contents.
* @param {String} courseId Course Id, used for completion purposes.
* @return {Promise} Resolved when done.
*/
self.openFile = function(module, courseId) {
var modal = $mmUtil.showModalLoading();
return $mmaModResource.openFile(module.contents, module.id).then(function() {
$mmaModResource.logView(module.instance).then(function() {
$mmCourse.checkModuleCompletion(courseId, module.completionstatus);
});
}).catch(function(error) {
$mmUtil.showErrorModalDefault(error, 'mma.mod_resource.errorwhileloadingthecontent', true);
}).finally(function() {
modal.dismiss();
});
};
return self;
}); | bmmg888/moodlemobile2 | www/addons/mod/resource/services/helper.js | JavaScript | apache-2.0 | 1,864 |
"use strict";
describe("DataService", function(){
var DataService;
beforeEach(function(){
inject(function(_DataService_){
DataService = _DataService_;
});
});
describe("#url", function(){
var tc = [
// Empty tests
[null, null],
[{}, null],
// Unknown resources
[{resource:''}, null],
[{resource:'bogus'}, null],
// Kind is not allowed
[{resource:'Pod'}, null],
[{resource:'User'}, null],
// resource normalization
[{resource:'users'}, "http://localhost:8443/oapi/v1/users"],
[{resource:'Users'}, "http://localhost:8443/oapi/v1/users"],
[{resource:'oauthaccesstokens'}, "http://localhost:8443/oapi/v1/oauthaccesstokens"],
[{resource:'OAuthAccessTokens'}, "http://localhost:8443/oapi/v1/oauthaccesstokens"],
[{resource:'pods'}, "http://localhost:8443/api/v1/pods"],
[{resource:'Pods'}, "http://localhost:8443/api/v1/pods"],
// Openshift resource
[{resource:'builds' }, "http://localhost:8443/oapi/v1/builds"],
[{resource:'builds', namespace:"foo" }, "http://localhost:8443/oapi/v1/namespaces/foo/builds"],
[{resource:'builds', name:"bar"}, "http://localhost:8443/oapi/v1/builds/bar"],
[{resource:'builds', namespace:"foo", name:"bar"}, "http://localhost:8443/oapi/v1/namespaces/foo/builds/bar"],
// k8s resource
[{resource:'replicationcontrollers' }, "http://localhost:8443/api/v1/replicationcontrollers"],
[{resource:'replicationcontrollers', namespace:"foo" }, "http://localhost:8443/api/v1/namespaces/foo/replicationcontrollers"],
[{resource:'replicationcontrollers', name:"bar"}, "http://localhost:8443/api/v1/replicationcontrollers/bar"],
[{resource:'replicationcontrollers', namespace:"foo", name:"bar"}, "http://localhost:8443/api/v1/namespaces/foo/replicationcontrollers/bar"],
// Subresources and webhooks
[{resource:'pods/proxy', name:"mypod:1123", namespace:"foo"}, "http://localhost:8443/api/v1/namespaces/foo/pods/mypod%3A1123/proxy"],
[{resource:'builds/clone', name:"mybuild", namespace:"foo"}, "http://localhost:8443/oapi/v1/namespaces/foo/builds/mybuild/clone"],
[{resource:'buildconfigs/instantiate', name:"mycfg", namespace:"foo"}, "http://localhost:8443/oapi/v1/namespaces/foo/buildconfigs/mycfg/instantiate"],
[{resource:'buildconfigs/webhooks/123/github', name:"mycfg", namespace:"foo"}, "http://localhost:8443/oapi/v1/namespaces/foo/buildconfigs/mycfg/webhooks/123/github"],
[{resource:'buildconfigs/webhooks/123?234/github', name:"mycfg", namespace:"foo"}, "http://localhost:8443/oapi/v1/namespaces/foo/buildconfigs/mycfg/webhooks/123%3F234/github"],
// Watch
[{resource:'pods', namespace:"foo", isWebsocket:true }, "ws://localhost:8443/api/v1/watch/namespaces/foo/pods"],
[{resource:'pods', namespace:"foo", isWebsocket:true, resourceVersion:"5"}, "ws://localhost:8443/api/v1/watch/namespaces/foo/pods?resourceVersion=5"],
// Namespaced subresource with params
[{resource:'pods/proxy', name:"mypod", namespace:"myns", myparam1:"myvalue"}, "http://localhost:8443/api/v1/namespaces/myns/pods/mypod/proxy?myparam1=myvalue"],
// Different API versions
[{resource:'builds',apiVersion:'v1beta3'}, "http://localhost:8443/osapi/v1beta3/builds"],
[{resource:'builds',apiVersion:'v1' }, "http://localhost:8443/oapi/v1/builds"],
[{resource:'builds',apiVersion:'unknown'}, "http://localhost:8443/oapi/unknown/builds"],
[{resource:'pods', apiVersion:'v1beta3'}, "http://localhost:8443/api/v1beta3/pods"],
[{resource:'pods', apiVersion:'v1' }, "http://localhost:8443/api/v1/pods"],
[{resource:'pods', apiVersion:'unknown'}, "http://localhost:8443/api/unknown/pods"]
];
angular.forEach(tc, function(item) {
it('should generate a correct URL for ' + JSON.stringify(item[0]), function() {
expect(DataService.url(item[0])).toEqual(item[1]);
});
});
});
});
| EricMountain-1A/openshift-origin | assets/test/spec/services/dataServiceSpec.js | JavaScript | apache-2.0 | 4,308 |
sap.ui.define([
"sap/ui/core/util/MockServer"
], function (MockServer) {
"use strict";
return {
init: function () {
// create
var oMockServer = new MockServer({
rootUri: "/destinations/northwind/V2/Northwind/Northwind.svc/"
});
var oUriParameters = jQuery.sap.getUriParameters();
// configure mock server with a delay
MockServer.config({
autoRespond: true,
autoRespondAfter: oUriParameters.get("serverDelay") || 1000
});
// simulate
var sPath = jQuery.sap.getModulePath("sap.ui.demo.wt.localService");
oMockServer.simulate(sPath + "/metadata.xml", sPath + "/mockdata");
// start
oMockServer.start();
}
};
});
| TobiasOetzel/ui5CodeJamHannover | webapp/localService/mockserver.js | JavaScript | apache-2.0 | 673 |
module["exports"] = [
"vit",
"silver",
"grå",
"svart",
"röd",
"grön",
"blå",
"gul",
"lila",
"indigo",
"guld",
"brun",
"rosa",
"purpur",
"korall"
];
| jmsenosa/random-keyword-sender | node_modules/faker/lib/locales/sv/commerce/color.js | JavaScript | gpl-2.0 | 182 |
// Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
/* eslint-disable */
{% include "erpnext/accounts/report/item_wise_sales_register/item_wise_sales_register.js" %}
frappe.query_reports["GST Itemised Sales Register"] = frappe.query_reports["Item-wise Sales Register"] | emakis/erpnext | erpnext/regional/report/gst_itemised_sales_register/gst_itemised_sales_register.js | JavaScript | gpl-3.0 | 339 |
var domEach = require('../utils').domEach,
_ = {
pick: require('lodash/pick'),
};
var toString = Object.prototype.toString;
/**
* Set / Get css.
*
* @param {String|Object} prop
* @param {String} val
* @return {self}
* @api public
*/
exports.css = function(prop, val) {
if (arguments.length === 2 ||
// When `prop` is a "plain" object
(toString.call(prop) === '[object Object]')) {
return domEach(this, function(idx, el) {
setCss(el, prop, val, idx);
});
} else {
return getCss(this[0], prop);
}
};
/**
* Set styles of all elements.
*
* @param {String|Object} prop
* @param {String} val
* @param {Number} idx - optional index within the selection
* @return {self}
* @api private
*/
function setCss(el, prop, val, idx) {
if ('string' == typeof prop) {
var styles = getCss(el);
if (typeof val === 'function') {
val = val.call(el, idx, styles[prop]);
}
if (val === '') {
delete styles[prop];
} else if (val != null) {
styles[prop] = val;
}
el.attribs.style = stringify(styles);
} else if ('object' == typeof prop) {
Object.keys(prop).forEach(function(k){
setCss(el, k, prop[k]);
});
}
}
/**
* Get parsed styles of the first element.
*
* @param {String} prop
* @return {Object}
* @api private
*/
function getCss(el, prop) {
var styles = parse(el.attribs.style);
if (typeof prop === 'string') {
return styles[prop];
} else if (Array.isArray(prop)) {
return _.pick(styles, prop);
} else {
return styles;
}
}
/**
* Stringify `obj` to styles.
*
* @param {Object} obj
* @return {Object}
* @api private
*/
function stringify(obj) {
return Object.keys(obj || {})
.reduce(function(str, prop){
return str += ''
+ (str ? ' ' : '')
+ prop
+ ': '
+ obj[prop]
+ ';';
}, '');
}
/**
* Parse `styles`.
*
* @param {String} styles
* @return {Object}
* @api private
*/
function parse(styles) {
styles = (styles || '').trim();
if (!styles) return {};
return styles
.split(';')
.reduce(function(obj, str){
var n = str.indexOf(':');
// skip if there is no :, or if it is the first/last character
if (n < 1 || n === str.length-1) return obj;
obj[str.slice(0,n).trim()] = str.slice(n+1).trim();
return obj;
}, {});
}
| Ronmantech/portf | webScraper/newsSearch/node_modules/cheerio/lib/api/css.js | JavaScript | gpl-3.0 | 2,374 |
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationImportExport = (props) => (
<SvgIcon {...props}>
<path d="M9 3L5 6.99h3V14h2V6.99h3L9 3zm7 14.01V10h-2v7.01h-3L15 21l4-3.99h-3z"/>
</SvgIcon>
);
CommunicationImportExport = pure(CommunicationImportExport);
CommunicationImportExport.displayName = 'CommunicationImportExport';
CommunicationImportExport.muiName = 'SvgIcon';
export default CommunicationImportExport;
| IsenrichO/mui-with-arrows | src/svg-icons/communication/import-export.js | JavaScript | mit | 490 |
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationPersonalVideo = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12z"/>
</SvgIcon>
);
NotificationPersonalVideo = pure(NotificationPersonalVideo);
NotificationPersonalVideo.displayName = 'NotificationPersonalVideo';
NotificationPersonalVideo.muiName = 'SvgIcon';
export default NotificationPersonalVideo;
| lawrence-yu/material-ui | src/svg-icons/notification/personal-video.js | JavaScript | mit | 534 |
/*! selectize.js | https://github.com/brianreavis/selectize.js | Apache License (v2) */
(function (factory) {
if (typeof exports === 'object') {
factory(require('jquery'));
} else if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(jQuery);
}
}(function ($) {
"use strict";
// --- src/contrib/highlight.js ---
/**
* highlight v3 | MIT license | Johann Burkard <[email protected]>
* Highlights arbitrary terms in a node.
*
* - Modified by Marshal <[email protected]> 2011-6-24 (added regex)
* - Modified by Brian Reavis <[email protected]> 2012-8-27 (cleanup)
*/
var highlight = function($element, pattern) {
if (typeof pattern === 'string' && !pattern.length) return;
var regex = (typeof pattern === 'string') ? new RegExp(pattern, 'i') : pattern;
var highlight = function(node) {
var skip = 0;
if (node.nodeType === 3) {
var pos = node.data.search(regex);
if (pos >= 0 && node.data.length > 0) {
var match = node.data.match(regex);
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(match[0].length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
} else if (node.nodeType === 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += highlight(node.childNodes[i]);
}
}
return skip;
};
return $element.each(function() {
highlight(this);
});
};
var unhighlight = function($element) {
return $element.find('span.highlight').each(function() {
var parent = this.parentNode;
parent.replaceChild(parent.firstChild, parent);
parent.normalize();
}).end();
};
// --- src/constants.js ---
/**
* selectize - A highly customizable select control with autocomplete.
* Copyright (c) 2013 Brian Reavis & contributors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* @author Brian Reavis <[email protected]>
*/
var IS_MAC = /Mac/.test(navigator.userAgent);
var KEY_COMMA = 188;
var KEY_RETURN = 13;
var KEY_ESC = 27;
var KEY_LEFT = 37;
var KEY_UP = 38;
var KEY_RIGHT = 39;
var KEY_DOWN = 40;
var KEY_BACKSPACE = 8;
var KEY_DELETE = 46;
var KEY_SHIFT = 16;
var KEY_CTRL = IS_MAC ? 18 : 17;
var KEY_TAB = 9;
var TAG_SELECT = 1;
var TAG_INPUT = 2;
var DIACRITICS = {
'a': '[aÀÁÂÃÄÅàáâãäå]',
'c': '[cÇç]',
'e': '[eÈÉÊËèéêë]',
'i': '[iÌÍÎÏìíîï]',
'n': '[nÑñ]',
'o': '[oÒÓÔÕÕÖØòóôõöø]',
's': '[sŠš]',
'u': '[uÙÚÛÜùúûü]',
'y': '[yŸÿý]',
'z': '[zŽž]'
};
// --- src/selectize.jquery.js ---
var defaults = {
delimiter: ',',
persist: true,
diacritics: true,
create: false,
highlight: true,
openOnFocus: true,
maxOptions: 1000,
maxItems: null,
hideSelected: null,
scrollDuration: 60,
loadThrottle: 300,
dataAttr: 'data-data',
sortField: null,
sortDirection: 'asc',
valueField: 'value',
labelField: 'text',
searchField: ['text'],
mode: null,
theme: 'default',
wrapperClass: 'selectize-control',
inputClass: 'selectize-input',
dropdownClass: 'selectize-dropdown',
load : null, // function(query, callback)
score : null, // function(search)
onChange : null, // function(value)
onItemAdd : null, // function(value, $item) { ... }
onItemRemove : null, // function(value) { ... }
onClear : null, // function() { ... }
onOptionAdd : null, // function(value, data) { ... }
onOptionRemove : null, // function(value) { ... }
onDropdownOpen : null, // function($dropdown) { ... }
onDropdownClose : null, // function($dropdown) { ... }
onType : null, // function(str) { ... }
render: {
item: null,
option: null,
option_create: null
}
};
$.fn.selectize = function (settings) {
var defaults = $.fn.selectize.defaults;
settings = settings || {};
return this.each(function() {
var instance, value, values, i, n, data, dataAttr, settings_element, tagName;
var $options, $option, $input = $(this);
tagName = $input[0].tagName.toLowerCase();
if (typeof settings === 'string') {
instance = $input.data('selectize');
instance[settings].apply(instance, Array.prototype.splice.apply(arguments, 1));
} else {
dataAttr = settings.dataAttr || defaults.dataAttr;
settings_element = {};
settings_element.placeholder = $input.attr('placeholder');
settings_element.options = {};
settings_element.items = [];
if (tagName === 'select') {
settings_element.maxItems = !!$input.attr('multiple') ? null : 1;
$options = $input.children();
for (i = 0, n = $options.length; i < n; i++) {
$option = $($options[i]);
value = $option.attr('value') || '';
if (!value.length) continue;
data = (dataAttr && $option.attr(dataAttr)) || {
'text' : $option.html(),
'value' : value
};
if (typeof data === 'string') data = JSON.parse(data);
settings_element.options[value] = data;
if ($option.is(':selected')) {
settings_element.items.push(value);
}
}
} else {
value = $.trim($input.val() || '');
if (value.length) {
values = value.split(settings.delimiter || defaults.delimiter);
for (i = 0, n = values.length; i < n; i++) {
settings_element.options[values[i]] = {
'text' : values[i],
'value' : values[i]
};
}
settings_element.items = values;
}
}
instance = new Selectize($input, $.extend(true, {}, defaults, settings_element, settings));
$input.data('selectize', instance);
$input.addClass('selectized');
}
});
};
$.fn.selectize.defaults = defaults;
// --- src/utils.js ---
var isset = function(object) {
return typeof object !== 'undefined';
};
var htmlEntities = function(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
};
var quoteRegExp = function(str) {
return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
};
var once = function(fn) {
var called = false;
return function() {
if (called) return;
called = true;
fn.apply(this, arguments);
};
};
var debounce = function(fn, delay) {
var timeout;
return function() {
var self = this;
var args = arguments;
window.clearTimeout(timeout);
timeout = window.setTimeout(function() {
fn.apply(self, args);
}, delay);
};
};
/**
* A workaround for http://bugs.jquery.com/ticket/6696
*
* @param {object} $parent - Parent element to listen on.
* @param {string} event - Event name.
* @param {string} selector - Descendant selector to filter by.
* @param {function} fn - Event handler.
*/
var watchChildEvent = function($parent, event, selector, fn) {
$parent.on(event, selector, function(e) {
var child = e.target;
while (child && child.parentNode !== $parent[0]) {
child = child.parentNode;
}
e.currentTarget = child;
return fn.apply(this, [e]);
});
};
var getSelection = function(input) {
var result = {};
if ('selectionStart' in input) {
result.start = input.selectionStart;
result.length = input.selectionEnd - result.start;
} else if (document.selection) {
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
result.start = sel.text.length - selLen;
result.length = selLen;
}
return result;
};
var transferStyles = function($from, $to, properties) {
var styles = {};
if (properties) {
for (var i = 0; i < properties.length; i++) {
styles[properties[i]] = $from.css(properties[i]);
}
} else {
styles = $from.css();
}
$to.css(styles);
return $to;
};
var measureString = function(str, $parent) {
var $test = $('<test>').css({
position: 'absolute',
top: -99999,
left: -99999,
width: 'auto',
padding: 0,
whiteSpace: 'nowrap'
}).text(str).appendTo('body');
transferStyles($parent, $test, [
'letterSpacing',
'fontSize',
'fontFamily',
'fontWeight',
'textTransform'
]);
var width = $test.width();
$test.remove();
return width;
};
var autoGrow = function($input) {
var update = function(e) {
var value, keyCode, printable, placeholder, width;
var shift, character;
e = e || window.event;
value = $input.val();
if (e.type && e.type.toLowerCase() === 'keydown') {
keyCode = e.keyCode;
printable = (
(keyCode >= 97 && keyCode <= 122) || // a-z
(keyCode >= 65 && keyCode <= 90) || // A-Z
(keyCode >= 48 && keyCode <= 57) || // 0-9
keyCode == 32 // space
);
if (printable) {
shift = e.shiftKey;
character = String.fromCharCode(e.keyCode);
if (shift) character = character.toUpperCase();
else character = character.toLowerCase();
value += character;
}
}
placeholder = $input.attr('placeholder') || '';
if (!value.length && placeholder.length) {
value = placeholder;
}
width = measureString(value, $input) + 4;
if (width !== $input.width()) {
$input.width(width);
$input.triggerHandler('resize');
}
};
$input.on('keydown keyup update blur', update);
update({});
};
// --- src/selectize.js ---
/**
* selectize.js
* Copyright (c) 2013 Brian Reavis & contributors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
* @author Brian Reavis <[email protected]>
*/
var Selectize = function($input, settings) {
$input[0].selectize = this;
this.$input = $input;
this.tagType = $input[0].tagName.toLowerCase() === 'select' ? TAG_SELECT : TAG_INPUT;
this.settings = settings;
this.highlightedValue = null;
this.isOpen = false;
this.isLocked = false;
this.isFocused = false;
this.isInputFocused = false;
this.isInputHidden = false;
this.isSetup = false;
this.isShiftDown = false;
this.isCtrlDown = false;
this.ignoreFocus = false;
this.hasOptions = false;
this.currentResults = null;
this.lastValue = '';
this.caretPos = 0;
this.loading = 0;
this.loadedSearches = {};
this.$activeOption = null;
this.$activeItems = [];
this.options = {};
this.userOptions = {};
this.items = [];
this.renderCache = {};
this.onSearchChange = debounce(this.onSearchChange, this.settings.loadThrottle);
if ($.isArray(settings.options)) {
var key = settings.valueField;
for (var i = 0; i < settings.options.length; i++) {
if (settings.options[i].hasOwnProperty(key)) {
this.options[settings.options[i][key]] = settings.options[i];
}
}
} else if (typeof settings.options === 'object') {
$.extend(this.options, settings.options);
delete this.settings.options;
}
// option-dependent defaults
this.settings.mode = this.settings.mode || (this.settings.maxItems === 1 ? 'single' : 'multi');
if (typeof this.settings.hideSelected !== 'boolean') {
this.settings.hideSelected = this.settings.mode === 'multi';
}
this.setup();
};
/**
* Creates all elements and sets up event bindings.
*/
Selectize.prototype.setup = function() {
var self = this;
var $wrapper;
var $control;
var $control_input;
var $dropdown;
var inputMode;
var displayMode;
var timeout_blur;
var timeout_focus;
$wrapper = $('<div>').addClass(this.settings.theme).addClass(this.settings.wrapperClass);
$control = $('<div>').addClass(this.settings.inputClass).addClass('items').toggleClass('has-options', !$.isEmptyObject(this.options)).appendTo($wrapper);
$control_input = $('<input type="text">').appendTo($control);
$dropdown = $('<div>').addClass(this.settings.dropdownClass).hide().appendTo($wrapper);
displayMode = this.$input.css('display');
$wrapper.css({
width: this.$input[0].style.width,
display: displayMode
});
inputMode = this.settings.mode;
$wrapper.toggleClass('single', inputMode === 'single');
$wrapper.toggleClass('multi', inputMode === 'multi');
if ((this.settings.maxItems === null || this.settings.maxItems > 1) && this.tagType === TAG_SELECT) {
this.$input.attr('multiple', 'multiple');
}
if (this.settings.placeholder) {
$control_input.attr('placeholder', this.settings.placeholder);
}
this.$wrapper = $wrapper;
this.$control = $control;
this.$control_input = $control_input;
this.$dropdown = $dropdown;
$control.on('mousedown', function(e) {
if (e.currentTarget === self.$control[0]) {
$control_input.trigger('focus');
} else {
self.focus(true);
}
e.preventDefault();
});
watchChildEvent($dropdown, 'mouseenter', '*', function() { return self.onOptionHover.apply(self, arguments); });
watchChildEvent($dropdown, 'mousedown', '*', function() { return self.onOptionSelect.apply(self, arguments); });
watchChildEvent($control, 'mousedown', '*:not(input)', function() { return self.onItemSelect.apply(self, arguments); });
autoGrow($control_input);
$control_input.on({
mousedown : function(e) { e.stopPropagation(); },
keydown : function() { return self.onKeyDown.apply(self, arguments); },
keyup : function() { return self.onKeyUp.apply(self, arguments); },
keypress : function() { return self.onKeyPress.apply(self, arguments); },
resize : function() { self.positionDropdown.apply(self, []); },
blur : function() { return self.onBlur.apply(self, arguments); },
focus : function() { return self.onFocus.apply(self, arguments); }
});
$(document).on({
keydown: function(e) {
self.isCtrlDown = e[IS_MAC ? 'altKey' : 'ctrlKey'];
self.isShiftDown = e.shiftKey;
if (self.isFocused && !self.isLocked) {
var tagName = (e.target.tagName || '').toLowerCase();
if (tagName === 'input' || tagName === 'textarea') return;
if ([KEY_SHIFT, KEY_BACKSPACE, KEY_DELETE, KEY_ESC, KEY_LEFT, KEY_RIGHT, KEY_TAB].indexOf(e.keyCode) !== -1) {
return self.onKeyDown.apply(self, arguments);
}
}
},
keyup: function(e) {
if (e.keyCode === KEY_CTRL) self.isCtrlDown = false;
else if (e.keyCode === KEY_SHIFT) self.isShiftDown = false;
},
mousedown: function(e) {
if (self.isFocused && !self.isLocked) {
// prevent events on the dropdown scrollbar from causing the control to blur
if (e.target === self.$dropdown[0]) {
var ignoreFocus = self.ignoreFocus;
self.ignoreFocus = true;
window.setTimeout(function() {
self.ignoreFocus = ignoreFocus;
self.focus(false);
}, 0);
return;
}
// blur on click outside
if (!self.$control.has(e.target).length && e.target !== self.$control[0]) {
self.blur();
}
}
}
});
$(window).on({
resize: function() {
if (self.isOpen) {
self.positionDropdown.apply(self, arguments);
}
}
});
this.$input.hide().after(this.$wrapper);
if ($.isArray(this.settings.items)) {
this.setValue(this.settings.items);
delete this.settings.items;
}
this.updateOriginalInput();
this.refreshItems();
this.updatePlaceholder();
this.isSetup = true;
};
/**
* Triggers a callback defined in the user-provided settings.
* Events: onItemAdd, onOptionAdd, etc
*
* @param {string} event
*/
Selectize.prototype.trigger = function(event) {
var args;
if (typeof this.settings[event] === 'function') {
args = Array.prototype.slice.apply(arguments, [1]);
this.settings[event].apply(this, args);
}
};
/**
* Triggered on <input> keypress.
*
* @param {object} e
* @returns {boolean}
*/
Selectize.prototype.onKeyPress = function(e) {
if (this.isLocked) return;
var character = String.fromCharCode(e.keyCode || e.which);
if (this.settings.create && character === this.settings.delimiter) {
this.createItem();
e.preventDefault();
return false;
}
};
/**
* Triggered on <input> keydown.
*
* @param {object} e
* @returns {boolean}
*/
Selectize.prototype.onKeyDown = function(e) {
if (this.isLocked) return;
var isInput = e.target === this.$control_input[0];
switch (e.keyCode || e.which) {
case KEY_ESC:
this.blur();
return;
case KEY_DOWN:
if (!this.isOpen && this.hasOptions && this.isInputFocused) {
this.open();
} else if (this.$activeOption) {
var $next = this.$activeOption.next();
if ($next.length) this.setActiveOption($next, true, true);
}
e.preventDefault();
break;
case KEY_UP:
if (this.$activeOption) {
var $prev = this.$activeOption.prev();
if ($prev.length) this.setActiveOption($prev, true, true);
}
e.preventDefault();
break;
case KEY_RETURN:
if (this.$activeOption) {
this.onOptionSelect({currentTarget: this.$activeOption});
}
e.preventDefault();
break;
case KEY_LEFT:
this.advanceSelection(-1, e);
break;
case KEY_RIGHT:
this.advanceSelection(1, e);
break;
case KEY_TAB:
if (this.settings.create && $.trim(this.$control_input.val()).length) {
this.createItem();
e.preventDefault();
}
break;
case KEY_BACKSPACE:
case KEY_DELETE:
this.deleteSelection(e);
break;
default:
if (this.isFull() || this.isInputHidden) {
e.preventDefault();
return;
}
}
if (!this.isFull()) {
this.focus(true);
}
};
/**
* Triggered on <input> keyup.
*
* @param {object} e
* @returns {boolean}
*/
Selectize.prototype.onKeyUp = function(e) {
if (this.isLocked) return;
var value = this.$control_input.val() || '';
if (this.lastValue !== value) {
this.lastValue = value;
this.onSearchChange(value);
this.refreshOptions();
this.trigger('onType', value);
}
};
/**
* Invokes the user-provide option provider / loader.
*
* Note: this function is debounced in the Selectize
* constructor (by `settings.loadDelay` milliseconds)
*
* @param {string} value
*/
Selectize.prototype.onSearchChange = function(value) {
if (!this.settings.load) return;
if (this.loadedSearches.hasOwnProperty(value)) return;
var self = this;
var $wrapper = this.$wrapper.addClass('loading');
this.loading++;
this.loadedSearches[value] = true;
this.settings.load.apply(this, [value, function(results) {
self.loading = Math.max(self.loading - 1, 0);
if (results && results.length) {
self.addOption(results);
self.refreshOptions(false);
if (self.isInputFocused) self.open();
}
if (!self.loading) {
$wrapper.removeClass('loading');
}
}]);
};
/**
* Triggered on <input> focus.
*
* @param {object} e (optional)
* @returns {boolean}
*/
Selectize.prototype.onFocus = function(e) {
this.isInputFocused = true;
this.isFocused = true;
if (this.ignoreFocus) return;
this.showInput();
this.setActiveItem(null);
this.$control.addClass('focus');
this.refreshOptions(!!this.settings.openOnFocus);
};
/**
* Triggered on <input> blur.
*
* @param {object} e
* @returns {boolean}
*/
Selectize.prototype.onBlur = function(e) {
this.isInputFocused = false;
if (this.ignoreFocus) return;
this.close();
this.setTextboxValue('');
this.setActiveOption(null);
this.setCaret(this.items.length, false);
if (!this.$activeItems.length) {
this.$control.removeClass('focus');
this.isFocused = false;
}
};
/**
* Triggered when the user rolls over
* an option in the autocomplete dropdown menu.
*
* @param {object} e
* @returns {boolean}
*/
Selectize.prototype.onOptionHover = function(e) {
this.setActiveOption(e.currentTarget, false);
};
/**
* Triggered when the user clicks on an option
* in the autocomplete dropdown menu.
*
* @param {object} e
* @returns {boolean}
*/
Selectize.prototype.onOptionSelect = function(e) {
e.preventDefault && e.preventDefault();
e.stopPropagation && e.stopPropagation();
this.focus(false);
var $target = $(e.currentTarget);
if ($target.hasClass('create')) {
this.createItem();
} else {
var value = $target.attr('data-value');
if (value) {
this.addItem(value);
this.setTextboxValue('');
}
}
};
/**
* Triggered when the user clicks on an item
* that has been selected.
*
* @param {object} e
* @returns {boolean}
*/
Selectize.prototype.onItemSelect = function(e) {
if (this.settings.mode === 'multi') {
e.preventDefault();
e.stopPropagation();
this.$control_input.triggerHandler('blur');
this.setActiveItem(e.currentTarget, e);
this.focus(false);
this.hideInput();
}
};
/**
* Sets the input field of the control to the specified value.
*
* @param {string} value
*/
Selectize.prototype.setTextboxValue = function(value) {
this.$control_input.val(value).triggerHandler('update');
this.lastValue = value;
};
/**
* Returns the value of the control. If multiple items
* can be selected (e.g. <select multiple>), this returns
* an array. If only one item can be selected, this
* returns a string.
*
* @returns {mixed}
*/
Selectize.prototype.getValue = function() {
if (this.tagType === TAG_SELECT && this.$input.attr('multiple')) {
return this.items;
} else {
return this.items.join(this.settings.delimiter);
}
};
/**
* Resets the selected items to the given value.
*
* @param {mixed} value
*/
Selectize.prototype.setValue = function(value) {
this.clear();
var items = $.isArray(value) ? value : [value];
for (var i = 0, n = items.length; i < n; i++) {
this.addItem(items[i]);
}
};
/**
* Sets the selected item.
*
* @param {object} $item
* @param {object} e (optional)
*/
Selectize.prototype.setActiveItem = function($item, e) {
var eventName;
var i, idx, begin, end, item, swap;
var $last;
$item = $($item);
// clear the active selection
if (!$item.length) {
$(this.$activeItems).removeClass('active');
this.$activeItems = [];
this.isFocused = this.isInputFocused;
return;
}
// modify selection
eventName = e && e.type.toLowerCase();
if (eventName === 'mousedown' && this.isShiftDown && this.$activeItems.length) {
$last = this.$control.children('.active:last');
begin = Array.prototype.indexOf.apply(this.$control[0].childNodes, [$last[0]]);
end = Array.prototype.indexOf.apply(this.$control[0].childNodes, [$item[0]]);
if (begin > end) {
swap = begin;
begin = end;
end = swap;
}
for (i = begin; i <= end; i++) {
item = this.$control[0].childNodes[i];
if (this.$activeItems.indexOf(item) === -1) {
$(item).addClass('active');
this.$activeItems.push(item);
}
}
e.preventDefault();
} else if ((eventName === 'mousedown' && this.isCtrlDown) || (eventName === 'keydown' && this.isShiftDown)) {
if ($item.hasClass('active')) {
idx = this.$activeItems.indexOf($item[0]);
this.$activeItems.splice(idx, 1);
$item.removeClass('active');
} else {
this.$activeItems.push($item.addClass('active')[0]);
}
} else {
$(this.$activeItems).removeClass('active');
this.$activeItems = [$item.addClass('active')[0]];
}
this.isFocused = !!this.$activeItems.length || this.isInputFocused;
};
/**
* Sets the selected item in the dropdown menu
* of available options.
*
* @param {object} $object
* @param {boolean} scroll
* @param {boolean} animate
*/
Selectize.prototype.setActiveOption = function($option, scroll, animate) {
var height_menu, height_item, y;
var scroll_top, scroll_bottom;
if (this.$activeOption) this.$activeOption.removeClass('active');
this.$activeOption = null;
$option = $($option);
if (!$option.length) return;
this.$activeOption = $option.addClass('active');
if (scroll || !isset(scroll)) {
height_menu = this.$dropdown.height();
height_item = this.$activeOption.outerHeight(true);
scroll = this.$dropdown.scrollTop() || 0;
y = this.$activeOption.offset().top - this.$dropdown.offset().top + scroll;
scroll_top = y;
scroll_bottom = y - height_menu + height_item;
if (y + height_item > height_menu - scroll) {
this.$dropdown.stop().animate({scrollTop: scroll_bottom}, animate ? this.settings.scrollDuration : 0);
} else if (y < scroll) {
this.$dropdown.stop().animate({scrollTop: scroll_top}, animate ? this.settings.scrollDuration : 0);
}
}
};
/**
* Hides the input element out of view, while
* retaining its focus.
*/
Selectize.prototype.hideInput = function() {
this.setTextboxValue('');
this.$control_input.css({opacity: 0, position: 'absolute', left: -10000});
this.isInputFocused = false;
this.isInputHidden = true;
};
/**
* Restores input visibility.
*/
Selectize.prototype.showInput = function() {
this.$control_input.css({opacity: 1, position: 'relative', left: 0});
this.isInputHidden = false;
};
/**
* Gives the control focus. If "trigger" is falsy,
* focus handlers won't be fired--causing the focus
* to happen silently in the background.
*
* @param {boolean} trigger
*/
Selectize.prototype.focus = function(trigger) {
var ignoreFocus = this.ignoreFocus;
var fire = trigger && !this.isInputFocused;
this.ignoreFocus = !trigger;
this.$control_input[0].focus();
if (fire) this.onFocus();
this.ignoreFocus = ignoreFocus;
};
/**
* Forces the control out of focus.
*/
Selectize.prototype.blur = function() {
this.$control_input.trigger('blur');
this.setActiveItem(null);
};
/**
* Splits a search string into an array of
* individual regexps to be used to match results.
*
* @param {string} query
* @returns {array}
*/
Selectize.prototype.parseSearchTokens = function(query) {
query = $.trim(String(query || '').toLowerCase());
if (!query || !query.length) return [];
var i, n, regex, letter;
var tokens = [];
var words = query.split(/ +/);
for (i = 0, n = words.length; i < n; i++) {
regex = quoteRegExp(words[i]);
if (this.settings.diacritics) {
for (letter in DIACRITICS) {
if (DIACRITICS.hasOwnProperty(letter)) {
regex = regex.replace(new RegExp(letter, 'g'), DIACRITICS[letter]);
}
}
}
tokens.push({
string : words[i],
regex : new RegExp(regex, 'i')
});
}
return tokens;
};
/**
* Returns a function to be used to score individual results.
* Results will be sorted by the score (descending). Scores less
* than or equal to zero (no match) will not be included in the results.
*
* @param {object} data
* @param {object} search
* @returns {function}
*/
Selectize.prototype.getScoreFunction = function(search) {
var self = this;
var tokens = search.tokens;
var calculateFieldScore = (function() {
if (!tokens.length) {
return function() { return 0; };
} else if (tokens.length === 1) {
return function(value) {
var score, pos;
value = String(value || '').toLowerCase();
pos = value.search(tokens[0].regex);
if (pos === -1) return 0;
score = tokens[0].string.length / value.length;
if (pos === 0) score += 0.5;
return score;
};
} else {
return function(value) {
var score, pos, i, j;
value = String(value || '').toLowerCase();
score = 0;
for (i = 0, j = tokens.length; i < j; i++) {
pos = value.search(tokens[i].regex);
if (pos === -1) return 0;
if (pos === 0) score += 0.5;
score += tokens[i].string.length / value.length;
}
return score / tokens.length;
};
}
})();
var calculateScore = (function() {
var fields = self.settings.searchField;
if (typeof fields === 'string') {
fields = [fields];
}
if (!fields || !fields.length) {
return function() { return 0; };
} else if (fields.length === 1) {
var field = fields[0];
return function(data) {
if (!data.hasOwnProperty(field)) return 0;
return calculateFieldScore(data[field]);
};
} else {
return function(data) {
var n = 0;
var score = 0;
for (var i = 0, j = fields.length; i < j; i++) {
if (data.hasOwnProperty(fields[i])) {
score += calculateFieldScore(data[fields[i]]);
n++;
}
}
return score / n;
};
}
})();
return calculateScore;
};
/**
* Searches through available options and returns
* a sorted array of matches. Includes options that
* have already been selected.
*
* The `settings` parameter can contain:
*
* - searchField
* - sortField
* - sortDirection
*
* Returns an object containing:
*
* - query {string}
* - tokens {array}
* - total {int}
* - items {array}
*
* @param {string} query
* @param {object} settings
* @returns {object}
*/
Selectize.prototype.search = function(query, settings) {
var self = this;
var value, score, search, calculateScore;
settings = settings || {};
query = $.trim(String(query || '').toLowerCase());
if (query !== this.lastQuery) {
this.lastQuery = query;
search = {
query : query,
tokens : this.parseSearchTokens(query),
total : 0,
items : []
};
// generate result scoring function
if (this.settings.score) {
calculateScore = this.settings.score.apply(this, [search]);
if (typeof calculateScore !== 'function') {
throw new Error('Selectize "score" setting must be a function that returns a function');
}
} else {
calculateScore = this.getScoreFunction(search);
}
// perform search and sort
if (query.length) {
for (value in this.options) {
if (this.options.hasOwnProperty(value)) {
score = calculateScore(this.options[value]);
if (score > 0) {
search.items.push({
score: score,
value: value
});
}
}
}
search.items.sort(function(a, b) {
return b.score - a.score;
});
} else {
for (value in this.options) {
if (this.options.hasOwnProperty(value)) {
search.items.push({
score: 1,
value: value
});
}
}
if (this.settings.sortField) {
search.items.sort((function() {
var field = self.settings.sortField;
var multiplier = self.settings.sortDirection === 'desc' ? -1 : 1;
return function(a, b) {
a = a && String(self.options[a.value][field] || '').toLowerCase();
b = b && String(self.options[b.value][field] || '').toLowerCase();
if (a > b) return 1 * multiplier;
if (b > a) return -1 * multiplier;
return 0;
};
})());
}
}
this.currentResults = search;
} else {
search = $.extend(true, {}, this.currentResults);
}
// apply limits and return
return this.prepareResults(search, settings);
};
/**
* Filters out any items that have already been selected
* and applies search limits.
*
* @param {object} results
* @param {object} settings
* @returns {object}
*/
Selectize.prototype.prepareResults = function(search, settings) {
if (this.settings.hideSelected) {
for (var i = search.items.length - 1; i >= 0; i--) {
if (this.items.indexOf(String(search.items[i].value)) !== -1) {
search.items.splice(i, 1);
}
}
}
search.total = search.items.length;
if (typeof settings.limit === 'number') {
search.items = search.items.slice(0, settings.limit);
}
return search;
};
/**
* Refreshes the list of available options shown
* in the autocomplete dropdown menu.
*
* @param {boolean} triggerDropdown
*/
Selectize.prototype.refreshOptions = function(triggerDropdown) {
if (typeof triggerDropdown === 'undefined') {
triggerDropdown = true;
}
var i, n;
var hasCreateOption;
var query = this.$control_input.val();
var results = this.search(query, {});
var html = [];
// build markup
n = results.items.length;
if (typeof this.settings.maxOptions === 'number') {
n = Math.min(n, this.settings.maxOptions);
}
for (i = 0; i < n; i++) {
html.push(this.render('option', this.options[results.items[i].value]));
}
this.$dropdown.html(html.join(''));
// highlight matching terms inline
if (this.settings.highlight && results.query.length && results.tokens.length) {
for (i = 0, n = results.tokens.length; i < n; i++) {
highlight(this.$dropdown, results.tokens[i].regex);
}
}
// add "selected" class to selected options
if (!this.settings.hideSelected) {
for (i = 0, n = this.items.length; i < n; i++) {
this.getOption(this.items[i]).addClass('selected');
}
}
// add create option
hasCreateOption = this.settings.create && results.query.length;
if (hasCreateOption) {
this.$dropdown.prepend(this.render('option_create', {input: query}));
}
// activate
this.hasOptions = results.items.length > 0 || hasCreateOption;
if (this.hasOptions) {
this.setActiveOption(this.$dropdown[0].childNodes[hasCreateOption && results.items.length > 0 ? 1 : 0]);
if (triggerDropdown && !this.isOpen) { this.open(); }
} else {
this.setActiveOption(null);
if (triggerDropdown && this.isOpen) { this.close(); }
}
};
/**
* Adds an available option. If it already exists,
* nothing will happen. Note: this does not refresh
* the options list dropdown (use `refreshOptions`
* for that).
*
* @param {string} value
* @param {object} data
*/
Selectize.prototype.addOption = function(value, data) {
if ($.isArray(value)) {
for (var i = 0, n = value.length; i < n; i++) {
this.addOption(value[i][this.settings.valueField], value[i]);
}
return;
}
if (this.options.hasOwnProperty(value)) return;
value = String(value);
this.userOptions[value] = true;
this.options[value] = data;
this.lastQuery = null;
this.trigger('onOptionAdd', value, data);
};
/**
* Updates an option available for selection. If
* it is visible in the selected items or options
* dropdown, it will be re-rendered automatically.
*
* @param {string} value
* @param {object} data
*/
Selectize.prototype.updateOption = function(value, data) {
value = String(value);
this.options[value] = data;
if (isset(this.renderCache['item'])) delete this.renderCache['item'][value];
if (isset(this.renderCache['option'])) delete this.renderCache['option'][value];
if (this.items.indexOf(value) !== -1) {
var $item = this.getItem(value);
var $item_new = $(this.render('item', data));
if ($item.hasClass('active')) $item_new.addClass('active');
$item.replaceWith($item_new);
}
if (this.isOpen) {
this.refreshOptions(false);
}
};
/**
* Removes an option.
*
* @param {string} value
*/
Selectize.prototype.removeOption = function(value) {
value = String(value);
delete this.userOptions[value];
delete this.options[value];
this.lastQuery = null;
this.trigger('onOptionRemove', value);
};
/**
* Returns the jQuery element of the option
* matching the given value.
*
* @param {string} value
* @returns {object}
*/
Selectize.prototype.getOption = function(value) {
return this.$dropdown.children('[data-value="' + value.replace(/(['"])/g, '\\$1') + '"]:first');
};
/**
* Returns the jQuery element of the item
* matching the given value.
*
* @param {string} value
* @returns {object}
*/
Selectize.prototype.getItem = function(value) {
var i = this.items.indexOf(value);
if (i !== -1) {
if (i >= this.caretPos) i++;
var $el = $(this.$control[0].childNodes[i]);
if ($el.attr('data-value') === value) {
return $el;
}
}
return $();
};
/**
* "Selects" an item. Adds it to the list
* at the current caret position.
*
* @param {string} value
*/
Selectize.prototype.addItem = function(value) {
var $item;
var self = this;
var inputMode = this.settings.mode;
var isFull = this.isFull();
value = String(value);
if (inputMode === 'single') this.clear();
if (inputMode === 'multi' && isFull) return;
if (this.items.indexOf(value) !== -1) return;
if (!this.options.hasOwnProperty(value)) return;
$item = $(this.render('item', this.options[value]));
this.items.splice(this.caretPos, 0, value);
this.insertAtCaret($item);
isFull = this.isFull();
this.$control.toggleClass('has-items', true);
this.$control.toggleClass('full', isFull).toggleClass('not-full', !isFull);
if (this.isSetup) {
// remove the option from the menu
var options = this.$dropdown[0].childNodes;
for (var i = 0; i < options.length; i++) {
var $option = $(options[i]);
if ($option.attr('data-value') === value) {
$option.remove();
if ($option[0] === this.$activeOption[0]) {
this.setActiveOption(options.length ? $(options[0]).addClass('active') : null);
}
break;
}
}
// hide the menu if the maximum number of items have been selected or no options are left
if (!options.length || (this.settings.maxItems !== null && this.items.length >= this.settings.maxItems)) {
this.close();
} else {
this.positionDropdown();
}
// restore focus to input
if (this.isFocused) {
window.setTimeout(function() {
if (inputMode === 'single') {
self.blur();
self.focus(false);
self.hideInput();
} else {
self.focus(false);
}
}, 0);
}
this.updatePlaceholder();
this.updateOriginalInput();
this.trigger('onItemAdd', value, $item);
}
};
/**
* Removes the selected item matching
* the provided value.
*
* @param {string} value
*/
Selectize.prototype.removeItem = function(value) {
var $item, i, idx;
$item = (typeof value === 'object') ? value : this.getItem(value);
value = String($item.attr('data-value'));
i = this.items.indexOf(value);
if (i !== -1) {
$item.remove();
if ($item.hasClass('active')) {
idx = this.$activeItems.indexOf($item[0]);
this.$activeItems.splice(idx, 1);
}
this.items.splice(i, 1);
this.$control.toggleClass('has-items', this.items.length > 0);
this.$control.removeClass('full').addClass('not-full');
this.lastQuery = null;
if (!this.settings.persist && this.userOptions.hasOwnProperty(value)) {
this.removeOption(value);
}
this.setCaret(i);
this.positionDropdown();
this.refreshOptions(false);
if (!this.hasOptions) { this.close(); }
else if (this.isInputFocused) { this.open(); }
this.updatePlaceholder();
this.updateOriginalInput();
this.trigger('onItemRemove', value);
}
};
/**
* Invokes the `create` method provided in the
* selectize options that should provide the data
* for the new item, given the user input.
*
* Once this completes, it will be added
* to the item list.
*/
Selectize.prototype.createItem = function() {
var self = this;
var input = $.trim(this.$control_input.val() || '');
var caret = this.caretPos;
if (!input.length) return;
this.lock();
this.close();
var setup = (typeof this.settings.create === 'function') ? this.settings.create : function(input) {
var data = {};
data[self.settings.labelField] = input;
data[self.settings.valueField] = input;
return data;
};
var create = once(function(data) {
self.unlock();
self.focus(false);
var value = data && data[self.settings.valueField];
if (!value) return;
self.addOption(value, data);
self.setCaret(caret, false);
self.addItem(value);
self.setTextboxValue('');
self.refreshOptions(true);
self.focus(false);
});
var output = setup(input, create);
if (typeof output === 'object') {
create(output);
}
};
/**
* Re-renders the selected item lists.
*/
Selectize.prototype.refreshItems = function() {
var isFull = this.isFull();
this.lastQuery = null;
this.$control.toggleClass('full', isFull).toggleClass('not-full', !isFull);
this.$control.toggleClass('has-items', this.items.length > 0);
if (this.isSetup) {
for (var i = 0; i < this.items.length; i++) {
this.addItem(this.items);
}
}
this.updateOriginalInput();
};
/**
* Determines whether or not more items can be added
* to the control without exceeding the user-defined maximum.
*
* @returns {boolean}
*/
Selectize.prototype.isFull = function() {
return this.settings.maxItems !== null && this.items.length >= this.settings.maxItems;
};
/**
* Refreshes the original <select> or <input>
* element to reflect the current state.
*/
Selectize.prototype.updateOriginalInput = function() {
var i, n, options;
if (this.$input[0].tagName.toLowerCase() === 'select') {
options = [];
for (i = 0, n = this.items.length; i < n; i++) {
options.push('<option value="' + htmlEntities(this.items[i]) + '" selected="selected"></option>');
}
if (!options.length && !this.$input.attr('multiple')) {
options.push('<option value="" selected="selected"></option>');
}
this.$input.html(options.join(''));
} else {
this.$input.val(this.getValue());
}
this.$input.trigger('change');
if (this.isSetup) {
this.trigger('onChange', this.$input.val());
}
};
/**
* Shows/hide the input placeholder depending
* on if there items in the list already.
*/
Selectize.prototype.updatePlaceholder = function() {
if (!this.settings.placeholder) return;
var $input = this.$control_input;
if (this.items.length) {
$input.removeAttr('placeholder');
} else {
$input.attr('placeholder', this.settings.placeholder);
}
$input.triggerHandler('update');
};
/**
* Shows the autocomplete dropdown containing
* the available options.
*/
Selectize.prototype.open = function() {
if (this.isOpen || (this.settings.mode === 'multi' && this.isFull())) return;
this.isOpen = true;
this.positionDropdown();
this.$control.addClass('dropdown-active');
this.$dropdown.show();
this.trigger('onDropdownOpen', this.$dropdown);
};
/**
* Closes the autocomplete dropdown menu.
*/
Selectize.prototype.close = function() {
if (!this.isOpen) return;
this.$dropdown.hide();
this.$control.removeClass('dropdown-active');
this.isOpen = false;
this.trigger('onDropdownClose', this.$dropdown);
};
/**
* Calculates and applies the appropriate
* position of the dropdown.
*/
Selectize.prototype.positionDropdown = function() {
var $control = this.$control;
var offset = $control.position();
offset.top += $control.outerHeight(true);
this.$dropdown.css({
width : $control.outerWidth(),
top : offset.top,
left : offset.left
});
};
/**
* Resets / clears all selected items
* from the control.
*/
Selectize.prototype.clear = function() {
if (!this.items.length) return;
this.$control.removeClass('has-items');
this.$control.children(':not(input)').remove();
this.items = [];
this.setCaret(0);
this.updatePlaceholder();
this.updateOriginalInput();
this.trigger('onClear');
};
/**
* A helper method for inserting an element
* at the current caret position.
*
* @param {object} $el
*/
Selectize.prototype.insertAtCaret = function($el) {
var caret = Math.min(this.caretPos, this.items.length);
if (caret === 0) {
this.$control.prepend($el);
} else {
$(this.$control[0].childNodes[caret]).before($el);
}
this.setCaret(caret + 1);
};
/**
* Removes the current selected item(s).
*
* @param {object} e (optional)
*/
Selectize.prototype.deleteSelection = function(e) {
var i, n, direction, selection, values, caret, $tail;
direction = (e.keyCode === KEY_BACKSPACE) ? -1 : 1;
selection = getSelection(this.$control_input[0]);
if (this.$activeItems.length) {
$tail = this.$control.children('.active:' + (direction > 0 ? 'last' : 'first'));
caret = Array.prototype.indexOf.apply(this.$control[0].childNodes, [$tail[0]]);
if (this.$activeItems.length > 1 && direction > 0) { caret--; }
values = [];
for (i = 0, n = this.$activeItems.length; i < n; i++) {
values.push($(this.$activeItems[i]).attr('data-value'));
}
while (values.length) {
this.removeItem(values.pop());
}
this.setCaret(caret);
e.preventDefault();
e.stopPropagation();
} else if ((this.isInputFocused || this.settings.mode === 'single') && this.items.length) {
if (direction < 0 && selection.start === 0 && selection.length === 0) {
this.removeItem(this.items[this.caretPos - 1]);
} else if (direction > 0 && selection.start === this.$control_input.val().length) {
this.removeItem(this.items[this.caretPos]);
}
}
};
/**
* Selects the previous / next item (depending
* on the `direction` argument).
*
* > 0 - right
* < 0 - left
*
* @param {int} direction
* @param {object} e (optional)
*/
Selectize.prototype.advanceSelection = function(direction, e) {
if (direction === 0) return;
var tail = direction > 0 ? 'last' : 'first';
var selection = getSelection(this.$control_input[0]);
if (this.isInputFocused) {
var valueLength = this.$control_input.val().length;
var cursorAtEdge = direction < 0
? selection.start === 0 && selection.length === 0
: selection.start === valueLength;
if (cursorAtEdge && !valueLength) {
this.advanceCaret(direction, e);
}
} else {
var $tail = this.$control.children('.active:' + tail);
if ($tail.length) {
var idx = Array.prototype.indexOf.apply(this.$control[0].childNodes, [$tail[0]]);
this.setCaret(direction > 0 ? idx + 1 : idx);
}
}
};
/**
* Moves the caret left / right.
*
* @param {int} direction
* @param {object} e (optional)
*/
Selectize.prototype.advanceCaret = function(direction, e) {
if (direction === 0) return;
var fn = direction > 0 ? 'next' : 'prev';
if (this.isShiftDown) {
var $adj = this.$control_input[fn]();
if ($adj.length) {
this.blur();
this.setActiveItem($adj);
e && e.preventDefault();
}
} else {
this.setCaret(this.caretPos + direction);
}
};
/**
* Moves the caret to the specified index.
*
* @param {int} i
* @param {boolean} focus
*/
Selectize.prototype.setCaret = function(i, focus) {
if (this.settings.mode === 'single' || this.isFull()) {
i = this.items.length;
} else {
i = Math.max(0, Math.min(this.items.length, i));
}
// the input must be moved by leaving it in place and moving the
// siblings, due to the fact that focus cannot be restored once lost
// on mobile webkit devices
var j, n, fn, $children, $child;
$children = this.$control.children(':not(input)');
for (j = 0, n = $children.length; j < n; j++) {
$child = $($children[j]).detach();
if (j < i) {
this.$control_input.before($child);
} else {
this.$control.append($child);
}
}
this.caretPos = i;
if (focus && this.isSetup) {
this.focus(true);
}
};
/**
* Disables user input on the control. Used while
* items are being asynchronously created.
*/
Selectize.prototype.lock = function() {
this.isLocked = true;
this.$control.addClass('locked');
};
/**
* Re-enables user input on the control.
*/
Selectize.prototype.unlock = function() {
this.isLocked = false;
this.$control.removeClass('locked');
};
/**
* A helper method for rendering "item" and
* "option" templates, given the data.
*
* @param {string} templateName
* @param {object} data
* @returns {string}
*/
Selectize.prototype.render = function(templateName, data) {
cache = isset(cache) ? cache : true;
var value, label;
var html = '';
var cache = false;
if (['option', 'item'].indexOf(templateName) !== -1) {
value = data[this.settings.valueField];
cache = isset(value);
}
if (cache) {
if (!isset(this.renderCache[templateName])) {
this.renderCache[templateName] = {};
}
if (this.renderCache[templateName].hasOwnProperty(value)) {
return this.renderCache[templateName][value];
}
}
if (this.settings.render && typeof this.settings.render[templateName] === 'function') {
html = this.settings.render[templateName].apply(this, [data]);
} else {
label = data[this.settings.labelField];
switch (templateName) {
case 'option':
html = '<div class="option">' + label + '</div>';
break;
case 'item':
html = '<div class="item">' + label + '</div>';
break;
case 'option_create':
html = '<div class="create">Create <strong>' + htmlEntities(data.input) + '</strong>…</div>';
break;
}
}
if (isset(value)) {
html = html.replace(/^[\ ]*<([a-z][a-z0-9\-_]*(?:\:[a-z][a-z0-9\-_]*)?)/i, '<$1 data-value="' + value + '"');
}
if (cache) {
this.renderCache[templateName][value] = html;
}
return html;
};
return Selectize;
}));
| hare1039/cdnjs | ajax/libs/selectize.js/0.1.7/selectize.js | JavaScript | mit | 49,830 |
function mf_file_callback_upload(data){
if(data.error == false){
//como aun tiene jquery 1.4 aun no tiene prop
var image_thumb = data.phpthumb;
image_thumb += '?&w=150&h=120&zc=1&src=';
image_thumb += data.file_url;
//jQuery('#img_thumb_'+data.field_id).attr('src',image_thumb);
jQuery('#edit-'+data.field_id).attr('href',data.file_url);
jQuery('#'+data.field_id).val(data.name);
// display filename
jQuery('#filename_'+data.field_id).empty();
var p = document.createElement("p");
var txt = document.createTextNode(data.name);
p.appendChild(txt);
jQuery('#filename_'+data.field_id).append(p);
var success_resp = '<span class="mf-upload-success" >'+data.msg+'</span>';
jQuery('#response-'+data.field_id).html(success_resp).show();
jQuery('#photo_edit_link_'+data.field_id).show();
setTimeout("remove_resp('#response-"+data.field_id+"')",5000);
}else{
//show errors
var error_resp = '<span class="mf-upload-error" >'+data.msg+'</span>';
jQuery('#response-'+data.field_id).html(error_resp).show();
setTimeout("remove_resp('#response-"+data.field_id+"')",5000);
}
}
function remove_resp(field_id){
jQuery(field_id).fadeOut('slow', function(){
jQuery(this).empty();
});
}
jQuery(document).on('click', '.remove_file',function(){
var message = jQuery(this).attr('alt');
if(confirm(message)){
var pattern = /remove\-(.+)/i;
var id = jQuery(this).attr('id');
id = pattern.exec(id);
id = id[1];
//todo añadir al arreglo de estan los files a borrar
jQuery('#'+id).val('');
jQuery('#photo_edit_link_'+id).hide();
// remove filename
jQuery('#filename_'+id).empty();
//jQuery("#img_thumb_"+id).attr("src",mf_js.mf_url+"images/noimage.jpg");
}
});
| dactrtr/MamaisonWp | wp-content/plugins/magic-fields-2/field_types/file_field/file_field.js | JavaScript | gpl-2.0 | 1,810 |
var request = require('..')
, https = require('https')
, fs = require('fs')
, path = require('path')
, should = require('should')
, express = require('express');
describe('request(url)', function(){
it('should be supported', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hello');
});
var s = app.listen(function(){
var url = 'http://localhost:' + s.address().port;
request(url)
.get('/')
.expect("hello", done);
});
})
describe('.end(cb)', function() {
it('should set `this` to the test object when calling cb', function(done) {
var app = express();
var s = app.listen(function(){
var url = 'http://localhost:' + s.address().port;
var test = request(url).get('/');
test.end(function(err, res) {
this.should.eql(test);
done();
});
});
})
})
})
describe('request(app)', function(){
it('should fire up the app on an ephemeral port', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
request(app)
.get('/')
.end(function(err, res){
res.should.have.status(200);
res.text.should.equal('hey');
done();
});
})
it('should work with an active server', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
var server = app.listen(4000, function(){
request(server)
.get('/')
.end(function(err, res){
res.should.have.status(200);
res.text.should.equal('hey');
done();
});
});
})
it('should work with remote server', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
var server = app.listen(4001, function(){
request('http://localhost:4001')
.get('/')
.end(function(err, res){
res.should.have.status(200);
res.text.should.equal('hey');
done();
});
});
})
it('should work with a https server', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
var fixtures = path.join(__dirname, 'fixtures');
var server = https.createServer({
key: fs.readFileSync(path.join(fixtures, 'test_key.pem')),
cert: fs.readFileSync(path.join(fixtures, 'test_cert.pem'))
}, app);
request(server)
.get('/')
.end(function(err, res){
if (err) return done(err);
res.should.have.status(200);
res.text.should.equal('hey');
done();
});
})
it('should work with .send() etc', function(done){
var app = express();
app.use(express.bodyParser());
app.post('/', function(req, res){
res.send(req.body.name);
});
request(app)
.post('/')
.send({ name: 'tobi' })
.expect('tobi', done);
})
it('should work when unbuffered', function(done){
var app = express();
app.get('/', function(req, res){
res.end('Hello');
});
request(app)
.get('/')
.expect('Hello', done);
})
it('should default redirects to 0', function(done){
var app = express();
app.get('/', function(req, res){
res.redirect('/login');
});
request(app)
.get('/')
.expect(302, done);
})
it('should handle socket errors', function(done) {
var app = express();
app.get('/', function(req, res){
res.destroy();
});
request(app)
.get('/')
.end(function(err) {
should.exist(err);
done();
});
})
describe('.expect(status[, fn])', function(){
it('should assert the response status', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
request(app)
.get('/')
.expect(404)
.end(function(err, res){
err.message.should.equal('expected 404 "Not Found", got 200 "OK"');
done();
});
})
})
describe('.expect(status)', function () {
it('should assert only status', function (done) {
var app = express();
app.get('/', function (req, res) {
res.send('hey');
})
request(app)
.get('/')
.expect(200)
.end(done)
})
})
describe('.expect(status, body[, fn])', function(){
it('should assert the response body and status', function(done){
var app = express();
app.get('/', function(req, res){
res.send('foo');
});
request(app)
.get('/')
.expect(200, 'foo', done)
});
describe("when the body argument is an empty string", function() {
it("should not quietly pass on failure", function(done) {
var app = express();
app.get('/', function(req, res){
res.send('foo');
});
request(app)
.get('/')
.expect(200, '')
.end(function(err, res){
err.message.should.equal('expected \'\' response body, got \'foo\'');
done();
});
});
});
})
describe('.expect(body[, fn])', function(){
it('should assert the response body', function(done){
var app = express();
app.set('json spaces', 0);
app.get('/', function(req, res){
res.send({ foo: 'bar' });
});
request(app)
.get('/')
.expect('hey')
.end(function(err, res){
err.message.should.equal('expected \'hey\' response body, got \'{"foo":"bar"}\'');
done();
});
})
it('should assert the response text', function(done){
var app = express();
app.set('json spaces', 0);
app.get('/', function(req, res){
res.send({ foo: 'bar' });
});
request(app)
.get('/')
.expect('{"foo":"bar"}', done);
})
it('should assert the parsed response body', function(done){
var app = express();
app.set('json spaces', 0);
app.get('/', function(req, res){
res.send({ foo: 'bar' });
});
request(app)
.get('/')
.expect({ foo: 'baz' })
.end(function(err, res){
err.message.should.equal('expected { foo: \'baz\' } response body, got { foo: \'bar\' }');
request(app)
.get('/')
.expect({ foo: 'bar' })
.end(done);
});
})
it('should support regular expressions', function(done){
var app = express();
app.get('/', function(req, res){
res.send('foobar');
});
request(app)
.get('/')
.expect(/^bar/)
.end(function(err, res){
err.message.should.equal('expected body \'foobar\' to match /^bar/');
done();
});
})
it('should assert response body multiple times', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey tj');
});
request(app)
.get('/')
.expect(/tj/)
.expect('hey')
.expect('hey tj')
.end(function (err, res) {
err.message.should.equal("expected 'hey' response body, got 'hey tj'");
done();
});
})
it('should assert response body multiple times with no exception', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey tj');
});
request(app)
.get('/')
.expect(/tj/)
.expect(/^hey/)
.expect('hey tj', done);
})
})
describe('.expect(field, value[, fn])', function(){
it('should assert the header field presence', function(done){
var app = express();
app.get('/', function(req, res){
res.send({ foo: 'bar' });
});
request(app)
.get('/')
.expect('Content-Foo', 'bar')
.end(function(err, res){
err.message.should.equal('expected "Content-Foo" header field');
done();
});
})
it('should assert the header field value', function(done){
var app = express();
app.get('/', function(req, res){
res.send({ foo: 'bar' });
});
request(app)
.get('/')
.expect('Content-Type', 'text/html')
.end(function(err, res){
err.message.should.equal('expected "Content-Type" of "text/html", got "application/json; charset=utf-8"');
done();
});
})
it('should assert multiple fields', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
request(app)
.get('/')
.expect('Content-Type', 'text/html; charset=utf-8')
.expect('Content-Length', '3')
.end(done);
})
it('should support regular expressions', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
request(app)
.get('/')
.expect('Content-Type', /^application/)
.end(function(err){
err.message.should.equal('expected "Content-Type" matching /^application/, got "text/html; charset=utf-8"');
done();
});
})
describe('handling multiple assertions per field', function(){
it('should work', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
request(app)
.get('/')
.expect('Content-Type', /text/)
.expect('Content-Type', /html/)
.end(done);
});
it('should return an error if the first one fails', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
request(app)
.get('/')
.expect('Content-Type', /bloop/)
.expect('Content-Type', /html/)
.end(function(err){
err.message.should.equal('expected "Content-Type" matching /bloop/, got "text/html; charset=utf-8"');
done();
});
});
it('should return an error if a middle one fails', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
request(app)
.get('/')
.expect('Content-Type', /text/)
.expect('Content-Type', /bloop/)
.expect('Content-Type', /html/)
.end(function(err){
err.message.should.equal('expected "Content-Type" matching /bloop/, got "text/html; charset=utf-8"');
done();
});
});
it('should return an error if the last one fails', function(done){
var app = express();
app.get('/', function(req, res){
res.send('hey');
});
request(app)
.get('/')
.expect('Content-Type', /text/)
.expect('Content-Type', /html/)
.expect('Content-Type', /bloop/)
.end(function(err){
err.message.should.equal('expected "Content-Type" matching /bloop/, got "text/html; charset=utf-8"');
done();
});
});
});
})
})
describe('request.agent(app)', function(){
var app = express();
app.use(express.cookieParser());
app.get('/', function(req, res){
res.cookie('cookie', 'hey');
res.send();
});
app.get('/return', function(req, res){
if (req.cookies.cookie) res.send(req.cookies.cookie);
else res.send(':(')
});
var agent = request.agent(app);
it('should save cookies', function(done){
agent
.get('/')
.expect('set-cookie', 'cookie=hey; Path=/', done);
})
it('should send cookies', function(done){
agent
.get('/return')
.expect('hey', done);
})
})
| PlenipotentSS/GhostBlug | node_modules/supertest/test/supertest.js | JavaScript | mit | 11,590 |
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["jss"] = factory();
else
root["jss"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.create = exports.sheets = exports.SheetsRegistry = undefined;
var _Jss = __webpack_require__(1);
var _Jss2 = _interopRequireDefault(_Jss);
var _SheetsRegistry = __webpack_require__(8);
var _SheetsRegistry2 = _interopRequireDefault(_SheetsRegistry);
var _sheets = __webpack_require__(7);
var _sheets2 = _interopRequireDefault(_sheets);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* SheetsRegistry for SSR.
*/
exports.SheetsRegistry = _SheetsRegistry2['default'];
/**
* Default global SheetsRegistry instance.
*/
/**
* A better abstraction over CSS.
*
* @copyright Oleg Slobodskoi 2014-present
* @website https://github.com/cssinjs/jss
* @license MIT
*/
exports.sheets = _sheets2['default'];
/**
* Creates a new instance of Jss.
*/
var create = exports.create = function create(options) {
return new _Jss2['default'](options);
};
/**
* A global Jss instance.
*/
exports['default'] = create();
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _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; };
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 _StyleSheet = __webpack_require__(2);
var _StyleSheet2 = _interopRequireDefault(_StyleSheet);
var _PluginsRegistry = __webpack_require__(16);
var _PluginsRegistry2 = _interopRequireDefault(_PluginsRegistry);
var _plugins = __webpack_require__(17);
var _plugins2 = _interopRequireDefault(_plugins);
var _sheets = __webpack_require__(7);
var _sheets2 = _interopRequireDefault(_sheets);
var _generateClassName = __webpack_require__(22);
var _generateClassName2 = _interopRequireDefault(_generateClassName);
var _createRule2 = __webpack_require__(11);
var _createRule3 = _interopRequireDefault(_createRule2);
var _findRenderer = __webpack_require__(3);
var _findRenderer2 = _interopRequireDefault(_findRenderer);
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"); } }
var Jss = function () {
function Jss(options) {
_classCallCheck(this, Jss);
this.version = "6.0.1";
this.plugins = new _PluginsRegistry2['default']();
this.use.apply(this, _plugins2['default']); // eslint-disable-line prefer-spread
this.setup(options);
}
_createClass(Jss, [{
key: 'setup',
value: function setup() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.options = _extends({}, options, {
generateClassName: options.generateClassName || _generateClassName2['default']
});
var plugins = this.options.plugins;
if (plugins) this.use.apply(this, plugins); // eslint-disable-line prefer-spread
return this;
}
/**
* Create a Style Sheet.
*/
}, {
key: 'createStyleSheet',
value: function createStyleSheet(styles, options) {
return new _StyleSheet2['default'](styles, _extends({
jss: this,
generateClassName: this.options.generateClassName
}, options));
}
/**
* Detach the Style Sheet and remove it from the registry.
*/
}, {
key: 'removeStyleSheet',
value: function removeStyleSheet(sheet) {
sheet.detach();
_sheets2['default'].remove(sheet);
return this;
}
/**
* Create a rule without a Style Sheet.
*/
}, {
key: 'createRule',
value: function createRule(name) {
var style = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
// Enable rule without name for inline styles.
if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') {
options = style;
style = name;
name = undefined;
}
if (!options.classes) options.classes = {};
if (!options.jss) options.jss = this;
if (!options.Renderer) options.Renderer = (0, _findRenderer2['default'])(options);
if (!options.generateClassName) {
options.generateClassName = this.options.generateClassName || _generateClassName2['default'];
}
var rule = (0, _createRule3['default'])(name, style, options);
this.plugins.onProcessRule(rule);
return rule;
}
/**
* Register plugin. Passed function will be invoked with a rule instance.
*/
}, {
key: 'use',
value: function use() {
var _this = this;
for (var _len = arguments.length, plugins = Array(_len), _key = 0; _key < _len; _key++) {
plugins[_key] = arguments[_key];
}
plugins.forEach(function (plugin) {
return _this.plugins.use(plugin);
});
return this;
}
}]);
return Jss;
}();
exports['default'] = Jss;
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _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; };
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 _findRenderer = __webpack_require__(3);
var _findRenderer2 = _interopRequireDefault(_findRenderer);
var _RulesContainer = __webpack_require__(10);
var _RulesContainer2 = _interopRequireDefault(_RulesContainer);
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"); } }
var StyleSheet = function () {
function StyleSheet(styles, options) {
_classCallCheck(this, StyleSheet);
var Renderer = (0, _findRenderer2['default'])(options);
var index = typeof options.index === 'number' ? options.index : 0;
this.attached = false;
this.deployed = false;
this.linked = false;
this.classes = Object.create(null);
this.options = _extends({
sheet: this,
parent: this,
classes: this.classes,
index: index,
Renderer: Renderer
}, options);
this.renderer = new Renderer(this);
this.renderer.createElement();
this.rules = new _RulesContainer2['default'](this.options);
for (var name in styles) {
this.rules.createAndRegister(name, styles[name]);
}
if (options.jss) {
var plugins = options.jss.plugins;
this.rules.getIndex().forEach(plugins.onProcessRule, plugins);
}
}
/**
* Attach renderable to the render tree.
*/
_createClass(StyleSheet, [{
key: 'attach',
value: function attach() {
if (this.attached) return this;
if (!this.deployed) this.deploy();
this.renderer.attach();
if (!this.linked && this.options.link) this.link();
this.attached = true;
return this;
}
/**
* Remove renderable from render tree.
*/
}, {
key: 'detach',
value: function detach() {
if (!this.attached) return this;
this.renderer.detach();
this.attached = false;
return this;
}
/**
* Add a rule to the current stylesheet.
* Will insert a rule also after the stylesheet has been rendered first time.
*/
}, {
key: 'addRule',
value: function addRule(name, style, options) {
var queue = this.queue;
// Plugins can create rules.
// In order to preserve the right order, we need to queue all `.addRule` calls,
// which happen after the first `rules.create()` call.
if (this.attached && !queue) this.queue = [];
var rule = this.rules.create(name, style, options);
if (this.attached) {
if (!this.deployed) return rule;
// Don't insert rule directly if there is no stringified version yet.
// It will be inserted all together when .attach is called.
if (queue) queue.push(rule);else {
var renderable = this.renderer.insertRule(rule);
if (renderable && this.options.link) rule.renderable = renderable;
if (this.queue) {
this.queue.forEach(this.renderer.insertRule, this.renderer);
this.queue = undefined;
}
}
return rule;
}
// We can't add rules to a detached style node.
// We will redeploy the sheet once user will attach it.
this.deployed = false;
return rule;
}
/**
* Create and add rules.
* Will render also after Style Sheet was rendered the first time.
*/
}, {
key: 'addRules',
value: function addRules(styles, options) {
var added = [];
for (var name in styles) {
added.push(this.addRule(name, styles[name], options));
}
return added;
}
/**
* Get a rule by name.
*/
}, {
key: 'getRule',
value: function getRule(name) {
return this.rules.get(name);
}
/**
* Delete a rule by name.
* Returns `true`: if rule has been deleted from the DOM.
*/
}, {
key: 'deleteRule',
value: function deleteRule(name) {
var rule = this.rules.get(name);
if (!rule) return false;
this.rules.remove(rule);
if (this.attached && rule.renderable) {
return this.renderer.deleteRule(rule.renderable);
}
return true;
}
/**
* Get index of a rule.
*/
}, {
key: 'indexOf',
value: function indexOf(rule) {
return this.rules.indexOf(rule);
}
/**
* Convert rules to a CSS string.
*/
}, {
key: 'toString',
value: function toString(options) {
return this.rules.toString(options);
}
/**
* Deploy pure CSS string to a renderable.
*/
}, {
key: 'deploy',
value: function deploy() {
this.renderer.deploy(this);
this.deployed = true;
return this;
}
/**
* Link renderable CSS rules with their corresponding models.
*/
}, {
key: 'link',
value: function link() {
var cssRules = this.renderer.getRules();
for (var i = 0; i < cssRules.length; i++) {
var CSSStyleRule = cssRules[i];
var rule = this.rules.get(CSSStyleRule.selectorText);
if (rule) rule.renderable = CSSStyleRule;
}
this.linked = true;
return this;
}
}]);
return StyleSheet;
}();
exports['default'] = StyleSheet;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports['default'] = findRenderer;
var _isInBrowser = __webpack_require__(4);
var _isInBrowser2 = _interopRequireDefault(_isInBrowser);
var _DomRenderer = __webpack_require__(5);
var _DomRenderer2 = _interopRequireDefault(_DomRenderer);
var _VirtualRenderer = __webpack_require__(9);
var _VirtualRenderer2 = _interopRequireDefault(_VirtualRenderer);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Find proper renderer.
* Option `virtual` is used to force use of VirtualRenderer even if DOM is
* detected, used for testing only.
*/
function findRenderer() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (options.Renderer) return options.Renderer;
var useVirtual = options.virtual || !_isInBrowser2['default'];
return useVirtual ? _VirtualRenderer2['default'] : _DomRenderer2['default'];
}
/***/ },
/* 4 */
/***/ function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var isBrowser = exports.isBrowser = (typeof window === "undefined" ? "undefined" : _typeof(window)) === "object" && (typeof document === "undefined" ? "undefined" : _typeof(document)) === 'object' && document.nodeType === 9;
exports.default = isBrowser;
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _warning = __webpack_require__(6);
var _warning2 = _interopRequireDefault(_warning);
var _sheets = __webpack_require__(7);
var _sheets2 = _interopRequireDefault(_sheets);
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"); } }
/**
* Get a style property.
*/
function getStyle(rule, prop) {
try {
return rule.style.getPropertyValue(prop);
} catch (err) {
// IE may throw if property is unknown.
return '';
}
}
/**
* Set a style property.
*/
function setStyle(rule, prop, value) {
try {
rule.style.setProperty(prop, value);
} catch (err) {
// IE may throw if property is unknown.
return false;
}
return true;
}
/**
* Get the selector.
*/
function getSelector(rule) {
return rule.selectorText;
}
/**
* Set the selector.
*/
function setSelector(rule, selectorText) {
rule.selectorText = selectorText;
// Return false if setter was not successful.
// Currently works in chrome only.
return rule.selectorText === selectorText;
}
/**
* Find attached sheet with an index higher than the passed one.
*/
function findHigherSheet(registry, index) {
for (var i = 0; i < registry.length; i++) {
var sheet = registry[i];
if (sheet.attached && sheet.options.index > index) {
return sheet;
}
}
return null;
}
/**
* Find attached sheet with the highest index.
*/
function findHighestSheet(registry) {
for (var i = registry.length - 1; i >= 0; i--) {
var sheet = registry[i];
if (sheet.attached) return sheet;
}
return null;
}
/**
* Find a comment with "jss" inside.
*/
function findCommentNode(head) {
for (var i = 0; i < head.childNodes.length; i++) {
var node = head.childNodes[i];
if (node.nodeType === 8 && node.nodeValue.trim() === 'jss') {
return node;
}
}
return null;
}
/**
* Find a node before which we can insert the sheet.
*/
function findPrevNode(head, index) {
var registry = _sheets2['default'].registry;
if (registry.length > 1) {
// Try to insert before the next higher sheet.
var sheet = findHigherSheet(registry, index);
if (sheet) return sheet.renderer.element;
// Otherwise insert after the last attached.
sheet = findHighestSheet(registry);
if (sheet) return sheet.renderer.element.nextElementSibling;
}
// Try find a comment placeholder if registry is empty.
var comment = findCommentNode(head);
if (comment) return comment.nextSibling;
return null;
}
var DomRenderer = function () {
// HTMLStyleElement needs fixing https://github.com/facebook/flow/issues/2696
function DomRenderer(sheet) {
_classCallCheck(this, DomRenderer);
this.getStyle = getStyle;
this.setStyle = setStyle;
this.setSelector = setSelector;
this.getSelector = getSelector;
this.sheet = sheet;
// There is no sheet when the renderer is used from a standalone RegularRule.
if (sheet) _sheets2['default'].add(sheet);
}
/**
* Create and ref style element.
*/
_createClass(DomRenderer, [{
key: 'createElement',
value: function createElement() {
var _ref = this.sheet ? this.sheet.options : {},
media = _ref.media,
meta = _ref.meta,
element = _ref.element;
this.head = document.head || document.getElementsByTagName('head')[0];
this.element = element || document.createElement('style');
this.element.type = 'text/css';
this.element.setAttribute('data-jss', '');
if (media) this.element.setAttribute('media', media);
if (meta) this.element.setAttribute('data-meta', meta);
}
/**
* Insert style element into render tree.
*/
}, {
key: 'attach',
value: function attach() {
// In the case the element node is external and it is already in the DOM.
if (this.element.parentNode || !this.sheet) return;
var prevNode = findPrevNode(this.head, this.sheet.options.index);
this.head.insertBefore(this.element, prevNode);
}
/**
* Remove style element from render tree.
*/
}, {
key: 'detach',
value: function detach() {
this.element.parentNode.removeChild(this.element);
}
/**
* Inject CSS string into element.
*/
}, {
key: 'deploy',
value: function deploy(sheet) {
this.element.textContent = '\n' + sheet.toString() + '\n';
}
/**
* Insert a rule into element.
*/
}, {
key: 'insertRule',
value: function insertRule(rule) {
var sheet = this.element.sheet;
var cssRules = sheet.cssRules;
var index = cssRules.length;
var str = rule.toString();
if (!str) return false;
try {
sheet.insertRule(str, index);
} catch (err) {
(0, _warning2['default'])(false, '[JSS] Can not insert an unsupported rule \n\r%s', rule);
return false;
}
return cssRules[index];
}
/**
* Delete a rule.
*/
}, {
key: 'deleteRule',
value: function deleteRule(rule) {
var sheet = this.element.sheet;
var cssRules = sheet.cssRules;
for (var index = 0; index < cssRules.length; index++) {
if (rule === cssRules[index]) {
sheet.deleteRule(index);
return true;
}
}
return false;
}
/**
* Get all rules elements.
*/
}, {
key: 'getRules',
value: function getRules() {
return this.element.sheet.cssRules;
}
}]);
return DomRenderer;
}();
exports['default'] = DomRenderer;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
/**
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical
* paths. Removing the logging code for production environments will keep the
* same logic and follow the same code paths.
*/
var warning = function() {};
if (true) {
warning = function(condition, format, args) {
var len = arguments.length;
args = new Array(len > 2 ? len - 2 : 0);
for (var key = 2; key < len; key++) {
args[key - 2] = arguments[key];
}
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (format.length < 10 || (/^[s\W]*$/).test(format)) {
throw new Error(
'The warning format should be able to uniquely identify this ' +
'warning. Please, use a more descriptive format than: ' + format
);
}
if (!condition) {
var argIndex = 0;
var message = 'Warning: ' +
format.replace(/%s/g, function() {
return args[argIndex++];
});
if (typeof console !== 'undefined') {
console.error(message);
}
try {
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
throw new Error(message);
} catch(x) {}
}
};
}
module.exports = warning;
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _SheetsRegistry = __webpack_require__(8);
var _SheetsRegistry2 = _interopRequireDefault(_SheetsRegistry);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* This is a global sheets registry. Only DomRenderer will add sheets to it.
* On the server one should use an own SheetsRegistry instance and add the
* sheets to it, because you need to make sure to create a new registry for
* each request in order to not leak sheets across requests.
*/
exports['default'] = new _SheetsRegistry2['default']();
/***/ },
/* 8 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/**
* Sheets registry to access them all at one place.
*/
var SheetsRegistry = function () {
function SheetsRegistry() {
_classCallCheck(this, SheetsRegistry);
this.registry = [];
}
_createClass(SheetsRegistry, [{
key: 'add',
/**
* Register a Style Sheet.
*/
value: function add(sheet) {
var registry = this.registry;
var index = sheet.options.index;
if (!registry.length || index >= registry[registry.length - 1].options.index) {
registry.push(sheet);
return;
}
for (var i = 0; i < registry.length; i++) {
var options = registry[i].options;
if (options.index > index) {
registry.splice(i, 0, sheet);
return;
}
}
}
/**
* Reset the registry.
*/
}, {
key: 'reset',
value: function reset() {
this.registry = [];
}
/**
* Remove a Style Sheet.
*/
}, {
key: 'remove',
value: function remove(sheet) {
var index = this.registry.indexOf(sheet);
this.registry.splice(index, 1);
}
/**
* Convert all attached sheets to a CSS string.
*/
}, {
key: 'toString',
value: function toString(options) {
return this.registry.filter(function (sheet) {
return sheet.attached;
}).map(function (sheet) {
return sheet.toString(options);
}).join('\n');
}
}]);
return SheetsRegistry;
}();
exports['default'] = SheetsRegistry;
/***/ },
/* 9 */
/***/ function(module, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
/* eslint-disable class-methods-use-this */
/**
* Rendering backend to do nothing in nodejs.
*/
var VirtualRenderer = function () {
function VirtualRenderer() {
_classCallCheck(this, VirtualRenderer);
}
_createClass(VirtualRenderer, [{
key: "createElement",
value: function createElement() {}
}, {
key: "setStyle",
value: function setStyle() {}
}, {
key: "getStyle",
value: function getStyle() {}
}, {
key: "setSelector",
value: function setSelector() {}
}, {
key: "getSelector",
value: function getSelector() {}
}, {
key: "attach",
value: function attach() {}
}, {
key: "detach",
value: function detach() {}
}, {
key: "deploy",
value: function deploy() {}
}, {
key: "insertRule",
value: function insertRule() {}
}, {
key: "deleteRule",
value: function deleteRule() {}
}, {
key: "getRules",
value: function getRules() {}
}]);
return VirtualRenderer;
}();
exports["default"] = VirtualRenderer;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _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; };
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 _createRule = __webpack_require__(11);
var _createRule2 = _interopRequireDefault(_createRule);
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"); } }
/**
* Contains rules objects and allows adding/removing etc.
* Is used for e.g. by `StyleSheet` or `ConditionalRule`.
*/
var RulesContainer = function () {
// Rules registry for access by .get() method.
// It contains the same rule registered by name and by selector.
function RulesContainer(options) {
_classCallCheck(this, RulesContainer);
this.map = Object.create(null);
this.index = [];
this.options = options;
this.classes = options.classes;
}
/**
* Create and register rule, run plugins.
*
* Will not render after Style Sheet was rendered the first time.
*/
// Used to ensure correct rules order.
_createClass(RulesContainer, [{
key: 'create',
value: function create(name, style, options) {
var rule = this.createAndRegister(name, style, options);
this.options.jss.plugins.onProcessRule(rule);
return rule;
}
/**
* Get a rule.
*
* @param {String} name
* @return {Rule}
* @api public
*/
}, {
key: 'get',
value: function get(name) {
return this.map[name];
}
/**
* Delete a rule.
*
* @param {Object} rule
* @return {Boolean} true if rule has been deleted from the DOM.
* @api public
*/
}, {
key: 'remove',
value: function remove(rule) {
this.unregister(rule);
this.index.splice(this.indexOf(rule), 1);
}
/**
* Get index of a rule.
*
* @param {Rule} rule
* @return {Number}
* @api public
*/
}, {
key: 'indexOf',
value: function indexOf(rule) {
return this.index.indexOf(rule);
}
/**
* Register a rule in `.map` and `.classes` maps.
*
* @param {Rule} rule
* @api public
*/
}, {
key: 'register',
value: function register(rule) {
if (rule.name) this.map[rule.name] = rule;
if (rule.className && rule.name) this.classes[rule.name] = rule.className;
if (rule.selector) this.map[rule.selector] = rule;
}
/**
* Unregister a rule.
*/
}, {
key: 'unregister',
value: function unregister(rule) {
delete this.map[rule.name];
delete this.map[rule.selector];
delete this.classes[rule.name];
}
/**
* Convert rules to a CSS string.
*/
}, {
key: 'toString',
value: function toString(options) {
var str = '';
for (var index = 0; index < this.index.length; index++) {
var rule = this.index[index];
var css = rule.toString(options);
// No need to render an empty rule.
if (!css) continue;
if (str) str += '\n';
str += css;
}
return str;
}
/**
* Returns a cloned index of rules.
* We need this because if we modify the index somewhere else during a loop
* we end up with very hard-to-track-down side effects.
*/
}, {
key: 'getIndex',
value: function getIndex() {
// We need to clone the array, because while
return this.index.slice(0);
}
/**
* Create and register a rule.
*/
}, {
key: 'createAndRegister',
value: function createAndRegister(name, style, options) {
var _options = this.options,
parent = _options.parent,
sheet = _options.sheet,
jss = _options.jss,
Renderer = _options.Renderer,
generateClassName = _options.generateClassName;
options = _extends({
classes: this.classes,
parent: parent,
sheet: sheet,
jss: jss,
Renderer: Renderer,
generateClassName: generateClassName
}, options);
if (!options.className) options.className = this.classes[name];
var rule = (0, _createRule2['default'])(name, style, options);
this.register(rule);
var index = options.index === undefined ? this.index.length : options.index;
this.index.splice(index, 0, rule);
return rule;
}
}]);
return RulesContainer;
}();
exports['default'] = RulesContainer;
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports['default'] = createRule;
var _warning = __webpack_require__(6);
var _warning2 = _interopRequireDefault(_warning);
var _RegularRule = __webpack_require__(12);
var _RegularRule2 = _interopRequireDefault(_RegularRule);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Create a rule instance.
*/
function createRule(name) {
var decl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var options = arguments[2];
var jss = options.jss;
// Is an at-rule.
if (name && name[0] === '@' && jss) {
var rule = jss.plugins.onCreateRule(name, decl, options);
if (rule) return rule;
(0, _warning2['default'])(false, '[JSS] Unknown rule %s', name);
}
return new _RegularRule2['default'](name, decl, options);
}
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
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 _toCss = __webpack_require__(13);
var _toCss2 = _interopRequireDefault(_toCss);
var _toCssValue = __webpack_require__(14);
var _toCssValue2 = _interopRequireDefault(_toCssValue);
var _findClassNames = __webpack_require__(15);
var _findClassNames2 = _interopRequireDefault(_findClassNames);
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"); } }
var parse = JSON.parse,
stringify = JSON.stringify;
var RegularRule = function () {
/**
* We expect `style` to be a plain object.
* To avoid original style object mutations, we clone it and hash it
* along the way.
* It is also the fastetst way.
* http://jsperf.com/lodash-deepclone-vs-jquery-extend-deep/6
*/
function RegularRule(name, style, options) {
_classCallCheck(this, RegularRule);
this.type = 'regular';
var generateClassName = options.generateClassName,
sheet = options.sheet,
Renderer = options.Renderer;
var styleStr = stringify(style);
this.style = parse(styleStr);
this.name = name;
this.options = options;
this.originalStyle = style;
this.className = '';
if (options.className) this.className = options.className;else if (generateClassName) this.className = generateClassName(styleStr, this);
this.selectorText = options.selector || '.' + this.className;
if (sheet) this.renderer = sheet.renderer;else if (Renderer) this.renderer = new Renderer();
}
/**
* Set selector string.
* Attenition: use this with caution. Most browser didn't implement
* selectorText setter, so this may result in rerendering of entire Style Sheet.
*/
_createClass(RegularRule, [{
key: 'prop',
/**
* Get or set a style property.
*/
value: function prop(name, value) {
// Its a setter.
if (value != null) {
this.style[name] = value;
// Only defined if option linked is true.
if (this.renderable) this.renderer.setStyle(this.renderable, name, value);
return this;
}
// Its a getter, read the value from the DOM if its not cached.
if (this.renderable && this.style[name] == null) {
// Cache the value after we have got it from the DOM once.
this.style[name] = this.renderer.getStyle(this.renderable, name);
}
return this.style[name];
}
/**
* Apply rule to an element inline.
*/
}, {
key: 'applyTo',
value: function applyTo(renderable) {
var json = this.toJSON();
for (var prop in json) {
this.renderer.setStyle(renderable, prop, json[prop]);
}return this;
}
/**
* Returns JSON representation of the rule.
* Fallbacks are not supported.
* Useful as inline style.
*/
}, {
key: 'toJSON',
value: function toJSON() {
var json = Object.create(null);
for (var prop in this.style) {
var value = this.style[prop];
if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) !== 'object') json[prop] = value;else if (Array.isArray(value)) json[prop] = (0, _toCssValue2['default'])(value);
}
return json;
}
/**
* Generates a CSS string.
*/
}, {
key: 'toString',
value: function toString(options) {
return (0, _toCss2['default'])(this.selector, this.style, options);
}
}, {
key: 'selector',
set: function set(selector) {
var sheet = this.options.sheet;
// After we modify a selector, ref by old selector needs to be removed.
if (sheet) sheet.rules.unregister(this);
this.selectorText = selector;
this.className = (0, _findClassNames2['default'])(selector);
if (!this.renderable) {
// Register the rule with new selector.
if (sheet) sheet.rules.register(this);
return;
}
var changed = this.renderer.setSelector(this.renderable, selector);
if (changed && sheet) {
sheet.rules.register(this);
return;
}
// If selector setter is not implemented, rerender the sheet.
// We need to delete renderable from the rule, because when sheet.deploy()
// calls rule.toString, it will get the old selector.
delete this.renderable;
if (sheet) {
sheet.rules.register(this);
sheet.deploy().link();
}
}
/**
* Get selector string.
*/
,
get: function get() {
if (this.renderable) {
var selector = this.renderer.getSelector(this.renderable);
return selector;
}
return this.selectorText;
}
}]);
return RegularRule;
}();
exports['default'] = RegularRule;
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports['default'] = toCss;
var _toCssValue = __webpack_require__(14);
var _toCssValue2 = _interopRequireDefault(_toCssValue);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Indent a string.
* http://jsperf.com/array-join-vs-for
*/
function indentStr(str, indent) {
var result = '';
for (var index = 0; index < indent; index++) {
result += ' ';
}return result + str;
}
/**
* Converts a Rule to CSS string.
*/
function toCss(selector, style) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var _options$indent = options.indent,
indent = _options$indent === undefined ? 0 : _options$indent;
var fallbacks = style.fallbacks;
var result = '';
indent++;
// Apply fallbacks first.
if (fallbacks) {
// Array syntax {fallbacks: [{prop: value}]}
if (Array.isArray(fallbacks)) {
for (var index = 0; index < fallbacks.length; index++) {
var fallback = fallbacks[index];
for (var prop in fallback) {
var value = fallback[prop];
if (value != null) {
result += '\n' + indentStr(prop + ': ' + (0, _toCssValue2['default'])(value) + ';', indent);
}
}
}
}
// Object syntax {fallbacks: {prop: value}}
else {
for (var _prop in fallbacks) {
var _value = fallbacks[_prop];
if (_value != null) {
result += '\n' + indentStr(_prop + ': ' + (0, _toCssValue2['default'])(_value) + ';', indent);
}
}
}
}
for (var _prop2 in style) {
var _value2 = style[_prop2];
if (_value2 != null && _prop2 !== 'fallbacks') {
result += '\n' + indentStr(_prop2 + ': ' + (0, _toCssValue2['default'])(_value2) + ';', indent);
}
}
if (!result) return result;
indent--;
result = indentStr(selector + ' {' + result + '\n', indent) + indentStr('}', indent);
return result;
}
/***/ },
/* 14 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports['default'] = toCssValue;
var joinWithSpace = function joinWithSpace(value) {
return value.join(' ');
};
/**
* Converts array values to string.
*
* `margin: [['5px', '10px']]` > `margin: 5px 10px;`
* `border: ['1px', '2px']` > `border: 1px, 2px;`
*/
function toCssValue(value) {
if (!Array.isArray(value)) return value;
// Support space separated values.
if (Array.isArray(value[0])) {
return toCssValue(value.map(joinWithSpace));
}
return value.join(', ');
}
/***/ },
/* 15 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports['default'] = findClassNames;
var dotsRegExp = /[.]/g;
var classesRegExp = /[.][^ ,]+/g;
/**
* Get class names from a selector.
*/
function findClassNames(selector) {
var classes = selector.match(classesRegExp);
if (!classes) return '';
return classes.join(' ').replace(dotsRegExp, '');
}
/***/ },
/* 16 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var PluginsRegistry = function () {
function PluginsRegistry() {
_classCallCheck(this, PluginsRegistry);
this.registry = [];
}
_createClass(PluginsRegistry, [{
key: 'onCreateRule',
/**
* Call `onCreateRule` hooks and return an object if returned by a hook.
*/
value: function onCreateRule(name, decl, options) {
for (var i = 0; i < this.registry.length; i++) {
var onCreateRule = this.registry[i].onCreateRule;
if (!onCreateRule) continue;
var rule = onCreateRule(name, decl, options);
if (rule) return rule;
}
return null;
}
/**
* Call `onProcessRule` hooks.
*/
}, {
key: 'onProcessRule',
value: function onProcessRule(rule) {
for (var i = 0; i < this.registry.length; i++) {
var onProcessRule = this.registry[i].onProcessRule;
if (onProcessRule) onProcessRule(rule);
}
}
/**
* Register a plugin.
* If function is passed, it is a shortcut for `{onProcessRule}`.
*/
}, {
key: 'use',
value: function use(plugin) {
if (typeof plugin === 'function') {
plugin = { onProcessRule: plugin };
}
this.registry.push(plugin);
}
}]);
return PluginsRegistry;
}();
exports['default'] = PluginsRegistry;
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _SimpleRule = __webpack_require__(18);
var _SimpleRule2 = _interopRequireDefault(_SimpleRule);
var _KeyframeRule = __webpack_require__(19);
var _KeyframeRule2 = _interopRequireDefault(_KeyframeRule);
var _ConditionalRule = __webpack_require__(20);
var _ConditionalRule2 = _interopRequireDefault(_ConditionalRule);
var _FontFaceRule = __webpack_require__(21);
var _FontFaceRule2 = _interopRequireDefault(_FontFaceRule);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var classes = {
'@charset': _SimpleRule2['default'],
'@import': _SimpleRule2['default'],
'@namespace': _SimpleRule2['default'],
'@keyframes': _KeyframeRule2['default'],
'@media': _ConditionalRule2['default'],
'@supports': _ConditionalRule2['default'],
'@font-face': _FontFaceRule2['default']
};
/**
* Generate plugins which will register all rules.
*/
exports['default'] = Object.keys(classes).map(function (key) {
// https://jsperf.com/indexof-vs-substr-vs-regex-at-the-beginning-3
var re = new RegExp('^' + key);
var onCreateRule = function onCreateRule(name, decl, options) {
return re.test(name) ? new classes[key](name, decl, options) : null;
};
return { onCreateRule: onCreateRule };
});
/***/ },
/* 18 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var SimpleRule = function () {
function SimpleRule(name, value, options) {
_classCallCheck(this, SimpleRule);
this.type = 'simple';
this.name = name;
this.value = value;
this.options = options;
}
/**
* Generates a CSS string.
*/
_createClass(SimpleRule, [{
key: 'toString',
value: function toString() {
if (Array.isArray(this.value)) {
var str = '';
for (var index = 0; index < this.value.length; index++) {
str += this.name + ' ' + this.value[index] + ';';
if (this.value[index + 1]) str += '\n';
}
return str;
}
return this.name + ' ' + this.value + ';';
}
}]);
return SimpleRule;
}();
exports['default'] = SimpleRule;
/***/ },
/* 19 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _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; };
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 _createRule = __webpack_require__(11);
var _createRule2 = _interopRequireDefault(_createRule);
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"); } }
var toCssOptions = { indent: 1 };
var KeyframeRule = function () {
function KeyframeRule(selector, frames, options) {
_classCallCheck(this, KeyframeRule);
this.type = 'keyframe';
this.selector = selector;
this.options = options;
this.frames = this.formatFrames(frames);
}
/**
* Creates formatted frames where every frame value is a rule instance.
*/
_createClass(KeyframeRule, [{
key: 'formatFrames',
value: function formatFrames(frames) {
var newFrames = Object.create(null);
for (var name in frames) {
var options = _extends({}, this.options, {
parent: this,
className: name,
selector: name
});
var rule = (0, _createRule2['default'])(name, frames[name], options);
options.jss.plugins.onProcessRule(rule);
newFrames[name] = rule;
}
return newFrames;
}
/**
* Generates a CSS string.
*/
}, {
key: 'toString',
value: function toString() {
var str = this.selector + ' {\n';
for (var name in this.frames) {
str += this.frames[name].toString(toCssOptions) + '\n';
}
str += '}';
return str;
}
}]);
return KeyframeRule;
}();
exports['default'] = KeyframeRule;
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _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; };
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 _RulesContainer = __webpack_require__(10);
var _RulesContainer2 = _interopRequireDefault(_RulesContainer);
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"); } }
/**
* Conditional rule for @media, @supports
*/
var ConditionalRule = function () {
function ConditionalRule(selector, styles, options) {
_classCallCheck(this, ConditionalRule);
this.type = 'conditional';
this.selector = selector;
this.options = options;
this.rules = new _RulesContainer2['default'](_extends({}, options, { parent: this }));
for (var name in styles) {
this.createAndRegisterRule(name, styles[name]);
}
if (options.jss) {
var plugins = options.jss.plugins;
this.rules.getIndex().forEach(plugins.onProcessRule, plugins);
}
}
/**
* Get a rule.
*/
_createClass(ConditionalRule, [{
key: 'getRule',
value: function getRule(name) {
return this.rules.get(name);
}
/**
* Get index of a rule.
*/
}, {
key: 'indexOf',
value: function indexOf(rule) {
return this.rules.indexOf(rule);
}
/**
* Create and register rule, run plugins.
*
* Will not render after Style Sheet was rendered the first time.
* Will link the rule in `this.rules`.
*/
}, {
key: 'addRule',
value: function addRule(name, style, options) {
return this.rules.create(name, style, this.getChildOptions(options));
}
/**
* Build options object for a child rule.
*/
}, {
key: 'getChildOptions',
value: function getChildOptions(options) {
return _extends({}, this.options, { parent: this }, options);
}
/**
* Create and register a rule.
*/
}, {
key: 'createAndRegisterRule',
value: function createAndRegisterRule(name, style) {
return this.rules.createAndRegister(name, style, this.getChildOptions());
}
/**
* Generates a CSS string.
*/
}, {
key: 'toString',
value: function toString() {
var inner = this.rules.toString({ indent: 1 });
if (!inner) return '';
return this.selector + ' {\n' + inner + '\n}';
}
}]);
return ConditionalRule;
}();
exports['default'] = ConditionalRule;
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _toCss = __webpack_require__(13);
var _toCss2 = _interopRequireDefault(_toCss);
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"); } }
var FontFaceRule = function () {
function FontFaceRule(selector, style, options) {
_classCallCheck(this, FontFaceRule);
this.type = 'font-face';
this.selector = selector;
this.style = style;
this.options = options;
}
/**
* Generates a CSS string.
*/
_createClass(FontFaceRule, [{
key: 'toString',
value: function toString() {
if (Array.isArray(this.style)) {
var str = '';
for (var index = 0; index < this.style.length; index++) {
str += (0, _toCss2['default'])(this.selector, this.style[index]);
if (this.style[index + 1]) str += '\n';
}
return str;
}
return (0, _toCss2['default'])(this.selector, this.style);
}
}]);
return FontFaceRule;
}();
exports['default'] = FontFaceRule;
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports['default'] = generateClassName;
var _murmurhash3_gc = __webpack_require__(23);
var _murmurhash3_gc2 = _interopRequireDefault(_murmurhash3_gc);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
/**
* Generates a class name using murmurhash.
*/
function generateClassName(str, rule) {
var hash = (0, _murmurhash3_gc2['default'])(str);
// There is no name if `jss.createRule(style)` was used.
return rule.name ? rule.name + '-' + hash : hash;
}
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
/**
* JS Implementation of MurmurHash3 (r136) (as of May 20, 2011)
*
* @author <a href="mailto:[email protected]">Gary Court</a>
* @see http://github.com/garycourt/murmurhash-js
* @author <a href="mailto:[email protected]">Austin Appleby</a>
* @see http://sites.google.com/site/murmurhash/
*
* @param {string} key ASCII only
* @param {number} seed Positive integer only
* @return {number} 32-bit positive integer hash
*/
function murmurhash3_32_gc(key, seed) {
var remainder, bytes, h1, h1b, c1, c1b, c2, c2b, k1, i;
remainder = key.length & 3; // key.length % 4
bytes = key.length - remainder;
h1 = seed;
c1 = 0xcc9e2d51;
c2 = 0x1b873593;
i = 0;
while (i < bytes) {
k1 =
((key.charCodeAt(i) & 0xff)) |
((key.charCodeAt(++i) & 0xff) << 8) |
((key.charCodeAt(++i) & 0xff) << 16) |
((key.charCodeAt(++i) & 0xff) << 24);
++i;
k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff;
h1 ^= k1;
h1 = (h1 << 13) | (h1 >>> 19);
h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff;
h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16));
}
k1 = 0;
switch (remainder) {
case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
case 1: k1 ^= (key.charCodeAt(i) & 0xff);
k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;
k1 = (k1 << 15) | (k1 >>> 17);
k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;
h1 ^= k1;
}
h1 ^= key.length;
h1 ^= h1 >>> 16;
h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;
h1 ^= h1 >>> 13;
h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff;
h1 ^= h1 >>> 16;
return h1 >>> 0;
}
if(true) {
module.exports = murmurhash3_32_gc
}
/***/ }
/******/ ])
});
;
//# sourceMappingURL=jss.js.map | Piicksarn/cdnjs | ajax/libs/jss/6.0.1/jss.js | JavaScript | mit | 62,302 |
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var ballImage;
var ballRadius;
function drawBallInit(diameter) {
ballRadius = diameter / 2;
ballImage = document.getElementById('ballImage');
}
function drawBall(x, y, angle) {
canvasContext.save();
canvasContext.shadowColor = 'black';
canvasContext.shadowOffsetX = -ballRadius;
canvasContext.shadowOffsetY = ballRadius;
canvasContext.shadowBlur = ballRadius;
canvasContext.translate(x, y);
canvasContext.rotate(angle);
canvasContext.drawImage(ballImage, -ballRadius, -ballRadius, ballDiameter,
ballDiameter);
canvasContext.restore();
}
| nwjs/chromium.src | tools/perf/page_sets/tough_canvas_cases/canvas2d_balls_common/bouncing_balls_draw_ball_as_image_with_shadow.js | JavaScript | bsd-3-clause | 733 |
'use strict';
var undefsafe = require('undefsafe');
var config = require('../config');
var stripeKey = undefsafe(config, 'payment.stripe.public');
var models = require('../models');
var metrics = require('../metrics');
var customer = models.customer;
var vatValidator = require('validate-vat');
var features = require('../features');
var featureList = require('../data/features.json');
var backersList = require('../data/backers.json');
var Promise = require('promise'); // jshint ignore:line
var util = require('util');
var stripeUtils = require('../stripe/utils');
var _ = require('underscore');
var debug = require('debug')('jsbin:upgrade');
// PROMISE ALL THE THINGS! \o/
var getCustomerByUser = Promise.denodeify(customer.getCustomerByUser).bind(customer);
var setCustomer = Promise.denodeify(customer.setCustomer).bind(customer);
var setProAccount = Promise.denodeify(models.user.setProAccount).bind(models.user);
var stripe;
// var debug = config.environment !== 'production';
if (stripeKey) {
stripe = require('stripe')(undefsafe(config, 'payment.stripe.secret'));
}
// this is a compatibility layer for our handler index.js magic
var upgrade = module.exports = {
name: 'upgrade',
};
upgrade.admin = {};
upgrade.subscription = function (req, res, next) {
if (!stripeKey) {
return next('route');
}
metrics.increment('upgrade.view.subscription');
var app = req.app;
getCustomerByUser(req.session.user).then(function (results) {
var result = results[0];
return stripe.invoices.list({
limit: 100,
customer: result.stripe_id // jshint ignore:line
}).then(function (invoices) {
return stripe.customers.listSubscriptions(result.stripe_id).then(function (subscriptions) { // jshint ignore:line
return {
invoices: invoices.data,
subscriptions: subscriptions
};
});
});
}).then(function (results) {
var data = results.subscriptions.data;
if (data && Array.isArray(data) && data.length) {
return results;
} else {
throw new Error('customer loaded, stripe customer loaded, but no stripe data found');
}
}).then(function (results) {
var data = results.subscriptions.data;
results.subscriptions.data = data.map(function (data) {
if (data.plan.id.indexOf('vat') !== -1) {
data.plan.vat = data.plan.amount - (data.plan.amount / 6);
}
return data;
});
return results;
}).then(function (data) {
// render the view
res.render('account/subscription', {
title: 'Your subscription',
layout: 'sub/layout.html',
root: app.locals.url('', true, req.secure),
static: app.locals.urlForStatic('', req.secure),
request: req,
subscription: data.subscriptions.data[0], //only send the first
invoices: data.invoices,
csrf: req.session._csrf,
username: req.session.user.name,
});
}).catch(function (error) {
// single catch for all error types
console.error(error.stack);
req.flash(req.flash.ERROR, 'Your customer records could not be loaded. If you believe this is an error please contact <a href="mailto:[email protected]?subject=Failed VAT">support</a>.');
next('route');
});
};
upgrade.invoice = function (req, res) {
getCustomerByUser(req.session.user).then(function (results) {
var invoice_id = req.params.invoice; // jshint ignore:line
return stripe.invoices.retrieve(invoice_id).then(function (invoice) { // jshint ignore:line
if (invoice.customer !== results[0].stripe_id) { // jshint ignore:line
throw 'Unauthorized';
}
return invoice;
});
}).then(function (invoice) {
res.render('invoice', {
invoice: invoice
});
}).catch(function (err) {
console.log(err.stack);
req.flash(req.flash.ERROR, 'Unauthorised request to url');
res.redirect('/login');
});
};
upgrade.cancel = function (req, res, next) {
return getCustomerByUser(req.session.user).then(function (results) {
var result = results[0];
debug('.then, stripe.customers.retrieve(' + result.stripe_id + ')'); // jshint ignore:line
return stripe.customers.cancelSubscription(result.stripe_id, req.body.subscription, { at_period_end: true });// jshint ignore:line
}).then(function () {
req.flash(req.flash.ERROR, 'Your Pro subscription has been cancelled, and your Pro status will be removed at the end of your billing period. We miss you already...');
if (next) {
next();
}
}).catch(function (error) {
console.error(error.stack);
if (next) {
return next(error);
} else {
res.send(500);
}
});
};
upgrade.features = function (req, res, next) {
if (!stripeKey) {
return next('route');
}
metrics.increment('upgrade.view.features');
var app = req.app;
var stripeProMonthURL = undefsafe(config, 'payment.stripe.urls.month');
res.render('features', {
title: 'Pro features',
layout: 'sub/layout.html',
root: app.locals.url('', true, req.secure),
static: app.locals.urlForStatic('', req.secure),
referrer: req.get('referer'),
featureList: featureList.features,
tweets: _.shuffle(featureList.tweets).slice(0, 3),
backersList: backersList,
stripeKey: stripeKey,
stripeProMonthURL: stripeProMonthURL,
description: 'JS Bin Pro Accounts: Pro accounts keep JS Bin 100% free for education, and give you dropbox sync, private bins, vanity urls, asset uploading and supports JS Bin\'s continued operation'
});
};
upgrade.payment = function (req, res, next) {
if (!stripeKey) {
return next('route');
}
if (!req.body.email) {
metrics.increment('upgrade.view.pay');
} else {
metrics.increment('upgrade.view.pay.try-again');
}
var app = req.app;
var user = undefsafe(req, 'session.user') || {};
var info = req.flash(req.flash.INFO);
var error = req.flash(req.flash.ERROR);
var notification = req.flash(req.flash.NOTIFICATION);
var flash = error || notification || info;
if (req.query.coupon && req.query.coupon !== 'true') {
req.body.coupon = req.query.coupon;
}
var upgradeWithFeatures = features('upgradeWithFeatures', req);
res.render(upgradeWithFeatures ? 'upgrade' : 'payment', {
title: 'Upgrade to Pro',
featureList: upgradeWithFeatures ? featureList.features.slice(0) : featureList.features,
user: req.session.user,
flash: flash,
request: req,
layout: 'sub/layout.html',
root: app.locals.url('', true, req.secure),
static: app.locals.urlForStatic('', req.secure),
referrer: req.get('referer'),
csrf: req.session._csrf,
tweets: _.shuffle(featureList.tweets).slice(0, 4),
values: {
email: req.body.email || user.email,
vat: req.body.vat,
country: req.body.country,
subscription: req.body.subscription,
number: req.body.number,
expiry: req.body.expiry,
cvc: req.body.cvc,
coupon: req.body.coupon,
buyer_type: req.body.buyer_type, // jshint ignore:line
},
stripe: {
key: stripeKey,
},
showCoupon: req.query.coupon === 'true' || undefsafe(req, 'body.coupon'),
description: 'JS Bin Pro Accounts: Pro accounts keep JS Bin 100% free for education, and give you dropbox sync, private bins, vanity urls, asset uploading and supports JS Bin\'s continued operation'
});
};
upgrade.processPayment = function (req, res, next) {
if (!stripeKey) {
return next('route');
}
var plans = undefsafe(config, 'payment.stripe.plans');
if (!plans) {
return next(412, 'Missing stripe plans'); // 412: precondition failed
}
if (req.error) {
return upgrade.payment(req, res, next);
}
var metadata = {
type: req.body.buyer_type || 'individual', // jshint ignore:line
country: req.body.country,
vat: req.body.vat,
username: req.session.user.name,
id: req.session.user.id,
ip: req.ip,
};
// get the credit card details submitted by the form
var stripSubscriptionData = {
email: req.body.email,
card: req.body.stripeToken,
metadata: metadata,
};
// if the user doesn't have an email address (likely they came from github)
// then let's update it now
if (!req.session.user.email) {
models.user.updateOwnershipData(req.session.user.name, {
email: req.body.email,
}, function () {
req.session.user.email = req.body.email;
req.session.user.avatar = req.app.locals.gravatar(req.session.user);
});
}
if (req.body.coupon) {
stripSubscriptionData.coupon = req.body.coupon;
}
function getPlan() {
var yearly = req.body.subscription === 'yearly';
var planOptions = yearly ? plans.yearly : plans.monthly;
return planOptions.simple;
}
function createVATInvoiceItem(stripeCustomer, plan, country) {
return stripeUtils.getVATByCountry(country).then(function (VAT) {
debug('stripe.invoiceItems.create');
return stripe.invoiceItems.create({
customer: stripeCustomer.id,
amount: Math.round(parseInt(plan.amount, 10) * VAT),
currency: 'gbp',
description: 'VAT @ ' + (VAT * 100 | 0) + '%',
});
});
}
new Promise(function (resolve) {
if (req.body.vat) {
// check country against the country against the card - it should match
// if it fails, we swallow and respond
var country = (req.body.country || '').toUpperCase();
var vat = (req.body.vat || '').replace(/\s/g, '');
vatValidator(country, vat, function (error, result) {
// important: this is where we are swallowing the promise, and not
// carrying on
if (error || result.valid === false) {
metrics.increment('upgrade.fail.vat');
req.flash(req.flash.ERROR, 'VAT did not appear to be valid, can ' +
'you try again or follow up with <a ' +
'href="mailto:[email protected]?subject=Failed VAT">support</a>.');
// this does NOT return a promise - this is on purpose
return upgrade.payment(req, res, next);
}
req.vatValid = true;
resolve();
});
} else {
// passthrough
resolve();
}
}).then(function () {
// 1. create (or get) customer
// 2. update customer with card and details
// 3. subscribe to plan (and adjust their VAT based on the country of
// the card BEFORE THE SUBSCRIPTION)
/** 1. get a stripe customer id */
debug('getCustomerByUser');
// getCustomerByUser will throw if it doesn't find the user - which leads us
// to creating the new stripe user
return getCustomerByUser(req.session.user).then(function (results) {
var result = results[0];
debug('.then, stripe.customers.retrieve(%s)', result.stripe_id); // jshint ignore:line
return stripe.customers.retrieve(result.stripe_id).catch(function (err) {
// failed to subscribe existing user to stripe
metrics.increment('upgrade.fail.existing-user-change-subscription');
console.error('upgrade.fail.existing-user-change-subscription');
console.error(err.stack);
});
}).catch(function () {
debug('catch: stripe.customers.create(%s)', JSON.stringify(stripSubscriptionData));
// create the customer with Stripe since they don't exist
return stripe.customers.create(stripSubscriptionData).then(function (stripeCustomer) {
debug('setCustomer & return stripeCustomer');
return setCustomer({
stripeId: stripeCustomer.id,
user: req.session.user.name,
plan: getPlan(stripeCustomer),
}).then(function () {
return stripeCustomer;
});
});
}).then(function (stripeCustomer) {
// handle VAT item if required
var country = stripeUtils.getCountry(stripeCustomer);
debug('Test VAT is required for %s', country);
// if the card holder is not in the EU, then skip the VAT checking logic
// and create the subscription
if (stripeUtils.countryIsInEU(country) === false) {
return stripeCustomer;
}
var plan = getPlan(stripeCustomer);
var businessVAT = stripeCustomer.metadata.vat;
debug('stripe.plans.retrieve(%s)', plan, businessVAT);
return stripe.plans.retrieve(plan).then(function (plan) {
// note: plan from stripe.plans.retrieve has all the metadata, like
// the actual price of the plan - which we need to apply the right VAT
if (businessVAT) {
debug('business registered');
return new Promise(function (resolve, reject) {
vatValidator(country, businessVAT, function (err, result) {
debug('vatValidator(%s, %s)', country, businessVAT, err, result);
if (err) {
return reject(err);
}
// if VAT is valid, then there's no VAT applied, and return
// the customer
if (result.valid) {
resolve(stripeCustomer);
} else {
// otherwise apply VAT
resolve(createVATInvoiceItem(stripeCustomer, plan, country));
}
});
});
} else {
debug('applying VAT');
return createVATInvoiceItem(stripeCustomer, plan, country);
}
}).then(function () {
// ensure to end on returning the customer
return stripeCustomer;
});
}).then(function (stripeCustomer) {
// if the customer already had a subscription, then let's update their
// subscription to the new one (this is a super edge case as we don't
// support doing this in the first place)
if (undefsafe(stripeCustomer, 'subscriptions.data.length')) {
debug('stripe.customers.updateSubscription');
return stripe.customers.updateSubscription(
stripeCustomer.id,
stripeCustomer.subscriptions.data[0].id,
{ plan: getPlan(stripeCustomer) }
);
} else {
debug('stripe.customers.createSubscription');
return stripe.customers.createSubscription(
stripeCustomer.id,
{ plan: getPlan(stripeCustomer) }
);
}
}).then(function (data) {
debug('setProAccount(%s, true)', req.session.user.name);
debug(util.inspect(data, { depth: 50 }));
debug('stripe all done - now setting user to pro!');
return setProAccount(req.session.user.name, true);
}).then(function () {
metrics.increment('upgrade.success');
req.session.user.pro = true;
var analytics = 'window._gaq && _gaq.push(["_trackEvent", "upgrade", "' + req.body.subscription + '"';
if (req.body.coupon) {
analytics += ',"coupon", "' + req.body.coupon + '"';
}
analytics += ']);';
req.flash(req.flash.NOTIFICATION, 'Welcome to the pro user lounge. Your seat is waiting. In the mean time, <a target="_blank" href="http://jsbin.com/help/pro">find out more about Pro accounts</a><script>' + analytics + '</script>');
res.redirect('/');
}).catch(function (error) {
// there was something wrong with the customer create process, so let's
// send them back to the payment page with a flash message
console.log(error.stack);
var message = 'Unknown error in the upgrade process. Please try again or contact support';
if (error && error.message) {
message = error.message;
} else if (error) {
message = error.toString();
}
if (error.type) {
metrics.increment('upgrade.fail.' + error.type);
} else {
metrics.increment('upgrade.fail.transaction-misc');
}
req.flash(req.flash.ERROR, message);
upgrade.payment(req, res, next);
});
}).catch(function (error) {
// this is likely to be an exception in our code. 
console.error('uncaught exception in upgrade');
console.log(error.stack);
metrics.increment('upgrade.fail.exception-in-code');
var message = 'Unknown error in the upgrade process. Please try again or contact support';
if (error && error.message) {
message = error.message;
} else if (error) {
message = error.toString();
}
req.flash(req.flash.ERROR, 'Exception in upgrade process: ' + message);
upgrade.payment(req, res, next);
});
};
| mlucool/jsbin | lib/handlers/upgrade.js | JavaScript | mit | 16,339 |
odoo.define('web.kanban_benchmarks', function (require) {
"use strict";
var KanbanView = require('web.KanbanView');
var testUtils = require('web.test_utils');
var createView = testUtils.createView;
QUnit.module('Kanban View', {
beforeEach: function () {
this.data = {
foo: {
fields: {
foo: {string: "Foo", type: "char"},
bar: {string: "Bar", type: "boolean"},
int_field: {string: "int_field", type: "integer", sortable: true},
qux: {string: "my float", type: "float"},
},
records: [
{ id: 1, bar: true, foo: "yop", int_field: 10, qux: 0.4},
{id: 2, bar: true, foo: "blip", int_field: 9, qux: 13},
]
},
};
this.arch = null;
this.run = function (assert, done) {
var data = this.data;
var arch = this.arch;
new Benchmark.Suite({})
.add('kanban', function () {
var kanban = createView({
View: KanbanView,
model: 'foo',
data: data,
arch: arch,
});
kanban.destroy();
})
.on('cycle', function(event) {
assert.ok(true, String(event.target));
})
.on('complete', done)
.run({ 'async': true });
};
}
}, function () {
QUnit.test('simple kanban view with 2 records', function (assert) {
var done = assert.async();
assert.expect(1);
this.arch = '<kanban class="o_kanban_test"><templates><t t-name="kanban-box">' +
'<div>' +
'<t t-esc="record.foo.value"/>' +
'<field name="foo"/>' +
'</div>' +
'</t></templates></kanban>';
this.run(assert, done);
});
QUnit.test('simple kanban view with 200 records', function (assert) {
var done = assert.async();
assert.expect(1);
for (var i = 2; i < 200; i++) {
this.data.foo.records.push({
id: i,
foo: "automated data" + i,
});
}
this.arch = '<kanban class="o_kanban_test"><templates><t t-name="kanban-box">' +
'<div>' +
'<t t-esc="record.foo.value"/>' +
'<field name="foo"/>' +
'</div>' +
'</t></templates></kanban>';
this.run(assert, done);
});
});
});
| Aravinthu/odoo | addons/web/static/tests/views/kanban_benchmarks.js | JavaScript | agpl-3.0 | 2,655 |
/*
Copyright (c) 2014, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License.
See the accompanying LICENSE file for terms.
*/
(function (root, factory) {
'use strict';
var Intl = root.Intl || root.IntlPolyfill,
MessageFormat = factory(Intl);
// register in -all- the module systems (at once)
if (typeof define === 'function' && define.amd) {
define(MessageFormat);
}
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = MessageFormat;
}
if (root) {
root.IntlMessageFormat = MessageFormat;
}
})(typeof global !== 'undefined' ? global : this, function (Intl) {
'use strict';
if (!Intl) {
throw new ReferenceError ('Intl must be available');
}
// -- ES5 Built-ins --------------------------------------------------------
// Purposely using the same implementation as the Intl.js `Intl` polyfill.
// Copyright 2013 Andy Earnshaw, MIT License
// Used for proto-less objects which won't have this method.
var hop = Object.prototype.hasOwnProperty;
var realDefineProp = (function () {
try { return !!Object.defineProperty({}, 'a', {}); }
catch (e) { return false; }
})();
var es3 = !realDefineProp && !Object.prototype.__defineGetter__;
var defineProperty = realDefineProp ? Object.defineProperty :
function (obj, name, desc) {
if ('get' in desc && obj.__defineGetter__) {
obj.__defineGetter__(name, desc.get);
} else if (!hop.call(obj, name) || 'value' in desc) {
obj[name] = desc.value;
}
};
var objCreate = Object.create || function (proto, props) {
var obj, k;
function F() {}
F.prototype = proto;
obj = new F();
for (k in props) {
if (hop.call(props, k)) {
defineProperty(obj, k, props[k]);
}
}
return obj;
};
var fnBind = Function.prototype.bind || function (thisObj) {
var fn = this,
args = [].slice.call(arguments, 1);
return function () {
fn.apply(thisObj, args.concat([].slice.call(arguments)));
};
};
// -- MessageFormat --------------------------------------------------------
function MessageFormat(pattern, locales, formats) {
// Parse string messages into a tokenized JSON structure for traversal.
if (typeof pattern === 'string') {
pattern = MessageFormat.__parse(pattern);
}
if (!(pattern && typeof pattern.length === 'number')) {
throw new TypeError('A pattern must be provided as a String or Array.');
}
// Creates a new object with the specified `formats` merged with the
// default formats.
formats = this._mergeFormats(MessageFormat.FORMATS, formats);
// Defined first because it's used to build the format pattern.
defineProperty(this, '_locale', {value: this._resolveLocale(locales)});
// Define the `pattern` property, a compiled pattern that is highly
// optimized for repeated `format()` invocations. **Note:** This passes
// the `locales` set provided to the constructor instead of just the
// resolved locale.
pattern = this._compilePattern(pattern, locales, formats);
defineProperty(this, '_pattern', {value: pattern});
// Bind `format()` method to `this` so it can be passed by reference
// like the other `Intl` APIs.
this.format = fnBind.call(this.format, this);
}
// Default format options used as the prototype of the `formats` provided to
// the constructor. These are used when constructing the internal
// Intl.NumberFormat and Intl.DateTimeFormat instances.
defineProperty(MessageFormat, 'FORMATS', {
enumerable: true,
value: {
number: {
'currency': {
style: 'currency'
},
'percent': {
style: 'percent'
}
},
date: {
'short': {
month: 'numeric',
day : 'numeric',
year : '2-digit'
},
'medium': {
month: 'short',
day : 'numeric',
year : 'numeric'
},
'long': {
month: 'long',
day : 'numeric',
year : 'numeric'
},
'full': {
weekday: 'long',
month : 'long',
day : 'numeric',
year : 'numeric'
}
},
time: {
'short': {
hour : 'numeric',
minute: 'numeric'
},
'medium': {
hour : 'numeric',
minute: 'numeric',
second: 'numeric'
},
'long': {
hour : 'numeric',
minute : 'numeric',
second : 'numeric',
timeZoneName: 'short'
},
'full': {
hour : 'numeric',
minute : 'numeric',
second : 'numeric',
timeZoneName: 'short'
}
}
}
});
// Define internal private properties for dealing with locale data.
defineProperty(MessageFormat, '__availableLocales__', {value: []});
defineProperty(MessageFormat, '__localeData__', {value: objCreate(null)});
defineProperty(MessageFormat, '__addLocaleData', {value: function (data) {
if (!(data && data.locale)) {
throw new Error('Object passed does not identify itself with a valid language tag');
}
if (!data.messageformat) {
throw new Error('Object passed does not contain locale data for IntlMessageFormat');
}
var availableLocales = MessageFormat.__availableLocales__,
localeData = MessageFormat.__localeData__;
// Message format locale data only requires the first part of the tag.
var locale = data.locale.toLowerCase().split('-')[0];
availableLocales.push(locale);
localeData[locale] = data.messageformat;
if (MessageFormat.defaultLocale === undefined) {
MessageFormat.defaultLocale = locale;
}
}});
// Defines `__parse()` static method as an exposed private.
defineProperty(MessageFormat, '__parse', {value: parse});
// Define public `defaultLocale` property which is set when the first bundle
// of locale data is added.
defineProperty(MessageFormat, 'defaultLocale', {
enumerable: true,
writable : true
});
MessageFormat.prototype.format = function (values) {
return this._format(this._pattern, values);
};
MessageFormat.prototype.resolvedOptions = function () {
// TODO: Provide anything else?
return {
locale: this._locale
};
};
MessageFormat.prototype._compilePattern = function (pattern, locales, formats) {
// Wrap string patterns with an array for iteration control flow.
if (typeof pattern === 'string') {
pattern = [pattern];
}
var locale = this._locale,
localeData = MessageFormat.__localeData__,
formatPattern = [],
i, len, part, type, valueName, format, pluralFunction, options,
key, optionsParts, option;
for (i = 0, len = pattern.length; i < len; i += 1) {
part = pattern[i];
// Checks if string part is a simple string, or if it has a
// tokenized place-holder that needs to be substituted.
if (typeof part === 'string') {
formatPattern.push(createStringPart(part));
continue;
}
type = part.type;
valueName = part.valueName;
options = part.options;
// Handles plural and select parts' options by building format
// patterns for each option.
if (options) {
optionsParts = {};
for (key in options) {
if (!hop.call(options, key)) { continue; }
option = options[key];
// Early exit and special handling for plural options with a
// "${#}" token. These options will have this token replaced
// with NumberFormat wrap with optional prefix and suffix.
if (type === 'plural' && typeof option === 'string' &&
option.indexOf('${#}') >= 0) {
option = option.match(/(.*)\${#}(.*)/);
optionsParts[key] = [
option[1], // prefix
{
valueName: valueName,
format : new Intl.NumberFormat(locales).format
},
option[2] // suffix
];
continue;
}
// Recursively compiles a format pattern for the option.
optionsParts[key] = this._compilePattern(option,
locales, formats);
}
}
// Create a specialized format part for each type. This creates a
// common interface for the `format()` method and encapsulates the
// relevant data need for each type of formatting.
switch (type) {
case 'date':
format = formats.date[part.format];
formatPattern.push({
valueName: valueName,
format : new Intl.DateTimeFormat(locales, format).format
});
break;
case 'time':
format = formats.time[part.format];
formatPattern.push({
valueName: valueName,
format : new Intl.DateTimeFormat(locales, format).format
});
break;
case 'number':
format = formats.number[part.format];
formatPattern.push({
valueName: valueName,
format : new Intl.NumberFormat(locales, format).format
});
break;
case 'plural':
pluralFunction = localeData[locale].pluralFunction;
formatPattern.push(new PluralPart(valueName, optionsParts,
pluralFunction));
break;
case 'select':
formatPattern.push(new SelectPart(valueName, optionsParts));
break;
default:
throw new Error('Message pattern part at index ' + i + ' does not have a valid type');
}
}
return formatPattern;
};
MessageFormat.prototype._format = function (pattern, values) {
var result = '',
i, len, part, valueName, value, options;
for (i = 0, len = pattern.length; i < len; i += 1) {
part = pattern[i];
// Exist early for string parts.
if (typeof part === 'string') {
result += part;
continue;
}
valueName = part.valueName;
// Enforce that all required values are provided by the caller.
if (!(values && hop.call(values, valueName))) {
throw new Error('A value must be provided for: ' + valueName);
}
value = values[valueName];
options = part.options;
// Recursively format plural and select parts' option — which can be
// a nested pattern structure. The choosing of the option to use is
// abstracted-by and delegated-to the part helper object.
if (options) {
result += this._format(part.getOption(value), values);
} else {
result += part.format(value);
}
}
return result;
};
MessageFormat.prototype._mergeFormats = function (defaults, formats) {
var mergedFormats = {},
type, mergedType;
for (type in defaults) {
if (!hop.call(defaults, type)) { continue; }
mergedFormats[type] = mergedType = objCreate(defaults[type]);
if (formats && hop.call(formats, type)) {
extend(mergedType, formats[type]);
}
}
return mergedFormats;
};
MessageFormat.prototype._resolveLocale = function (locales) {
var availableLocales = MessageFormat.__availableLocales__,
locale, parts, i, len;
if (availableLocales.length === 0) {
throw new Error('No locale data has been provided for IntlMessageFormat yet');
}
if (typeof locales === 'string') {
locales = [locales];
}
if (locales && locales.length) {
for (i = 0, len = locales.length; i < len; i += 1) {
locale = locales[i].toLowerCase().split('-')[0];
// Make sure the first part of the locale that we care about is
// structurally valid.
if (!/[a-z]{2,3}/i.test(locale)) {
throw new RangeError('"' + locales[i] + '" is not a structurally valid language tag');
}
if (availableLocales.indexOf(locale) >= 0) {
break;
}
}
}
return locale || MessageFormat.defaultLocale;
};
// -- MessageFormat Helpers ------------------------------------------------
var RE_PARSED_TOKEN = /^\${([-\w]+)}$/;
function createStringPart(str) {
var token = str.match(RE_PARSED_TOKEN);
return token ? new StringPart(token[1]) : str;
}
function StringPart(valueName) {
this.valueName = valueName;
}
StringPart.prototype.format = function (value) {
if (!value) {
return '';
}
return typeof value === 'string' ? value : String(value);
};
function SelectPart(valueName, options) {
this.valueName = valueName;
this.options = options;
}
SelectPart.prototype.getOption = function (value) {
var options = this.options;
return options[value] || options.other;
};
function PluralPart(valueName, options, pluralFunction) {
this.valueName = valueName;
this.options = options;
this.pluralFunction = pluralFunction;
}
PluralPart.prototype.getOption = function (value) {
var options = this.options,
option = this.pluralFunction(value);
return options[option] || options.other;
};
// -- MessageFormat Parser -------------------------------------------------
// Copied from: https://github.com/yahoo/locator-lang
// `type` (required): The name of the message format type.
// `regex` (required): The regex used to check if this formatter can parse the message.
// `parse` (required): The main parse method which is given the full message.
// `tokenParser` (optional): Used to parse the remaining tokens of a message (what remains after the variable and the format type).
// `postParser` (optional): Used to format the output before returning from the main `parse` method.
// `outputFormatter` (optional): Used to format the fully parsed string returned from the base case of the recursive parser.
var FORMATTERS = [
{
type: 'string',
regex: /^{\s*([-\w]+)\s*}$/,
parse: formatElementParser,
postParser: function (parsed) {
return '${' + parsed.valueName + '}';
}
},
{
type: 'select',
regex: /^{\s*([-\w]+)\s*,\s*select\s*,\s*(.*)\s*}$/,
parse: formatElementParser,
tokenParser: pairedOptionsParser
},
{
type: 'plural',
regex: /^{\s*([-\w]+)\s*,\s*plural\s*,\s*(.*)\s*}$/,
parse: formatElementParser,
tokenParser: pairedOptionsParser,
outputFormatter: function (str) {
return str.replace(/#/g, '${#}');
}
},
{
type: 'time',
regex: /^{\s*([-\w]+)\s*,\s*time(?:,(.*))?\s*}$/,
parse: formatElementParser,
tokenParser: formatOptionParser,
postParser: function (parsed) {
parsed.format = parsed.format || 'medium';
return parsed;
}
},
{
type: 'date',
regex: /^{\s*([-\w]+)\s*,\s*date(?:,(.*))?\s*}$/,
parse: formatElementParser,
tokenParser: formatOptionParser,
postParser: function (parsed) {
parsed.format = parsed.format || 'medium';
return parsed;
}
},
{
type: 'number',
regex: /^{\s*([-\w]+)\s*,\s*number(?:,(.*))?\s*}$/,
parse: formatElementParser,
tokenParser: formatOptionParser
},
{
type: 'custom',
regex: /^{\s*([-\w]+)\s*,\s*([a-zA-Z]*)(?:,(.*))?\s*}$/,
parse: formatElementParser,
tokenParser:formatOptionParser
}
];
/**
Tokenizes a MessageFormat pattern.
@method tokenize
@param {String} pattern A pattern
@param {Boolean} trim Whether or not the tokens should be trimmed of whitespace
@return {Array} Tokens
**/
function tokenize (pattern, trim) {
var bracketRE = /[{}]/g,
tokens = [],
balance = 0,
startIndex = 0,
endIndex,
substr,
match,
i,
len;
match = bracketRE.exec(pattern);
while (match) {
// Keep track of balanced brackets
balance += match[0] === '{' ? 1 : -1;
// Imbalanced brackets detected (e.g. "}hello{", "{hello}}")
if (balance < 0) {
throw new Error('Imbalanced bracket detected at index ' +
match.index + ' for message "' + pattern + '"');
}
// Tokenize a pair of balanced brackets
if (balance === 0) {
endIndex = match.index + 1;
tokens.push(
pattern.slice(startIndex, endIndex)
);
startIndex = endIndex;
}
// Tokenize any text that comes before the first opening bracket
if (balance === 1 && startIndex !== match.index) {
substr = pattern.slice(startIndex, match.index);
if (substr.indexOf('{') === -1) {
tokens.push(substr);
startIndex = match.index;
}
}
match = bracketRE.exec(pattern);
}
// Imbalanced brackets detected (e.g. "{{hello}")
if (balance !== 0) {
throw new Error('Brackets were not properly closed: ' + pattern);
}
// Tokenize any remaining non-empty string
if (startIndex !== pattern.length) {
tokens.push(
pattern.slice(startIndex)
);
}
if (trim) {
for (i = 0, len = tokens.length; i < len; i++) {
tokens[i] = tokens[i].replace(/^\s+|\s+$/gm, '');
}
}
return tokens;
}
/**
Gets the content of the format element by peeling off the outermost pair of
brackets.
@method getFormatElementContent
@param {String} formatElement Format element
@return {String} Contents of format element
**/
function getFormatElementContent (formatElement) {
return formatElement.replace(/^\{\s*/,'').replace(/\s*\}$/, '');
}
/**
Checks if the pattern contains a format element.
@method containsFormatElement
@param {String} pattern Pattern
@return {Boolean} Whether or not the pattern contains a format element
**/
function containsFormatElement (pattern) {
return pattern.indexOf('{') >= 0;
}
/**
Parses a list of tokens into paired options where the key is the option name
and the value is the pattern.
@method pairedOptionsParser
@param {Object} parsed Parsed object
@param {Array} tokens Remaining tokens that come after the value name and the
format id
@return {Object} Parsed object with added options
**/
function pairedOptionsParser (parsed, tokens) {
var hasDefault,
value,
name,
l,
i;
parsed.options = {};
if (tokens.length % 2) {
throw new Error('Options must come in pairs: ' + tokens.join(', '));
}
for (i = 0, l = tokens.length; i < l; i += 2) {
name = tokens[i];
value = tokens[i + 1];
parsed.options[name] = value;
hasDefault = hasDefault || name === 'other';
}
if (!hasDefault) {
throw new Error('Options must include default "other" option: ' + tokens.join(', '));
}
return parsed;
}
function formatOptionParser (parsed, tokens) {
parsed.format = tokens[0];
return parsed;
}
/**
Parses a format element. Format elements are surrounded by curly braces, and
contain at least a value name.
@method formatElementParser
@param {String} formatElement A format element
@param {Object} match The result of a String.match() that has at least the
value name at index 1 and a subformat at index 2
@return {Object} Parsed object
**/
function formatElementParser (formatElement, match, formatter) {
var parsed = {
type: formatter.type,
valueName: match[1]
},
tokens = match[2] && tokenize(match[2], true);
// If there are any additional tokens to parse, it should be done here
if (formatter.tokenParser && tokens) {
parsed = formatter.tokenParser(parsed, tokens);
}
// Any final modifications to the parsed output should be done here
if (formatter.postParser) {
parsed = formatter.postParser(parsed);
}
return parsed;
}
/**
For each formatter, test it on the token in order. Exit early on first
token matched.
@method parseToken
@param {Array} tokens
@param {Number} index
@return {String|Object} Parsed token or original token
*/
function parseToken (tokens, index) {
var i, len;
for (i = 0, len = FORMATTERS.length; i < len; i++) {
if (parseFormatTokens(FORMATTERS[i], tokens, index)) {
return tokens[index];
}
}
return tokens[index];
}
/**
Attempts to parse a token at the given index with the provided formatter.
If the token fails the `formatter.regex`, `false` is returned. Otherwise,
the token is parsed with `formatter.parse`. Then if the token contains
options due to the parsing process, it has each option processed. Then it
returns `true` alerting the caller the token was parsed.
@method parseFormatTokens
@param {Object} formatter
@param {Array} tokens
@param {Number} tokenIndex
@return {Boolean}
*/
function parseFormatTokens (formatter, tokens, tokenIndex) {
var token = tokens[tokenIndex],
match = token.match(formatter.regex),
parsedToken,
parsedKeys = [],
key,
i, len;
if (match) {
parsedToken = formatter.parse(token, match, formatter);
tokens[tokenIndex] = parsedToken;
// if we have options, each option must be parsed
if (parsedToken && parsedToken.options && typeof parsedToken.options === 'object') {
for (key in parsedToken.options) {
if (parsedToken.options.hasOwnProperty(key)) {
parsedKeys.push(key);
}
}
}
for (i = 0, len = parsedKeys.length; i < len; i++) {
parseFormatOptions(parsedToken, parsedKeys[i], formatter);
}
return true;
}
return !!match;
}
/**
@method parseFormatOptions
@param {Object}
*/
function parseFormatOptions (parsedToken, key, formatter) {
var value = parsedToken.options && parsedToken.options[key];
value = getFormatElementContent(value);
parsedToken.options[key] = parse(value, formatter.outputFormatter);
}
/**
Parses a pattern that may contain nested format elements.
@method parse
@param {String} pattern A pattern
@return {Object|Array} Parsed output
**/
function parse (pattern, outputFormatter) {
var tokens,
i, len;
// base case (plain string)
if (!containsFormatElement(pattern)) {
// Final chance to format the string before the parser spits it out
return outputFormatter ? outputFormatter(pattern) : [pattern];
}
tokens = tokenize(pattern);
for (i = 0, len = tokens.length; i < len; i++) {
if (tokens[i].charAt(0) === '{') { // tokens must start with a {
tokens[i] = parseToken(tokens, i);
}
}
return tokens;
}
// -- Utilities ------------------------------------------------------------
function extend(obj) {
var sources = Array.prototype.slice.call(arguments, 1),
i, len, source, key;
for (i = 0, len = sources.length; i < len; i += 1) {
source = sources[i];
if (!source) { continue; }
for (key in source) {
if (source.hasOwnProperty(key)) {
obj[key] = source[key];
}
}
}
return obj;
}
return MessageFormat;
});
IntlMessageFormat.__addLocaleData({locale:"lv", messageformat:{pluralFunction:function (n) { var v=n.toString().replace(/^[^.]*\.?/,"").length,f=parseInt(n.toString().replace(/^[^.]*\.?/,""),10);n=Math.floor(n);if(n%10===0||n%100>=11&&n%100<=19||v===2&&f%100>=11&&f%100<=19)return"zero";if(n%10===1&&((n%100!==11)||v===2&&f%10===1&&((f%100!==11)||(v!==2)&&f%10===1)))return"one";return"other"; }}}); | ahocevar/cdnjs | ajax/libs/intl-messageformat/0.1.0/intl-messageformat.lv.js | JavaScript | mit | 27,362 |
/**
* Functionality for drawing simple NavigationBar.
*/
import { __extends } from "tslib";
/**
* ============================================================================
* IMPORTS
* ============================================================================
* @hidden
*/
import { Component } from "../../core/Component";
import { DataItem } from "../../core/DataItem";
import { ListTemplate, ListDisposer } from "../../core/utils/List";
import { TextLink } from "../../core/elements/TextLink";
import { Triangle } from "../../core/elements/Triangle";
import { registry } from "../../core/Registry";
import { InterfaceColorSet } from "../../core/utils/InterfaceColorSet";
import { percent } from "../../core/utils/Percent";
import * as $iter from "../../core/utils/Iterator";
/**
* ============================================================================
* DATA ITEM
* ============================================================================
* @hidden
*/
/**
* Defines a [[DataItem]] for [[NavigationBar]].
*
* @see {@link DataItem}
*/
var NavigationBarDataItem = /** @class */ (function (_super) {
__extends(NavigationBarDataItem, _super);
/**
* Constructor
*/
function NavigationBarDataItem() {
var _this = _super.call(this) || this;
_this.className = "NavigationBarDataItem";
_this.applyTheme();
return _this;
}
Object.defineProperty(NavigationBarDataItem.prototype, "name", {
/**
* @return Name
*/
get: function () {
return this.properties["name"];
},
/**
* Name of the navigation bar item.
*
* @param value Name
*/
set: function (value) {
this.setProperty("name", value);
},
enumerable: true,
configurable: true
});
return NavigationBarDataItem;
}(DataItem));
export { NavigationBarDataItem };
/**
* ============================================================================
* MAIN CLASS
* ============================================================================
* @hidden
*/
/**
* NavigationBar class can be used to create a multi-level breadcrumb-style
* navigation control.
*
* @see {@link INavigationBarEvents} for a list of available events
* @see {@link INavigationBarAdapters} for a list of available Adapters
* @todo Implement better
* @important
*/
var NavigationBar = /** @class */ (function (_super) {
__extends(NavigationBar, _super);
/**
* Constructor
*/
function NavigationBar() {
var _this =
// Init
_super.call(this) || this;
_this.className = "NavigationBar";
var interfaceColors = new InterfaceColorSet();
var textLink = new TextLink();
textLink.valign = "middle";
textLink.paddingTop = 8;
textLink.paddingBottom = 8;
_this.paddingBottom = 2;
_this.links = new ListTemplate(textLink);
_this._disposers.push(new ListDisposer(_this.links));
_this._disposers.push(textLink);
_this._linksIterator = new $iter.ListIterator(_this.links, function () { return _this.links.create(); });
_this._linksIterator.createNewItems = true;
var triangle = new Triangle();
triangle.direction = "right";
triangle.width = 8;
triangle.height = 12;
triangle.fill = interfaceColors.getFor("alternativeBackground");
triangle.fillOpacity = 0.5;
triangle.valign = "middle";
triangle.marginLeft = 10;
triangle.marginRight = 10;
_this.separators = new ListTemplate(triangle);
_this._disposers.push(new ListDisposer(_this.separators));
_this._disposers.push(triangle);
var activeLink = new TextLink();
_this.activeLink = activeLink;
activeLink.copyFrom(textLink);
activeLink.valign = "middle";
activeLink.fontWeight = "bold";
_this.width = percent(100);
_this.layout = "grid";
_this.dataFields.name = "name";
// Apply theme
_this.applyTheme();
return _this;
}
/**
* Completely redraws the navigation bar.
*
* @ignore Exclude from docs
*/
NavigationBar.prototype.validateDataElements = function () {
this.removeChildren();
this._linksIterator.reset();
_super.prototype.validateDataElements.call(this);
//@todo: dispose
};
/**
* Creates a visual element for a data item (nav item).
*
* @ignore Exclude from docs
* @param dataItem Data item
*/
NavigationBar.prototype.validateDataElement = function (dataItem) {
_super.prototype.validateDataElement.call(this, dataItem);
var textLink;
if (dataItem.index < this.dataItems.length - 1) {
textLink = this._linksIterator.getLast();
textLink.parent = this;
var separator = this.separators.create();
separator.parent = this;
separator.valign = "middle";
}
else {
textLink = this.activeLink;
textLink.events.copyFrom(this.links.template.events);
textLink.hide(0);
textLink.show();
textLink.parent = this;
}
textLink.dataItem = dataItem;
textLink.text = dataItem.name;
textLink.validate();
};
return NavigationBar;
}(Component));
export { NavigationBar };
/**
* Register class in system, so that it can be instantiated using its name from
* anywhere.
*
* @ignore
*/
registry.registeredClasses["NavigationBar"] = NavigationBar;
registry.registeredClasses["NavigationBarDataItem"] = NavigationBarDataItem;
//# sourceMappingURL=NavigationBar.js.map | cdnjs/cdnjs | ajax/libs/amcharts4/4.9.37/.internal/charts/elements/NavigationBar.js | JavaScript | mit | 5,941 |
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.0.5
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.radioButton
* @description radioButton module!
*/
angular.module('material.components.radioButton', [
'material.core'
])
.directive('mdRadioGroup', mdRadioGroupDirective)
.directive('mdRadioButton', mdRadioButtonDirective);
/**
* @ngdoc directive
* @module material.components.radioButton
* @name mdRadioGroup
*
* @restrict E
*
* @description
* The `<md-radio-group>` directive identifies a grouping
* container for the 1..n grouped radio buttons; specified using nested
* `<md-radio-button>` tags.
*
* As per the [material design spec](http://www.google.com/design/spec/style/color.html#color-ui-color-application)
* the radio button is in the accent color by default. The primary color palette may be used with
* the `md-primary` class.
*
* Note: `<md-radio-group>` and `<md-radio-button>` handle tabindex differently
* than the native `<input type='radio'>` controls. Whereas the native controls
* force the user to tab through all the radio buttons, `<md-radio-group>`
* is focusable, and by default the `<md-radio-button>`s are not.
*
* @param {string} ng-model Assignable angular expression to data-bind to.
* @param {boolean=} md-no-ink Use of attribute indicates flag to disable ink ripple effects.
*
* @usage
* <hljs lang="html">
* <md-radio-group ng-model="selected">
*
* <md-radio-button
* ng-repeat="d in colorOptions"
* ng-value="d.value" aria-label="{{ d.label }}">
*
* {{ d.label }}
*
* </md-radio-button>
*
* </md-radio-group>
* </hljs>
*
*/
function mdRadioGroupDirective($mdUtil, $mdConstant, $mdTheming, $timeout) {
RadioGroupController.prototype = createRadioGroupControllerProto();
return {
restrict: 'E',
controller: ['$element', RadioGroupController],
require: ['mdRadioGroup', '?ngModel'],
link: { pre: linkRadioGroup }
};
function linkRadioGroup(scope, element, attr, ctrls) {
$mdTheming(element);
var rgCtrl = ctrls[0];
var ngModelCtrl = ctrls[1] || $mdUtil.fakeNgModel();
rgCtrl.init(ngModelCtrl);
scope.mouseActive = false;
element.attr({
'role': 'radiogroup',
'tabIndex': element.attr('tabindex') || '0'
})
.on('keydown', keydownListener)
.on('mousedown', function(event) {
scope.mouseActive = true;
$timeout(function() {
scope.mouseActive = false;
}, 100);
})
.on('focus', function() {
if(scope.mouseActive === false) { rgCtrl.$element.addClass('md-focused'); }
})
.on('blur', function() { rgCtrl.$element.removeClass('md-focused'); });
/**
*
*/
function setFocus() {
if (!element.hasClass('md-focused')) { element.addClass('md-focused'); }
}
/**
*
*/
function keydownListener(ev) {
var keyCode = ev.which || ev.keyCode;
// Only listen to events that we originated ourselves
// so that we don't trigger on things like arrow keys in
// inputs.
if (keyCode != $mdConstant.KEY_CODE.ENTER &&
ev.currentTarget != ev.target) {
return;
}
switch (keyCode) {
case $mdConstant.KEY_CODE.LEFT_ARROW:
case $mdConstant.KEY_CODE.UP_ARROW:
ev.preventDefault();
rgCtrl.selectPrevious();
setFocus();
break;
case $mdConstant.KEY_CODE.RIGHT_ARROW:
case $mdConstant.KEY_CODE.DOWN_ARROW:
ev.preventDefault();
rgCtrl.selectNext();
setFocus();
break;
case $mdConstant.KEY_CODE.ENTER:
var form = angular.element($mdUtil.getClosest(element[0], 'form'));
if (form.length > 0) {
form.triggerHandler('submit');
}
break;
}
}
}
function RadioGroupController($element) {
this._radioButtonRenderFns = [];
this.$element = $element;
}
function createRadioGroupControllerProto() {
return {
init: function(ngModelCtrl) {
this._ngModelCtrl = ngModelCtrl;
this._ngModelCtrl.$render = angular.bind(this, this.render);
},
add: function(rbRender) {
this._radioButtonRenderFns.push(rbRender);
},
remove: function(rbRender) {
var index = this._radioButtonRenderFns.indexOf(rbRender);
if (index !== -1) {
this._radioButtonRenderFns.splice(index, 1);
}
},
render: function() {
this._radioButtonRenderFns.forEach(function(rbRender) {
rbRender();
});
},
setViewValue: function(value, eventType) {
this._ngModelCtrl.$setViewValue(value, eventType);
// update the other radio buttons as well
this.render();
},
getViewValue: function() {
return this._ngModelCtrl.$viewValue;
},
selectNext: function() {
return changeSelectedButton(this.$element, 1);
},
selectPrevious: function() {
return changeSelectedButton(this.$element, -1);
},
setActiveDescendant: function (radioId) {
this.$element.attr('aria-activedescendant', radioId);
}
};
}
/**
* Change the radio group's selected button by a given increment.
* If no button is selected, select the first button.
*/
function changeSelectedButton(parent, increment) {
// Coerce all child radio buttons into an array, then wrap then in an iterator
var buttons = $mdUtil.iterator(parent[0].querySelectorAll('md-radio-button'), true);
if (buttons.count()) {
var validate = function (button) {
// If disabled, then NOT valid
return !angular.element(button).attr("disabled");
};
var selected = parent[0].querySelector('md-radio-button.md-checked');
var target = buttons[increment < 0 ? 'previous' : 'next'](selected, validate) || buttons.first();
// Activate radioButton's click listener (triggerHandler won't create a real click event)
angular.element(target).triggerHandler('click');
}
}
}
mdRadioGroupDirective.$inject = ["$mdUtil", "$mdConstant", "$mdTheming", "$timeout"];
/**
* @ngdoc directive
* @module material.components.radioButton
* @name mdRadioButton
*
* @restrict E
*
* @description
* The `<md-radio-button>`directive is the child directive required to be used within `<md-radio-group>` elements.
*
* While similar to the `<input type="radio" ng-model="" value="">` directive,
* the `<md-radio-button>` directive provides ink effects, ARIA support, and
* supports use within named radio groups.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {string} ngValue Angular expression which sets the value to which the expression should
* be set when selected.
* @param {string} value The value to which the expression should be set when selected.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} aria-label Adds label to radio button for accessibility.
* Defaults to radio button's text. If no text content is available, a warning will be logged.
*
* @usage
* <hljs lang="html">
*
* <md-radio-button value="1" aria-label="Label 1">
* Label 1
* </md-radio-button>
*
* <md-radio-button ng-model="color" ng-value="specialValue" aria-label="Green">
* Green
* </md-radio-button>
*
* </hljs>
*
*/
function mdRadioButtonDirective($mdAria, $mdUtil, $mdTheming) {
var CHECKED_CSS = 'md-checked';
return {
restrict: 'E',
require: '^mdRadioGroup',
transclude: true,
template: '<div class="md-container" md-ink-ripple md-ink-ripple-checkbox>' +
'<div class="md-off"></div>' +
'<div class="md-on"></div>' +
'</div>' +
'<div ng-transclude class="md-label"></div>',
link: link
};
function link(scope, element, attr, rgCtrl) {
var lastChecked;
$mdTheming(element);
configureAria(element, scope);
initialize();
/**
*
*/
function initialize(controller) {
if ( !rgCtrl ) {
throw 'RadioGroupController not found.';
}
rgCtrl.add(render);
attr.$observe('value', render);
element
.on('click', listener)
.on('$destroy', function() {
rgCtrl.remove(render);
});
}
/**
*
*/
function listener(ev) {
if (element[0].hasAttribute('disabled')) return;
scope.$apply(function() {
rgCtrl.setViewValue(attr.value, ev && ev.type);
});
}
/**
* Add or remove the `.md-checked` class from the RadioButton (and conditionally its parent).
* Update the `aria-activedescendant` attribute.
*/
function render() {
var checked = (rgCtrl.getViewValue() == attr.value);
if (checked === lastChecked) {
return;
}
lastChecked = checked;
element.attr('aria-checked', checked);
if (checked) {
markParentAsChecked(true);
element.addClass(CHECKED_CSS);
rgCtrl.setActiveDescendant(element.attr('id'));
} else {
markParentAsChecked(false);
element.removeClass(CHECKED_CSS);
}
/**
* If the radioButton is inside a div, then add class so highlighting will work...
*/
function markParentAsChecked(addClass ) {
if ( element.parent()[0].nodeName != "MD-RADIO-GROUP") {
element.parent()[ !!addClass ? 'addClass' : 'removeClass'](CHECKED_CSS);
}
}
}
/**
* Inject ARIA-specific attributes appropriate for each radio button
*/
function configureAria( element, scope ){
scope.ariaId = buildAriaID();
element.attr({
'id' : scope.ariaId,
'role' : 'radio',
'aria-checked' : 'false'
});
$mdAria.expectWithText(element, 'aria-label');
/**
* Build a unique ID for each radio button that will be used with aria-activedescendant.
* Preserve existing ID if already specified.
* @returns {*|string}
*/
function buildAriaID() {
return attr.id || ( 'radio' + "_" + $mdUtil.nextUid() );
}
}
}
}
mdRadioButtonDirective.$inject = ["$mdAria", "$mdUtil", "$mdTheming"];
})(window, window.angular); | akera-io/akera-devstudio | www/libs/angular-material/modules/js/radioButton/radioButton.js | JavaScript | mit | 10,669 |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v6.4.0
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var utils_1 = require("../../utils");
var context_1 = require("../../context/context");
var eventService_1 = require("../../eventService");
var events_1 = require("../../events");
var logger_1 = require("../../logger");
var virtualPage_1 = require("./virtualPage");
var VirtualPageCache = (function () {
function VirtualPageCache(cacheSettings) {
this.pages = {};
this.activePageLoadsCount = 0;
this.pagesInCacheCount = 0;
this.maxRowFound = false;
this.active = true;
this.cacheParams = cacheSettings;
this.virtualRowCount = cacheSettings.paginationInitialRowCount;
}
VirtualPageCache.prototype.setBeans = function (loggerFactory) {
this.logger = loggerFactory.create('VirtualPageCache');
};
VirtualPageCache.prototype.init = function () {
// start load of data, as the virtualRowCount will remain at 0 otherwise,
// so we need this to kick things off, otherwise grid would never call getRow()
this.getRow(0);
};
VirtualPageCache.prototype.getRowCombinedHeight = function () {
return this.virtualRowCount * this.cacheParams.rowHeight;
};
VirtualPageCache.prototype.forEachNode = function (callback) {
var _this = this;
var index = 0;
utils_1.Utils.iterateObject(this.pages, function (key, cachePage) {
var start = cachePage.getStartRow();
var end = cachePage.getEndRow();
for (var rowIndex = start; rowIndex < end; rowIndex++) {
// we check against virtualRowCount as this page may be the last one, and if it is, then
// it's probable that the last rows are not part of the set
if (rowIndex < _this.virtualRowCount) {
var rowNode = cachePage.getRow(rowIndex);
callback(rowNode, index);
index++;
}
}
});
};
VirtualPageCache.prototype.getRowIndexAtPixel = function (pixel) {
if (this.cacheParams.rowHeight !== 0) {
var rowIndexForPixel = Math.floor(pixel / this.cacheParams.rowHeight);
if (rowIndexForPixel >= this.virtualRowCount) {
return this.virtualRowCount - 1;
}
else {
return rowIndexForPixel;
}
}
else {
return 0;
}
};
VirtualPageCache.prototype.moveItemsDown = function (page, moveFromIndex, moveCount) {
var startRow = page.getStartRow();
var endRow = page.getEndRow();
var indexOfLastRowToMove = moveFromIndex + moveCount;
// all rows need to be moved down below the insertion index
for (var currentRowIndex = endRow - 1; currentRowIndex >= startRow; currentRowIndex--) {
// don't move rows at or before the insertion index
if (currentRowIndex < indexOfLastRowToMove) {
continue;
}
var indexOfNodeWeWant = currentRowIndex - moveCount;
var nodeForThisIndex = this.getRow(indexOfNodeWeWant, true);
if (nodeForThisIndex) {
page.setRowNode(currentRowIndex, nodeForThisIndex);
}
else {
page.setBlankRowNode(currentRowIndex);
page.setDirty();
}
}
};
VirtualPageCache.prototype.insertItems = function (page, indexToInsert, items) {
var pageStartRow = page.getStartRow();
var pageEndRow = page.getEndRow();
var newRowNodes = [];
// next stage is insert the rows into this page, if applicable
for (var index = 0; index < items.length; index++) {
var rowIndex = indexToInsert + index;
var currentRowInThisPage = rowIndex >= pageStartRow && rowIndex < pageEndRow;
if (currentRowInThisPage) {
var dataItem = items[index];
var newRowNode = page.setNewData(rowIndex, dataItem);
newRowNodes.push(newRowNode);
}
}
return newRowNodes;
};
VirtualPageCache.prototype.insertItemsAtIndex = function (indexToInsert, items) {
var _this = this;
// get all page id's as NUMBERS (not strings, as we need to sort as numbers) and in descending order
var pageIds = Object.keys(this.pages).map(function (str) { return parseInt(str); }).sort().reverse();
var newNodes = [];
pageIds.forEach(function (pageId) {
var page = _this.pages[pageId];
var pageEndRow = page.getEndRow();
// if the insertion is after this page, then this page is not impacted
if (pageEndRow <= indexToInsert) {
return;
}
_this.moveItemsDown(page, indexToInsert, items.length);
var newNodesThisPage = _this.insertItems(page, indexToInsert, items);
newNodesThisPage.forEach(function (rowNode) { return newNodes.push(rowNode); });
});
if (this.maxRowFound) {
this.virtualRowCount += items.length;
}
this.dispatchModelUpdated();
this.eventService.dispatchEvent(events_1.Events.EVENT_ITEMS_ADDED, newNodes);
};
VirtualPageCache.prototype.getRowCount = function () {
return this.virtualRowCount;
};
VirtualPageCache.prototype.onPageLoaded = function (event) {
// if we are not active, then we ignore all events, otherwise we could end up getting the
// grid to refresh even though we are no longer the active cache
if (!this.active) {
return;
}
this.logger.log("onPageLoaded: page = " + event.page.getPageNumber() + ", lastRow = " + event.lastRow);
this.activePageLoadsCount--;
this.checkPageToLoad();
if (event.success) {
this.checkVirtualRowCount(event.page, event.lastRow);
}
};
// as we are not a context managed bean, we cannot use @PreDestroy
VirtualPageCache.prototype.destroy = function () {
this.active = false;
};
// the rowRenderer will not pass dontCreatePage, meaning when rendering the grid,
// it will want new pages in teh cache as it asks for rows. only when we are inserting /
// removing rows via the api is dontCreatePage set, where we move rows between the pages.
VirtualPageCache.prototype.getRow = function (rowIndex, dontCreatePage) {
if (dontCreatePage === void 0) { dontCreatePage = false; }
var pageNumber = Math.floor(rowIndex / this.cacheParams.pageSize);
var page = this.pages[pageNumber];
if (!page) {
if (dontCreatePage) {
return null;
}
else {
page = this.createPage(pageNumber);
}
}
return page.getRow(rowIndex);
};
VirtualPageCache.prototype.createPage = function (pageNumber) {
var newPage = new virtualPage_1.VirtualPage(pageNumber, this.cacheParams);
this.context.wireBean(newPage);
newPage.addEventListener(virtualPage_1.VirtualPage.EVENT_LOAD_COMPLETE, this.onPageLoaded.bind(this));
this.pages[pageNumber] = newPage;
this.pagesInCacheCount++;
var needToPurge = utils_1.Utils.exists(this.cacheParams.maxPagesInCache)
&& this.pagesInCacheCount > this.cacheParams.maxPagesInCache;
if (needToPurge) {
var lruPage = this.findLeastRecentlyUsedPage(newPage);
this.removePageFromCache(lruPage);
}
this.checkPageToLoad();
return newPage;
};
VirtualPageCache.prototype.removePageFromCache = function (pageToRemove) {
if (!pageToRemove) {
return;
}
delete this.pages[pageToRemove.getPageNumber()];
this.pagesInCacheCount--;
// we do not want to remove the 'loaded' event listener, as the
// concurrent loads count needs to be updated when the load is complete
// if the purged page is in loading state
};
VirtualPageCache.prototype.printCacheStatus = function () {
this.logger.log("checkPageToLoad: activePageLoadsCount = " + this.activePageLoadsCount + ", pages = " + JSON.stringify(this.getPageState()));
};
VirtualPageCache.prototype.checkPageToLoad = function () {
this.printCacheStatus();
if (this.activePageLoadsCount >= this.cacheParams.maxConcurrentDatasourceRequests) {
this.logger.log("checkPageToLoad: max loads exceeded");
return;
}
var pageToLoad = null;
utils_1.Utils.iterateObject(this.pages, function (key, cachePage) {
if (cachePage.getState() === virtualPage_1.VirtualPage.STATE_DIRTY) {
pageToLoad = cachePage;
}
});
if (pageToLoad) {
pageToLoad.load();
this.activePageLoadsCount++;
this.logger.log("checkPageToLoad: loading page " + pageToLoad.getPageNumber());
this.printCacheStatus();
}
else {
this.logger.log("checkPageToLoad: no pages to load");
}
};
VirtualPageCache.prototype.findLeastRecentlyUsedPage = function (pageToExclude) {
var lruPage = null;
utils_1.Utils.iterateObject(this.pages, function (key, page) {
// we exclude checking for the page just created, as this has yet to be accessed and hence
// the lastAccessed stamp will not be updated for the first time yet
if (page === pageToExclude) {
return;
}
if (utils_1.Utils.missing(lruPage) || page.getLastAccessed() < lruPage.getLastAccessed()) {
lruPage = page;
}
});
return lruPage;
};
VirtualPageCache.prototype.checkVirtualRowCount = function (page, lastRow) {
// if client provided a last row, we always use it, as it could change between server calls
// if user deleted data and then called refresh on the grid.
if (typeof lastRow === 'number' && lastRow >= 0) {
this.virtualRowCount = lastRow;
this.maxRowFound = true;
this.dispatchModelUpdated();
}
else if (!this.maxRowFound) {
// otherwise, see if we need to add some virtual rows
var lastRowIndex = (page.getPageNumber() + 1) * this.cacheParams.pageSize;
var lastRowIndexPlusOverflow = lastRowIndex + this.cacheParams.paginationOverflowSize;
if (this.virtualRowCount < lastRowIndexPlusOverflow) {
this.virtualRowCount = lastRowIndexPlusOverflow;
this.dispatchModelUpdated();
}
}
};
VirtualPageCache.prototype.dispatchModelUpdated = function () {
if (this.active) {
this.eventService.dispatchEvent(events_1.Events.EVENT_MODEL_UPDATED);
}
};
VirtualPageCache.prototype.getPageState = function () {
var result = [];
utils_1.Utils.iterateObject(this.pages, function (pageNumber, page) {
result.push({ pageNumber: pageNumber, startRow: page.getStartRow(), endRow: page.getEndRow(), pageStatus: page.getState() });
});
return result;
};
VirtualPageCache.prototype.refreshVirtualPageCache = function () {
utils_1.Utils.iterateObject(this.pages, function (pageId, page) {
page.setDirty();
});
this.checkPageToLoad();
};
VirtualPageCache.prototype.purgeVirtualPageCache = function () {
var _this = this;
var pagesList = utils_1.Utils.values(this.pages);
pagesList.forEach(function (virtualPage) { return _this.removePageFromCache(virtualPage); });
this.dispatchModelUpdated();
};
VirtualPageCache.prototype.getVirtualRowCount = function () {
return this.virtualRowCount;
};
VirtualPageCache.prototype.isMaxRowFound = function () {
return this.maxRowFound;
};
VirtualPageCache.prototype.setVirtualRowCount = function (rowCount, maxRowFound) {
this.virtualRowCount = rowCount;
// if undefined is passed, we do not set this value, if one of {true,false}
// is passed, we do set the value.
if (utils_1.Utils.exists(maxRowFound)) {
this.maxRowFound = maxRowFound;
}
// if we are still searching, then the row count must not end at the end
// of a particular page, otherwise the searching will not pop into the
// next page
if (!this.maxRowFound) {
if (this.virtualRowCount % this.cacheParams.pageSize === 0) {
this.virtualRowCount++;
}
}
this.dispatchModelUpdated();
};
__decorate([
context_1.Autowired('eventService'),
__metadata('design:type', eventService_1.EventService)
], VirtualPageCache.prototype, "eventService", void 0);
__decorate([
context_1.Autowired('context'),
__metadata('design:type', context_1.Context)
], VirtualPageCache.prototype, "context", void 0);
__decorate([
__param(0, context_1.Qualifier('loggerFactory')),
__metadata('design:type', Function),
__metadata('design:paramtypes', [logger_1.LoggerFactory]),
__metadata('design:returntype', void 0)
], VirtualPageCache.prototype, "setBeans", null);
__decorate([
context_1.PostConstruct,
__metadata('design:type', Function),
__metadata('design:paramtypes', []),
__metadata('design:returntype', void 0)
], VirtualPageCache.prototype, "init", null);
return VirtualPageCache;
})();
exports.VirtualPageCache = VirtualPageCache;
| menuka94/cdnjs | ajax/libs/ag-grid/6.4.0/lib/rowControllers/virtualPagination/virtualPageCache.js | JavaScript | mit | 14,803 |
/* Copyright 2017 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define("pdfjs-dist/web/pdf_viewer", [], factory);
else if(typeof exports === 'object')
exports["pdfjs-dist/web/pdf_viewer"] = factory();
else
root["pdfjs-dist/web/pdf_viewer"] = root.pdfjsDistWebPdfViewer = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __w_pdfjs_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __w_pdfjs_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __w_pdfjs_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __w_pdfjs_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __w_pdfjs_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __w_pdfjs_require__.d = function(exports, name, getter) {
/******/ if(!__w_pdfjs_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __w_pdfjs_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __w_pdfjs_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __w_pdfjs_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __w_pdfjs_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __w_pdfjs_require__(__w_pdfjs_require__.s = 14);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __w_pdfjs_require__) {
"use strict";
var pdfjsLib;
if (typeof window !== 'undefined' && window['pdfjs-dist/build/pdf']) {
pdfjsLib = window['pdfjs-dist/build/pdf'];
} else if (false) {
pdfjsLib = __non_webpack_require__('../build/pdf.js');
} else {
throw new Error('Neither `require` nor `window` found');
}
module.exports = pdfjsLib;
/***/ }),
/* 1 */
/***/ (function(module, exports, __w_pdfjs_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.localized = exports.animationStarted = exports.normalizeWheelEventDelta = exports.binarySearchFirstItem = exports.watchScroll = exports.scrollIntoView = exports.getOutputScale = exports.approximateFraction = exports.roundToDivide = exports.getVisibleElements = exports.parseQueryString = exports.noContextMenuHandler = exports.getPDFFileNameFromURL = exports.ProgressBar = exports.EventBus = exports.NullL10n = exports.mozL10n = exports.RendererType = exports.cloneObj = exports.VERTICAL_PADDING = exports.SCROLLBAR_PADDING = exports.MAX_AUTO_SCALE = exports.UNKNOWN_SCALE = exports.MAX_SCALE = exports.MIN_SCALE = exports.DEFAULT_SCALE = exports.DEFAULT_SCALE_VALUE = exports.CSS_UNITS = undefined;
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 _pdfjsLib = __w_pdfjs_require__(0);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var CSS_UNITS = 96.0 / 72.0;
var DEFAULT_SCALE_VALUE = 'auto';
var DEFAULT_SCALE = 1.0;
var MIN_SCALE = 0.25;
var MAX_SCALE = 10.0;
var UNKNOWN_SCALE = 0;
var MAX_AUTO_SCALE = 1.25;
var SCROLLBAR_PADDING = 40;
var VERTICAL_PADDING = 5;
var RendererType = {
CANVAS: 'canvas',
SVG: 'svg'
};
function formatL10nValue(text, args) {
if (!args) {
return text;
}
return text.replace(/\{\{\s*(\w+)\s*\}\}/g, function (all, name) {
return name in args ? args[name] : '{{' + name + '}}';
});
}
var NullL10n = {
get: function get(property, args, fallback) {
return Promise.resolve(formatL10nValue(fallback, args));
},
translate: function translate(element) {
return Promise.resolve();
}
};
_pdfjsLib.PDFJS.disableFullscreen = _pdfjsLib.PDFJS.disableFullscreen === undefined ? false : _pdfjsLib.PDFJS.disableFullscreen;
_pdfjsLib.PDFJS.useOnlyCssZoom = _pdfjsLib.PDFJS.useOnlyCssZoom === undefined ? false : _pdfjsLib.PDFJS.useOnlyCssZoom;
_pdfjsLib.PDFJS.maxCanvasPixels = _pdfjsLib.PDFJS.maxCanvasPixels === undefined ? 16777216 : _pdfjsLib.PDFJS.maxCanvasPixels;
_pdfjsLib.PDFJS.disableHistory = _pdfjsLib.PDFJS.disableHistory === undefined ? false : _pdfjsLib.PDFJS.disableHistory;
_pdfjsLib.PDFJS.disableTextLayer = _pdfjsLib.PDFJS.disableTextLayer === undefined ? false : _pdfjsLib.PDFJS.disableTextLayer;
_pdfjsLib.PDFJS.ignoreCurrentPositionOnZoom = _pdfjsLib.PDFJS.ignoreCurrentPositionOnZoom === undefined ? false : _pdfjsLib.PDFJS.ignoreCurrentPositionOnZoom;
{
_pdfjsLib.PDFJS.locale = _pdfjsLib.PDFJS.locale === undefined && typeof navigator !== 'undefined' ? navigator.language : _pdfjsLib.PDFJS.locale;
}
function getOutputScale(ctx) {
var devicePixelRatio = window.devicePixelRatio || 1;
var backingStoreRatio = ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
var pixelRatio = devicePixelRatio / backingStoreRatio;
return {
sx: pixelRatio,
sy: pixelRatio,
scaled: pixelRatio !== 1
};
}
function scrollIntoView(element, spot) {
var skipOverflowHiddenElements = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var parent = element.offsetParent;
if (!parent) {
console.error('offsetParent is not set -- cannot scroll');
return;
}
var offsetY = element.offsetTop + element.clientTop;
var offsetX = element.offsetLeft + element.clientLeft;
while (parent.clientHeight === parent.scrollHeight || skipOverflowHiddenElements && getComputedStyle(parent).overflow === 'hidden') {
if (parent.dataset._scaleY) {
offsetY /= parent.dataset._scaleY;
offsetX /= parent.dataset._scaleX;
}
offsetY += parent.offsetTop;
offsetX += parent.offsetLeft;
parent = parent.offsetParent;
if (!parent) {
return;
}
}
if (spot) {
if (spot.top !== undefined) {
offsetY += spot.top;
}
if (spot.left !== undefined) {
offsetX += spot.left;
parent.scrollLeft = offsetX;
}
}
parent.scrollTop = offsetY;
}
function watchScroll(viewAreaElement, callback) {
var debounceScroll = function debounceScroll(evt) {
if (rAF) {
return;
}
rAF = window.requestAnimationFrame(function viewAreaElementScrolled() {
rAF = null;
var currentY = viewAreaElement.scrollTop;
var lastY = state.lastY;
if (currentY !== lastY) {
state.down = currentY > lastY;
}
state.lastY = currentY;
callback(state);
});
};
var state = {
down: true,
lastY: viewAreaElement.scrollTop,
_eventHandler: debounceScroll
};
var rAF = null;
viewAreaElement.addEventListener('scroll', debounceScroll, true);
return state;
}
function parseQueryString(query) {
var parts = query.split('&');
var params = Object.create(null);
for (var i = 0, ii = parts.length; i < ii; ++i) {
var param = parts[i].split('=');
var key = param[0].toLowerCase();
var value = param.length > 1 ? param[1] : null;
params[decodeURIComponent(key)] = decodeURIComponent(value);
}
return params;
}
function binarySearchFirstItem(items, condition) {
var minIndex = 0;
var maxIndex = items.length - 1;
if (items.length === 0 || !condition(items[maxIndex])) {
return items.length;
}
if (condition(items[minIndex])) {
return minIndex;
}
while (minIndex < maxIndex) {
var currentIndex = minIndex + maxIndex >> 1;
var currentItem = items[currentIndex];
if (condition(currentItem)) {
maxIndex = currentIndex;
} else {
minIndex = currentIndex + 1;
}
}
return minIndex;
}
function approximateFraction(x) {
if (Math.floor(x) === x) {
return [x, 1];
}
var xinv = 1 / x;
var limit = 8;
if (xinv > limit) {
return [1, limit];
} else if (Math.floor(xinv) === xinv) {
return [1, xinv];
}
var x_ = x > 1 ? xinv : x;
var a = 0,
b = 1,
c = 1,
d = 1;
while (true) {
var p = a + c,
q = b + d;
if (q > limit) {
break;
}
if (x_ <= p / q) {
c = p;
d = q;
} else {
a = p;
b = q;
}
}
var result = void 0;
if (x_ - a / b < c / d - x_) {
result = x_ === x ? [a, b] : [b, a];
} else {
result = x_ === x ? [c, d] : [d, c];
}
return result;
}
function roundToDivide(x, div) {
var r = x % div;
return r === 0 ? x : Math.round(x - r + div);
}
function getVisibleElements(scrollEl, views) {
var sortByVisibility = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var top = scrollEl.scrollTop,
bottom = top + scrollEl.clientHeight;
var left = scrollEl.scrollLeft,
right = left + scrollEl.clientWidth;
function isElementBottomBelowViewTop(view) {
var element = view.div;
var elementBottom = element.offsetTop + element.clientTop + element.clientHeight;
return elementBottom > top;
}
var visible = [],
view = void 0,
element = void 0;
var currentHeight = void 0,
viewHeight = void 0,
hiddenHeight = void 0,
percentHeight = void 0;
var currentWidth = void 0,
viewWidth = void 0;
var firstVisibleElementInd = views.length === 0 ? 0 : binarySearchFirstItem(views, isElementBottomBelowViewTop);
for (var i = firstVisibleElementInd, ii = views.length; i < ii; i++) {
view = views[i];
element = view.div;
currentHeight = element.offsetTop + element.clientTop;
viewHeight = element.clientHeight;
if (currentHeight > bottom) {
break;
}
currentWidth = element.offsetLeft + element.clientLeft;
viewWidth = element.clientWidth;
if (currentWidth + viewWidth < left || currentWidth > right) {
continue;
}
hiddenHeight = Math.max(0, top - currentHeight) + Math.max(0, currentHeight + viewHeight - bottom);
percentHeight = (viewHeight - hiddenHeight) * 100 / viewHeight | 0;
visible.push({
id: view.id,
x: currentWidth,
y: currentHeight,
view: view,
percent: percentHeight
});
}
var first = visible[0];
var last = visible[visible.length - 1];
if (sortByVisibility) {
visible.sort(function (a, b) {
var pc = a.percent - b.percent;
if (Math.abs(pc) > 0.001) {
return -pc;
}
return a.id - b.id;
});
}
return {
first: first,
last: last,
views: visible
};
}
function noContextMenuHandler(evt) {
evt.preventDefault();
}
function isDataSchema(url) {
var i = 0,
ii = url.length;
while (i < ii && url[i].trim() === '') {
i++;
}
return url.substr(i, 5).toLowerCase() === 'data:';
}
function getPDFFileNameFromURL(url) {
var defaultFilename = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'document.pdf';
if (isDataSchema(url)) {
console.warn('getPDFFileNameFromURL: ' + 'ignoring "data:" URL for performance reasons.');
return defaultFilename;
}
var reURI = /^(?:(?:[^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
var splitURI = reURI.exec(url);
var suggestedFilename = reFilename.exec(splitURI[1]) || reFilename.exec(splitURI[2]) || reFilename.exec(splitURI[3]);
if (suggestedFilename) {
suggestedFilename = suggestedFilename[0];
if (suggestedFilename.indexOf('%') !== -1) {
try {
suggestedFilename = reFilename.exec(decodeURIComponent(suggestedFilename))[0];
} catch (ex) {}
}
}
return suggestedFilename || defaultFilename;
}
function normalizeWheelEventDelta(evt) {
var delta = Math.sqrt(evt.deltaX * evt.deltaX + evt.deltaY * evt.deltaY);
var angle = Math.atan2(evt.deltaY, evt.deltaX);
if (-0.25 * Math.PI < angle && angle < 0.75 * Math.PI) {
delta = -delta;
}
var MOUSE_DOM_DELTA_PIXEL_MODE = 0;
var MOUSE_DOM_DELTA_LINE_MODE = 1;
var MOUSE_PIXELS_PER_LINE = 30;
var MOUSE_LINES_PER_PAGE = 30;
if (evt.deltaMode === MOUSE_DOM_DELTA_PIXEL_MODE) {
delta /= MOUSE_PIXELS_PER_LINE * MOUSE_LINES_PER_PAGE;
} else if (evt.deltaMode === MOUSE_DOM_DELTA_LINE_MODE) {
delta /= MOUSE_LINES_PER_PAGE;
}
return delta;
}
function cloneObj(obj) {
var result = Object.create(null);
for (var i in obj) {
if (Object.prototype.hasOwnProperty.call(obj, i)) {
result[i] = obj[i];
}
}
return result;
}
var animationStarted = new Promise(function (resolve) {
window.requestAnimationFrame(resolve);
});
var mozL10n = void 0;
var localized = Promise.resolve();
var EventBus = function () {
function EventBus() {
_classCallCheck(this, EventBus);
this._listeners = Object.create(null);
}
_createClass(EventBus, [{
key: 'on',
value: function on(eventName, listener) {
var eventListeners = this._listeners[eventName];
if (!eventListeners) {
eventListeners = [];
this._listeners[eventName] = eventListeners;
}
eventListeners.push(listener);
}
}, {
key: 'off',
value: function off(eventName, listener) {
var eventListeners = this._listeners[eventName];
var i = void 0;
if (!eventListeners || (i = eventListeners.indexOf(listener)) < 0) {
return;
}
eventListeners.splice(i, 1);
}
}, {
key: 'dispatch',
value: function dispatch(eventName) {
var eventListeners = this._listeners[eventName];
if (!eventListeners || eventListeners.length === 0) {
return;
}
var args = Array.prototype.slice.call(arguments, 1);
eventListeners.slice(0).forEach(function (listener) {
listener.apply(null, args);
});
}
}]);
return EventBus;
}();
function clamp(v, min, max) {
return Math.min(Math.max(v, min), max);
}
var ProgressBar = function () {
function ProgressBar(id) {
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
height = _ref.height,
width = _ref.width,
units = _ref.units;
_classCallCheck(this, ProgressBar);
this.visible = true;
this.div = document.querySelector(id + ' .progress');
this.bar = this.div.parentNode;
this.height = height || 100;
this.width = width || 100;
this.units = units || '%';
this.div.style.height = this.height + this.units;
this.percent = 0;
}
_createClass(ProgressBar, [{
key: '_updateBar',
value: function _updateBar() {
if (this._indeterminate) {
this.div.classList.add('indeterminate');
this.div.style.width = this.width + this.units;
return;
}
this.div.classList.remove('indeterminate');
var progressSize = this.width * this._percent / 100;
this.div.style.width = progressSize + this.units;
}
}, {
key: 'setWidth',
value: function setWidth(viewer) {
if (!viewer) {
return;
}
var container = viewer.parentNode;
var scrollbarWidth = container.offsetWidth - viewer.offsetWidth;
if (scrollbarWidth > 0) {
this.bar.setAttribute('style', 'width: calc(100% - ' + scrollbarWidth + 'px);');
}
}
}, {
key: 'hide',
value: function hide() {
if (!this.visible) {
return;
}
this.visible = false;
this.bar.classList.add('hidden');
document.body.classList.remove('loadingInProgress');
}
}, {
key: 'show',
value: function show() {
if (this.visible) {
return;
}
this.visible = true;
document.body.classList.add('loadingInProgress');
this.bar.classList.remove('hidden');
}
}, {
key: 'percent',
get: function get() {
return this._percent;
},
set: function set(val) {
this._indeterminate = isNaN(val);
this._percent = clamp(val, 0, 100);
this._updateBar();
}
}]);
return ProgressBar;
}();
exports.CSS_UNITS = CSS_UNITS;
exports.DEFAULT_SCALE_VALUE = DEFAULT_SCALE_VALUE;
exports.DEFAULT_SCALE = DEFAULT_SCALE;
exports.MIN_SCALE = MIN_SCALE;
exports.MAX_SCALE = MAX_SCALE;
exports.UNKNOWN_SCALE = UNKNOWN_SCALE;
exports.MAX_AUTO_SCALE = MAX_AUTO_SCALE;
exports.SCROLLBAR_PADDING = SCROLLBAR_PADDING;
exports.VERTICAL_PADDING = VERTICAL_PADDING;
exports.cloneObj = cloneObj;
exports.RendererType = RendererType;
exports.mozL10n = mozL10n;
exports.NullL10n = NullL10n;
exports.EventBus = EventBus;
exports.ProgressBar = ProgressBar;
exports.getPDFFileNameFromURL = getPDFFileNameFromURL;
exports.noContextMenuHandler = noContextMenuHandler;
exports.parseQueryString = parseQueryString;
exports.getVisibleElements = getVisibleElements;
exports.roundToDivide = roundToDivide;
exports.approximateFraction = approximateFraction;
exports.getOutputScale = getOutputScale;
exports.scrollIntoView = scrollIntoView;
exports.watchScroll = watchScroll;
exports.binarySearchFirstItem = binarySearchFirstItem;
exports.normalizeWheelEventDelta = normalizeWheelEventDelta;
exports.animationStarted = animationStarted;
exports.localized = localized;
/***/ }),
/* 2 */
/***/ (function(module, exports, __w_pdfjs_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getGlobalEventBus = exports.attachDOMEventsToEventBus = undefined;
var _ui_utils = __w_pdfjs_require__(1);
function attachDOMEventsToEventBus(eventBus) {
eventBus.on('documentload', function () {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('documentload', true, true, {});
window.dispatchEvent(event);
});
eventBus.on('pagerendered', function (e) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagerendered', true, true, {
pageNumber: e.pageNumber,
cssTransform: e.cssTransform
});
e.source.div.dispatchEvent(event);
});
eventBus.on('textlayerrendered', function (e) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('textlayerrendered', true, true, { pageNumber: e.pageNumber });
e.source.textLayerDiv.dispatchEvent(event);
});
eventBus.on('pagechange', function (e) {
var event = document.createEvent('UIEvents');
event.initUIEvent('pagechange', true, true, window, 0);
event.pageNumber = e.pageNumber;
e.source.container.dispatchEvent(event);
});
eventBus.on('pagesinit', function (e) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagesinit', true, true, null);
e.source.container.dispatchEvent(event);
});
eventBus.on('pagesloaded', function (e) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagesloaded', true, true, { pagesCount: e.pagesCount });
e.source.container.dispatchEvent(event);
});
eventBus.on('scalechange', function (e) {
var event = document.createEvent('UIEvents');
event.initUIEvent('scalechange', true, true, window, 0);
event.scale = e.scale;
event.presetValue = e.presetValue;
e.source.container.dispatchEvent(event);
});
eventBus.on('updateviewarea', function (e) {
var event = document.createEvent('UIEvents');
event.initUIEvent('updateviewarea', true, true, window, 0);
event.location = e.location;
e.source.container.dispatchEvent(event);
});
eventBus.on('find', function (e) {
if (e.source === window) {
return;
}
var event = document.createEvent('CustomEvent');
event.initCustomEvent('find' + e.type, true, true, {
query: e.query,
phraseSearch: e.phraseSearch,
caseSensitive: e.caseSensitive,
highlightAll: e.highlightAll,
findPrevious: e.findPrevious
});
window.dispatchEvent(event);
});
eventBus.on('attachmentsloaded', function (e) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('attachmentsloaded', true, true, { attachmentsCount: e.attachmentsCount });
e.source.container.dispatchEvent(event);
});
eventBus.on('sidebarviewchanged', function (e) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('sidebarviewchanged', true, true, { view: e.view });
e.source.outerContainer.dispatchEvent(event);
});
eventBus.on('pagemode', function (e) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('pagemode', true, true, { mode: e.mode });
e.source.pdfViewer.container.dispatchEvent(event);
});
eventBus.on('namedaction', function (e) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('namedaction', true, true, { action: e.action });
e.source.pdfViewer.container.dispatchEvent(event);
});
eventBus.on('presentationmodechanged', function (e) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('presentationmodechanged', true, true, {
active: e.active,
switchInProgress: e.switchInProgress
});
window.dispatchEvent(event);
});
eventBus.on('outlineloaded', function (e) {
var event = document.createEvent('CustomEvent');
event.initCustomEvent('outlineloaded', true, true, { outlineCount: e.outlineCount });
e.source.container.dispatchEvent(event);
});
}
var globalEventBus = null;
function getGlobalEventBus() {
if (globalEventBus) {
return globalEventBus;
}
globalEventBus = new _ui_utils.EventBus();
attachDOMEventsToEventBus(globalEventBus);
return globalEventBus;
}
exports.attachDOMEventsToEventBus = attachDOMEventsToEventBus;
exports.getGlobalEventBus = getGlobalEventBus;
/***/ }),
/* 3 */
/***/ (function(module, exports, __w_pdfjs_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SimpleLinkService = exports.PDFLinkService = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _dom_events = __w_pdfjs_require__(2);
var _ui_utils = __w_pdfjs_require__(1);
var PDFLinkService = function PDFLinkServiceClosure() {
function PDFLinkService(options) {
options = options || {};
this.eventBus = options.eventBus || (0, _dom_events.getGlobalEventBus)();
this.baseUrl = null;
this.pdfDocument = null;
this.pdfViewer = null;
this.pdfHistory = null;
this._pagesRefCache = null;
}
PDFLinkService.prototype = {
setDocument: function PDFLinkService_setDocument(pdfDocument, baseUrl) {
this.baseUrl = baseUrl;
this.pdfDocument = pdfDocument;
this._pagesRefCache = Object.create(null);
},
setViewer: function PDFLinkService_setViewer(pdfViewer) {
this.pdfViewer = pdfViewer;
},
setHistory: function PDFLinkService_setHistory(pdfHistory) {
this.pdfHistory = pdfHistory;
},
get pagesCount() {
return this.pdfDocument ? this.pdfDocument.numPages : 0;
},
get page() {
return this.pdfViewer.currentPageNumber;
},
set page(value) {
this.pdfViewer.currentPageNumber = value;
},
navigateTo: function navigateTo(dest) {
var _this = this;
var goToDestination = function goToDestination(_ref) {
var namedDest = _ref.namedDest,
explicitDest = _ref.explicitDest;
var destRef = explicitDest[0],
pageNumber = void 0;
if (destRef instanceof Object) {
pageNumber = _this._cachedPageNumber(destRef);
if (pageNumber === null) {
_this.pdfDocument.getPageIndex(destRef).then(function (pageIndex) {
_this.cachePageRef(pageIndex + 1, destRef);
goToDestination({
namedDest: namedDest,
explicitDest: explicitDest
});
}).catch(function () {
console.error('PDFLinkService.navigateTo: "' + destRef + '" is not ' + ('a valid page reference, for dest="' + dest + '".'));
});
return;
}
} else if ((destRef | 0) === destRef) {
pageNumber = destRef + 1;
} else {
console.error('PDFLinkService.navigateTo: "' + destRef + '" is not ' + ('a valid destination reference, for dest="' + dest + '".'));
return;
}
if (!pageNumber || pageNumber < 1 || pageNumber > _this.pagesCount) {
console.error('PDFLinkService.navigateTo: "' + pageNumber + '" is not ' + ('a valid page number, for dest="' + dest + '".'));
return;
}
_this.pdfViewer.scrollPageIntoView({
pageNumber: pageNumber,
destArray: explicitDest
});
if (_this.pdfHistory) {
_this.pdfHistory.push({
dest: explicitDest,
hash: namedDest,
page: pageNumber
});
}
};
new Promise(function (resolve, reject) {
if (typeof dest === 'string') {
_this.pdfDocument.getDestination(dest).then(function (destArray) {
resolve({
namedDest: dest,
explicitDest: destArray
});
});
return;
}
resolve({
namedDest: '',
explicitDest: dest
});
}).then(function (data) {
if (!(data.explicitDest instanceof Array)) {
console.error('PDFLinkService.navigateTo: "' + data.explicitDest + '" is' + (' not a valid destination array, for dest="' + dest + '".'));
return;
}
goToDestination(data);
});
},
getDestinationHash: function getDestinationHash(dest) {
if (typeof dest === 'string') {
return this.getAnchorUrl('#' + escape(dest));
}
if (dest instanceof Array) {
var str = JSON.stringify(dest);
return this.getAnchorUrl('#' + escape(str));
}
return this.getAnchorUrl('');
},
getAnchorUrl: function PDFLinkService_getAnchorUrl(anchor) {
return (this.baseUrl || '') + anchor;
},
setHash: function PDFLinkService_setHash(hash) {
var pageNumber, dest;
if (hash.indexOf('=') >= 0) {
var params = (0, _ui_utils.parseQueryString)(hash);
if ('search' in params) {
this.eventBus.dispatch('findfromurlhash', {
source: this,
query: params['search'].replace(/"/g, ''),
phraseSearch: params['phrase'] === 'true'
});
}
if ('nameddest' in params) {
if (this.pdfHistory) {
this.pdfHistory.updateNextHashParam(params.nameddest);
}
this.navigateTo(params.nameddest);
return;
}
if ('page' in params) {
pageNumber = params.page | 0 || 1;
}
if ('zoom' in params) {
var zoomArgs = params.zoom.split(',');
var zoomArg = zoomArgs[0];
var zoomArgNumber = parseFloat(zoomArg);
if (zoomArg.indexOf('Fit') === -1) {
dest = [null, { name: 'XYZ' }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null, zoomArgs.length > 2 ? zoomArgs[2] | 0 : null, zoomArgNumber ? zoomArgNumber / 100 : zoomArg];
} else {
if (zoomArg === 'Fit' || zoomArg === 'FitB') {
dest = [null, { name: zoomArg }];
} else if (zoomArg === 'FitH' || zoomArg === 'FitBH' || zoomArg === 'FitV' || zoomArg === 'FitBV') {
dest = [null, { name: zoomArg }, zoomArgs.length > 1 ? zoomArgs[1] | 0 : null];
} else if (zoomArg === 'FitR') {
if (zoomArgs.length !== 5) {
console.error('PDFLinkService_setHash: ' + 'Not enough parameters for \'FitR\'.');
} else {
dest = [null, { name: zoomArg }, zoomArgs[1] | 0, zoomArgs[2] | 0, zoomArgs[3] | 0, zoomArgs[4] | 0];
}
} else {
console.error('PDFLinkService_setHash: \'' + zoomArg + '\' is not a valid zoom value.');
}
}
}
if (dest) {
this.pdfViewer.scrollPageIntoView({
pageNumber: pageNumber || this.page,
destArray: dest,
allowNegativeOffset: true
});
} else if (pageNumber) {
this.page = pageNumber;
}
if ('pagemode' in params) {
this.eventBus.dispatch('pagemode', {
source: this,
mode: params.pagemode
});
}
} else {
if (/^\d+$/.test(hash) && hash <= this.pagesCount) {
console.warn('PDFLinkService_setHash: specifying a page number ' + 'directly after the hash symbol (#) is deprecated, ' + 'please use the "#page=' + hash + '" form instead.');
this.page = hash | 0;
}
dest = unescape(hash);
try {
dest = JSON.parse(dest);
if (!(dest instanceof Array)) {
dest = dest.toString();
}
} catch (ex) {}
if (typeof dest === 'string' || isValidExplicitDestination(dest)) {
if (this.pdfHistory) {
this.pdfHistory.updateNextHashParam(dest);
}
this.navigateTo(dest);
return;
}
console.error('PDFLinkService_setHash: \'' + unescape(hash) + '\' is not a valid destination.');
}
},
executeNamedAction: function PDFLinkService_executeNamedAction(action) {
switch (action) {
case 'GoBack':
if (this.pdfHistory) {
this.pdfHistory.back();
}
break;
case 'GoForward':
if (this.pdfHistory) {
this.pdfHistory.forward();
}
break;
case 'NextPage':
if (this.page < this.pagesCount) {
this.page++;
}
break;
case 'PrevPage':
if (this.page > 1) {
this.page--;
}
break;
case 'LastPage':
this.page = this.pagesCount;
break;
case 'FirstPage':
this.page = 1;
break;
default:
break;
}
this.eventBus.dispatch('namedaction', {
source: this,
action: action
});
},
onFileAttachmentAnnotation: function onFileAttachmentAnnotation() {
var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.eventBus.dispatch('fileattachmentannotation', {
source: this,
id: params.id,
filename: params.filename,
content: params.content
});
},
cachePageRef: function PDFLinkService_cachePageRef(pageNum, pageRef) {
var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
this._pagesRefCache[refStr] = pageNum;
},
_cachedPageNumber: function PDFLinkService_cachedPageNumber(pageRef) {
var refStr = pageRef.num + ' ' + pageRef.gen + ' R';
return this._pagesRefCache && this._pagesRefCache[refStr] || null;
}
};
function isValidExplicitDestination(dest) {
if (!(dest instanceof Array)) {
return false;
}
var destLength = dest.length,
allowNull = true;
if (destLength < 2) {
return false;
}
var page = dest[0];
if (!((typeof page === 'undefined' ? 'undefined' : _typeof(page)) === 'object' && typeof page.num === 'number' && (page.num | 0) === page.num && typeof page.gen === 'number' && (page.gen | 0) === page.gen) && !(typeof page === 'number' && (page | 0) === page && page >= 0)) {
return false;
}
var zoom = dest[1];
if (!((typeof zoom === 'undefined' ? 'undefined' : _typeof(zoom)) === 'object' && typeof zoom.name === 'string')) {
return false;
}
switch (zoom.name) {
case 'XYZ':
if (destLength !== 5) {
return false;
}
break;
case 'Fit':
case 'FitB':
return destLength === 2;
case 'FitH':
case 'FitBH':
case 'FitV':
case 'FitBV':
if (destLength !== 3) {
return false;
}
break;
case 'FitR':
if (destLength !== 6) {
return false;
}
allowNull = false;
break;
default:
return false;
}
for (var i = 2; i < destLength; i++) {
var param = dest[i];
if (!(typeof param === 'number' || allowNull && param === null)) {
return false;
}
}
return true;
}
return PDFLinkService;
}();
var SimpleLinkService = function SimpleLinkServiceClosure() {
function SimpleLinkService() {}
SimpleLinkService.prototype = {
get page() {
return 0;
},
set page(value) {},
navigateTo: function navigateTo(dest) {},
getDestinationHash: function getDestinationHash(dest) {
return '#';
},
getAnchorUrl: function getAnchorUrl(hash) {
return '#';
},
setHash: function setHash(hash) {},
executeNamedAction: function executeNamedAction(action) {},
onFileAttachmentAnnotation: function onFileAttachmentAnnotation(params) {},
cachePageRef: function cachePageRef(pageNum, pageRef) {}
};
return SimpleLinkService;
}();
exports.PDFLinkService = PDFLinkService;
exports.SimpleLinkService = SimpleLinkService;
/***/ }),
/* 4 */
/***/ (function(module, exports, __w_pdfjs_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DefaultAnnotationLayerFactory = exports.AnnotationLayerBuilder = undefined;
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 _pdfjsLib = __w_pdfjs_require__(0);
var _ui_utils = __w_pdfjs_require__(1);
var _pdf_link_service = __w_pdfjs_require__(3);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var AnnotationLayerBuilder = function () {
function AnnotationLayerBuilder(_ref) {
var pageDiv = _ref.pageDiv,
pdfPage = _ref.pdfPage,
linkService = _ref.linkService,
downloadManager = _ref.downloadManager,
_ref$renderInteractiv = _ref.renderInteractiveForms,
renderInteractiveForms = _ref$renderInteractiv === undefined ? false : _ref$renderInteractiv,
_ref$l10n = _ref.l10n,
l10n = _ref$l10n === undefined ? _ui_utils.NullL10n : _ref$l10n;
_classCallCheck(this, AnnotationLayerBuilder);
this.pageDiv = pageDiv;
this.pdfPage = pdfPage;
this.linkService = linkService;
this.downloadManager = downloadManager;
this.renderInteractiveForms = renderInteractiveForms;
this.l10n = l10n;
this.div = null;
}
_createClass(AnnotationLayerBuilder, [{
key: 'render',
value: function render(viewport) {
var _this = this;
var intent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'display';
this.pdfPage.getAnnotations({ intent: intent }).then(function (annotations) {
var parameters = {
viewport: viewport.clone({ dontFlip: true }),
div: _this.div,
annotations: annotations,
page: _this.pdfPage,
renderInteractiveForms: _this.renderInteractiveForms,
linkService: _this.linkService,
downloadManager: _this.downloadManager
};
if (_this.div) {
_pdfjsLib.AnnotationLayer.update(parameters);
} else {
if (annotations.length === 0) {
return;
}
_this.div = document.createElement('div');
_this.div.className = 'annotationLayer';
_this.pageDiv.appendChild(_this.div);
parameters.div = _this.div;
_pdfjsLib.AnnotationLayer.render(parameters);
_this.l10n.translate(_this.div);
}
});
}
}, {
key: 'hide',
value: function hide() {
if (!this.div) {
return;
}
this.div.setAttribute('hidden', 'true');
}
}]);
return AnnotationLayerBuilder;
}();
var DefaultAnnotationLayerFactory = function () {
function DefaultAnnotationLayerFactory() {
_classCallCheck(this, DefaultAnnotationLayerFactory);
}
_createClass(DefaultAnnotationLayerFactory, [{
key: 'createAnnotationLayerBuilder',
value: function createAnnotationLayerBuilder(pageDiv, pdfPage) {
var renderInteractiveForms = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var l10n = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _ui_utils.NullL10n;
return new AnnotationLayerBuilder({
pageDiv: pageDiv,
pdfPage: pdfPage,
renderInteractiveForms: renderInteractiveForms,
linkService: new _pdf_link_service.SimpleLinkService(),
l10n: l10n
});
}
}]);
return DefaultAnnotationLayerFactory;
}();
exports.AnnotationLayerBuilder = AnnotationLayerBuilder;
exports.DefaultAnnotationLayerFactory = DefaultAnnotationLayerFactory;
/***/ }),
/* 5 */
/***/ (function(module, exports, __w_pdfjs_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PDFPageView = undefined;
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 _ui_utils = __w_pdfjs_require__(1);
var _pdfjsLib = __w_pdfjs_require__(0);
var _dom_events = __w_pdfjs_require__(2);
var _pdf_rendering_queue = __w_pdfjs_require__(7);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var PDFPageView = function () {
function PDFPageView(options) {
_classCallCheck(this, PDFPageView);
var container = options.container;
var defaultViewport = options.defaultViewport;
this.id = options.id;
this.renderingId = 'page' + this.id;
this.pageLabel = null;
this.rotation = 0;
this.scale = options.scale || _ui_utils.DEFAULT_SCALE;
this.viewport = defaultViewport;
this.pdfPageRotate = defaultViewport.rotation;
this.hasRestrictedScaling = false;
this.enhanceTextSelection = options.enhanceTextSelection || false;
this.renderInteractiveForms = options.renderInteractiveForms || false;
this.eventBus = options.eventBus || (0, _dom_events.getGlobalEventBus)();
this.renderingQueue = options.renderingQueue;
this.textLayerFactory = options.textLayerFactory;
this.annotationLayerFactory = options.annotationLayerFactory;
this.renderer = options.renderer || _ui_utils.RendererType.CANVAS;
this.l10n = options.l10n || _ui_utils.NullL10n;
this.paintTask = null;
this.paintedViewportMap = new WeakMap();
this.renderingState = _pdf_rendering_queue.RenderingStates.INITIAL;
this.resume = null;
this.error = null;
this.onBeforeDraw = null;
this.onAfterDraw = null;
this.annotationLayer = null;
this.textLayer = null;
this.zoomLayer = null;
var div = document.createElement('div');
div.className = 'page';
div.style.width = Math.floor(this.viewport.width) + 'px';
div.style.height = Math.floor(this.viewport.height) + 'px';
div.setAttribute('data-page-number', this.id);
this.div = div;
container.appendChild(div);
}
_createClass(PDFPageView, [{
key: 'setPdfPage',
value: function setPdfPage(pdfPage) {
this.pdfPage = pdfPage;
this.pdfPageRotate = pdfPage.rotate;
var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
this.viewport = pdfPage.getViewport(this.scale * _ui_utils.CSS_UNITS, totalRotation);
this.stats = pdfPage.stats;
this.reset();
}
}, {
key: 'destroy',
value: function destroy() {
this.reset();
if (this.pdfPage) {
this.pdfPage.cleanup();
}
}
}, {
key: '_resetZoomLayer',
value: function _resetZoomLayer() {
var removeFromDOM = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (!this.zoomLayer) {
return;
}
var zoomLayerCanvas = this.zoomLayer.firstChild;
this.paintedViewportMap.delete(zoomLayerCanvas);
zoomLayerCanvas.width = 0;
zoomLayerCanvas.height = 0;
if (removeFromDOM) {
this.zoomLayer.remove();
}
this.zoomLayer = null;
}
}, {
key: 'reset',
value: function reset() {
var keepZoomLayer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var keepAnnotations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
this.cancelRendering();
var div = this.div;
div.style.width = Math.floor(this.viewport.width) + 'px';
div.style.height = Math.floor(this.viewport.height) + 'px';
var childNodes = div.childNodes;
var currentZoomLayerNode = keepZoomLayer && this.zoomLayer || null;
var currentAnnotationNode = keepAnnotations && this.annotationLayer && this.annotationLayer.div || null;
for (var i = childNodes.length - 1; i >= 0; i--) {
var node = childNodes[i];
if (currentZoomLayerNode === node || currentAnnotationNode === node) {
continue;
}
div.removeChild(node);
}
div.removeAttribute('data-loaded');
if (currentAnnotationNode) {
this.annotationLayer.hide();
} else {
this.annotationLayer = null;
}
if (!currentZoomLayerNode) {
if (this.canvas) {
this.paintedViewportMap.delete(this.canvas);
this.canvas.width = 0;
this.canvas.height = 0;
delete this.canvas;
}
this._resetZoomLayer();
}
if (this.svg) {
this.paintedViewportMap.delete(this.svg);
delete this.svg;
}
this.loadingIconDiv = document.createElement('div');
this.loadingIconDiv.className = 'loadingIcon';
div.appendChild(this.loadingIconDiv);
}
}, {
key: 'update',
value: function update(scale, rotation) {
this.scale = scale || this.scale;
if (typeof rotation !== 'undefined') {
this.rotation = rotation;
}
var totalRotation = (this.rotation + this.pdfPageRotate) % 360;
this.viewport = this.viewport.clone({
scale: this.scale * _ui_utils.CSS_UNITS,
rotation: totalRotation
});
if (this.svg) {
this.cssTransform(this.svg, true);
this.eventBus.dispatch('pagerendered', {
source: this,
pageNumber: this.id,
cssTransform: true
});
return;
}
var isScalingRestricted = false;
if (this.canvas && _pdfjsLib.PDFJS.maxCanvasPixels > 0) {
var outputScale = this.outputScale;
if ((Math.floor(this.viewport.width) * outputScale.sx | 0) * (Math.floor(this.viewport.height) * outputScale.sy | 0) > _pdfjsLib.PDFJS.maxCanvasPixels) {
isScalingRestricted = true;
}
}
if (this.canvas) {
if (_pdfjsLib.PDFJS.useOnlyCssZoom || this.hasRestrictedScaling && isScalingRestricted) {
this.cssTransform(this.canvas, true);
this.eventBus.dispatch('pagerendered', {
source: this,
pageNumber: this.id,
cssTransform: true
});
return;
}
if (!this.zoomLayer && !this.canvas.hasAttribute('hidden')) {
this.zoomLayer = this.canvas.parentNode;
this.zoomLayer.style.position = 'absolute';
}
}
if (this.zoomLayer) {
this.cssTransform(this.zoomLayer.firstChild);
}
this.reset(true, true);
}
}, {
key: 'cancelRendering',
value: function cancelRendering() {
if (this.paintTask) {
this.paintTask.cancel();
this.paintTask = null;
}
this.renderingState = _pdf_rendering_queue.RenderingStates.INITIAL;
this.resume = null;
if (this.textLayer) {
this.textLayer.cancel();
this.textLayer = null;
}
}
}, {
key: 'cssTransform',
value: function cssTransform(target) {
var redrawAnnotations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
var width = this.viewport.width;
var height = this.viewport.height;
var div = this.div;
target.style.width = target.parentNode.style.width = div.style.width = Math.floor(width) + 'px';
target.style.height = target.parentNode.style.height = div.style.height = Math.floor(height) + 'px';
var relativeRotation = this.viewport.rotation - this.paintedViewportMap.get(target).rotation;
var absRotation = Math.abs(relativeRotation);
var scaleX = 1,
scaleY = 1;
if (absRotation === 90 || absRotation === 270) {
scaleX = height / width;
scaleY = width / height;
}
var cssTransform = 'rotate(' + relativeRotation + 'deg) ' + 'scale(' + scaleX + ',' + scaleY + ')';
_pdfjsLib.CustomStyle.setProp('transform', target, cssTransform);
if (this.textLayer) {
var textLayerViewport = this.textLayer.viewport;
var textRelativeRotation = this.viewport.rotation - textLayerViewport.rotation;
var textAbsRotation = Math.abs(textRelativeRotation);
var scale = width / textLayerViewport.width;
if (textAbsRotation === 90 || textAbsRotation === 270) {
scale = width / textLayerViewport.height;
}
var textLayerDiv = this.textLayer.textLayerDiv;
var transX = void 0,
transY = void 0;
switch (textAbsRotation) {
case 0:
transX = transY = 0;
break;
case 90:
transX = 0;
transY = '-' + textLayerDiv.style.height;
break;
case 180:
transX = '-' + textLayerDiv.style.width;
transY = '-' + textLayerDiv.style.height;
break;
case 270:
transX = '-' + textLayerDiv.style.width;
transY = 0;
break;
default:
console.error('Bad rotation value.');
break;
}
_pdfjsLib.CustomStyle.setProp('transform', textLayerDiv, 'rotate(' + textAbsRotation + 'deg) ' + 'scale(' + scale + ', ' + scale + ') ' + 'translate(' + transX + ', ' + transY + ')');
_pdfjsLib.CustomStyle.setProp('transformOrigin', textLayerDiv, '0% 0%');
}
if (redrawAnnotations && this.annotationLayer) {
this.annotationLayer.render(this.viewport, 'display');
}
}
}, {
key: 'getPagePoint',
value: function getPagePoint(x, y) {
return this.viewport.convertToPdfPoint(x, y);
}
}, {
key: 'draw',
value: function draw() {
var _this = this;
if (this.renderingState !== _pdf_rendering_queue.RenderingStates.INITIAL) {
console.error('Must be in new state before drawing');
this.reset();
}
this.renderingState = _pdf_rendering_queue.RenderingStates.RUNNING;
var pdfPage = this.pdfPage;
var div = this.div;
var canvasWrapper = document.createElement('div');
canvasWrapper.style.width = div.style.width;
canvasWrapper.style.height = div.style.height;
canvasWrapper.classList.add('canvasWrapper');
if (this.annotationLayer && this.annotationLayer.div) {
div.insertBefore(canvasWrapper, this.annotationLayer.div);
} else {
div.appendChild(canvasWrapper);
}
var textLayer = null;
if (this.textLayerFactory) {
var textLayerDiv = document.createElement('div');
textLayerDiv.className = 'textLayer';
textLayerDiv.style.width = canvasWrapper.style.width;
textLayerDiv.style.height = canvasWrapper.style.height;
if (this.annotationLayer && this.annotationLayer.div) {
div.insertBefore(textLayerDiv, this.annotationLayer.div);
} else {
div.appendChild(textLayerDiv);
}
textLayer = this.textLayerFactory.createTextLayerBuilder(textLayerDiv, this.id - 1, this.viewport, this.enhanceTextSelection);
}
this.textLayer = textLayer;
var renderContinueCallback = null;
if (this.renderingQueue) {
renderContinueCallback = function renderContinueCallback(cont) {
if (!_this.renderingQueue.isHighestPriority(_this)) {
_this.renderingState = _pdf_rendering_queue.RenderingStates.PAUSED;
_this.resume = function () {
_this.renderingState = _pdf_rendering_queue.RenderingStates.RUNNING;
cont();
};
return;
}
cont();
};
}
var finishPaintTask = function finishPaintTask(error) {
if (paintTask === _this.paintTask) {
_this.paintTask = null;
}
if (error === 'cancelled' || error instanceof _pdfjsLib.RenderingCancelledException) {
_this.error = null;
return Promise.resolve(undefined);
}
_this.renderingState = _pdf_rendering_queue.RenderingStates.FINISHED;
if (_this.loadingIconDiv) {
div.removeChild(_this.loadingIconDiv);
delete _this.loadingIconDiv;
}
_this._resetZoomLayer(true);
_this.error = error;
_this.stats = pdfPage.stats;
if (_this.onAfterDraw) {
_this.onAfterDraw();
}
_this.eventBus.dispatch('pagerendered', {
source: _this,
pageNumber: _this.id,
cssTransform: false
});
if (error) {
return Promise.reject(error);
}
return Promise.resolve(undefined);
};
var paintTask = this.renderer === _ui_utils.RendererType.SVG ? this.paintOnSvg(canvasWrapper) : this.paintOnCanvas(canvasWrapper);
paintTask.onRenderContinue = renderContinueCallback;
this.paintTask = paintTask;
var resultPromise = paintTask.promise.then(function () {
return finishPaintTask(null).then(function () {
if (textLayer) {
var readableStream = pdfPage.streamTextContent({ normalizeWhitespace: true });
textLayer.setTextContentStream(readableStream);
textLayer.render();
}
});
}, function (reason) {
return finishPaintTask(reason);
});
if (this.annotationLayerFactory) {
if (!this.annotationLayer) {
this.annotationLayer = this.annotationLayerFactory.createAnnotationLayerBuilder(div, pdfPage, this.renderInteractiveForms, this.l10n);
}
this.annotationLayer.render(this.viewport, 'display');
}
div.setAttribute('data-loaded', true);
if (this.onBeforeDraw) {
this.onBeforeDraw();
}
return resultPromise;
}
}, {
key: 'paintOnCanvas',
value: function paintOnCanvas(canvasWrapper) {
var renderCapability = (0, _pdfjsLib.createPromiseCapability)();
var result = {
promise: renderCapability.promise,
onRenderContinue: function onRenderContinue(cont) {
cont();
},
cancel: function cancel() {
renderTask.cancel();
}
};
var viewport = this.viewport;
var canvas = document.createElement('canvas');
canvas.id = this.renderingId;
canvas.setAttribute('hidden', 'hidden');
var isCanvasHidden = true;
var showCanvas = function showCanvas() {
if (isCanvasHidden) {
canvas.removeAttribute('hidden');
isCanvasHidden = false;
}
};
canvasWrapper.appendChild(canvas);
this.canvas = canvas;
canvas.mozOpaque = true;
var ctx = canvas.getContext('2d', { alpha: false });
var outputScale = (0, _ui_utils.getOutputScale)(ctx);
this.outputScale = outputScale;
if (_pdfjsLib.PDFJS.useOnlyCssZoom) {
var actualSizeViewport = viewport.clone({ scale: _ui_utils.CSS_UNITS });
outputScale.sx *= actualSizeViewport.width / viewport.width;
outputScale.sy *= actualSizeViewport.height / viewport.height;
outputScale.scaled = true;
}
if (_pdfjsLib.PDFJS.maxCanvasPixels > 0) {
var pixelsInViewport = viewport.width * viewport.height;
var maxScale = Math.sqrt(_pdfjsLib.PDFJS.maxCanvasPixels / pixelsInViewport);
if (outputScale.sx > maxScale || outputScale.sy > maxScale) {
outputScale.sx = maxScale;
outputScale.sy = maxScale;
outputScale.scaled = true;
this.hasRestrictedScaling = true;
} else {
this.hasRestrictedScaling = false;
}
}
var sfx = (0, _ui_utils.approximateFraction)(outputScale.sx);
var sfy = (0, _ui_utils.approximateFraction)(outputScale.sy);
canvas.width = (0, _ui_utils.roundToDivide)(viewport.width * outputScale.sx, sfx[0]);
canvas.height = (0, _ui_utils.roundToDivide)(viewport.height * outputScale.sy, sfy[0]);
canvas.style.width = (0, _ui_utils.roundToDivide)(viewport.width, sfx[1]) + 'px';
canvas.style.height = (0, _ui_utils.roundToDivide)(viewport.height, sfy[1]) + 'px';
this.paintedViewportMap.set(canvas, viewport);
var transform = !outputScale.scaled ? null : [outputScale.sx, 0, 0, outputScale.sy, 0, 0];
var renderContext = {
canvasContext: ctx,
transform: transform,
viewport: this.viewport,
renderInteractiveForms: this.renderInteractiveForms
};
var renderTask = this.pdfPage.render(renderContext);
renderTask.onContinue = function (cont) {
showCanvas();
if (result.onRenderContinue) {
result.onRenderContinue(cont);
} else {
cont();
}
};
renderTask.promise.then(function () {
showCanvas();
renderCapability.resolve(undefined);
}, function (error) {
showCanvas();
renderCapability.reject(error);
});
return result;
}
}, {
key: 'paintOnSvg',
value: function paintOnSvg(wrapper) {
var _this2 = this;
var cancelled = false;
var ensureNotCancelled = function ensureNotCancelled() {
if (cancelled) {
if (_pdfjsLib.PDFJS.pdfjsNext) {
throw new _pdfjsLib.RenderingCancelledException('Rendering cancelled, page ' + _this2.id, 'svg');
} else {
throw 'cancelled';
}
}
};
var pdfPage = this.pdfPage;
var actualSizeViewport = this.viewport.clone({ scale: _ui_utils.CSS_UNITS });
var promise = pdfPage.getOperatorList().then(function (opList) {
ensureNotCancelled();
var svgGfx = new _pdfjsLib.SVGGraphics(pdfPage.commonObjs, pdfPage.objs);
return svgGfx.getSVG(opList, actualSizeViewport).then(function (svg) {
ensureNotCancelled();
_this2.svg = svg;
_this2.paintedViewportMap.set(svg, actualSizeViewport);
svg.style.width = wrapper.style.width;
svg.style.height = wrapper.style.height;
_this2.renderingState = _pdf_rendering_queue.RenderingStates.FINISHED;
wrapper.appendChild(svg);
});
});
return {
promise: promise,
onRenderContinue: function onRenderContinue(cont) {
cont();
},
cancel: function cancel() {
cancelled = true;
}
};
}
}, {
key: 'setPageLabel',
value: function setPageLabel(label) {
this.pageLabel = typeof label === 'string' ? label : null;
if (this.pageLabel !== null) {
this.div.setAttribute('data-page-label', this.pageLabel);
} else {
this.div.removeAttribute('data-page-label');
}
}
}, {
key: 'width',
get: function get() {
return this.viewport.width;
}
}, {
key: 'height',
get: function get() {
return this.viewport.height;
}
}]);
return PDFPageView;
}();
exports.PDFPageView = PDFPageView;
/***/ }),
/* 6 */
/***/ (function(module, exports, __w_pdfjs_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DefaultTextLayerFactory = exports.TextLayerBuilder = undefined;
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 _dom_events = __w_pdfjs_require__(2);
var _pdfjsLib = __w_pdfjs_require__(0);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var EXPAND_DIVS_TIMEOUT = 300;
var TextLayerBuilder = function () {
function TextLayerBuilder(_ref) {
var textLayerDiv = _ref.textLayerDiv,
eventBus = _ref.eventBus,
pageIndex = _ref.pageIndex,
viewport = _ref.viewport,
_ref$findController = _ref.findController,
findController = _ref$findController === undefined ? null : _ref$findController,
_ref$enhanceTextSelec = _ref.enhanceTextSelection,
enhanceTextSelection = _ref$enhanceTextSelec === undefined ? false : _ref$enhanceTextSelec;
_classCallCheck(this, TextLayerBuilder);
this.textLayerDiv = textLayerDiv;
this.eventBus = eventBus || (0, _dom_events.getGlobalEventBus)();
this.textContent = null;
this.textContentItemsStr = [];
this.textContentStream = null;
this.renderingDone = false;
this.pageIdx = pageIndex;
this.pageNumber = this.pageIdx + 1;
this.matches = [];
this.viewport = viewport;
this.textDivs = [];
this.findController = findController;
this.textLayerRenderTask = null;
this.enhanceTextSelection = enhanceTextSelection;
this._bindMouse();
}
_createClass(TextLayerBuilder, [{
key: '_finishRendering',
value: function _finishRendering() {
this.renderingDone = true;
if (!this.enhanceTextSelection) {
var endOfContent = document.createElement('div');
endOfContent.className = 'endOfContent';
this.textLayerDiv.appendChild(endOfContent);
}
this.eventBus.dispatch('textlayerrendered', {
source: this,
pageNumber: this.pageNumber,
numTextDivs: this.textDivs.length
});
}
}, {
key: 'render',
value: function render() {
var _this = this;
var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
if (!(this.textContent || this.textContentStream) || this.renderingDone) {
return;
}
this.cancel();
this.textDivs = [];
var textLayerFrag = document.createDocumentFragment();
this.textLayerRenderTask = (0, _pdfjsLib.renderTextLayer)({
textContent: this.textContent,
textContentStream: this.textContentStream,
container: textLayerFrag,
viewport: this.viewport,
textDivs: this.textDivs,
textContentItemsStr: this.textContentItemsStr,
timeout: timeout,
enhanceTextSelection: this.enhanceTextSelection
});
this.textLayerRenderTask.promise.then(function () {
_this.textLayerDiv.appendChild(textLayerFrag);
_this._finishRendering();
_this.updateMatches();
}, function (reason) {});
}
}, {
key: 'cancel',
value: function cancel() {
if (this.textLayerRenderTask) {
this.textLayerRenderTask.cancel();
this.textLayerRenderTask = null;
}
}
}, {
key: 'setTextContentStream',
value: function setTextContentStream(readableStream) {
this.cancel();
this.textContentStream = readableStream;
}
}, {
key: 'setTextContent',
value: function setTextContent(textContent) {
this.cancel();
this.textContent = textContent;
}
}, {
key: 'convertMatches',
value: function convertMatches(matches, matchesLength) {
var i = 0;
var iIndex = 0;
var textContentItemsStr = this.textContentItemsStr;
var end = textContentItemsStr.length - 1;
var queryLen = this.findController === null ? 0 : this.findController.state.query.length;
var ret = [];
if (!matches) {
return ret;
}
for (var m = 0, len = matches.length; m < len; m++) {
var matchIdx = matches[m];
while (i !== end && matchIdx >= iIndex + textContentItemsStr[i].length) {
iIndex += textContentItemsStr[i].length;
i++;
}
if (i === textContentItemsStr.length) {
console.error('Could not find a matching mapping');
}
var match = {
begin: {
divIdx: i,
offset: matchIdx - iIndex
}
};
if (matchesLength) {
matchIdx += matchesLength[m];
} else {
matchIdx += queryLen;
}
while (i !== end && matchIdx > iIndex + textContentItemsStr[i].length) {
iIndex += textContentItemsStr[i].length;
i++;
}
match.end = {
divIdx: i,
offset: matchIdx - iIndex
};
ret.push(match);
}
return ret;
}
}, {
key: 'renderMatches',
value: function renderMatches(matches) {
if (matches.length === 0) {
return;
}
var textContentItemsStr = this.textContentItemsStr;
var textDivs = this.textDivs;
var prevEnd = null;
var pageIdx = this.pageIdx;
var isSelectedPage = this.findController === null ? false : pageIdx === this.findController.selected.pageIdx;
var selectedMatchIdx = this.findController === null ? -1 : this.findController.selected.matchIdx;
var highlightAll = this.findController === null ? false : this.findController.state.highlightAll;
var infinity = {
divIdx: -1,
offset: undefined
};
function beginText(begin, className) {
var divIdx = begin.divIdx;
textDivs[divIdx].textContent = '';
appendTextToDiv(divIdx, 0, begin.offset, className);
}
function appendTextToDiv(divIdx, fromOffset, toOffset, className) {
var div = textDivs[divIdx];
var content = textContentItemsStr[divIdx].substring(fromOffset, toOffset);
var node = document.createTextNode(content);
if (className) {
var span = document.createElement('span');
span.className = className;
span.appendChild(node);
div.appendChild(span);
return;
}
div.appendChild(node);
}
var i0 = selectedMatchIdx,
i1 = i0 + 1;
if (highlightAll) {
i0 = 0;
i1 = matches.length;
} else if (!isSelectedPage) {
return;
}
for (var i = i0; i < i1; i++) {
var match = matches[i];
var begin = match.begin;
var end = match.end;
var isSelected = isSelectedPage && i === selectedMatchIdx;
var highlightSuffix = isSelected ? ' selected' : '';
if (this.findController) {
this.findController.updateMatchPosition(pageIdx, i, textDivs, begin.divIdx);
}
if (!prevEnd || begin.divIdx !== prevEnd.divIdx) {
if (prevEnd !== null) {
appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
}
beginText(begin);
} else {
appendTextToDiv(prevEnd.divIdx, prevEnd.offset, begin.offset);
}
if (begin.divIdx === end.divIdx) {
appendTextToDiv(begin.divIdx, begin.offset, end.offset, 'highlight' + highlightSuffix);
} else {
appendTextToDiv(begin.divIdx, begin.offset, infinity.offset, 'highlight begin' + highlightSuffix);
for (var n0 = begin.divIdx + 1, n1 = end.divIdx; n0 < n1; n0++) {
textDivs[n0].className = 'highlight middle' + highlightSuffix;
}
beginText(end, 'highlight end' + highlightSuffix);
}
prevEnd = end;
}
if (prevEnd) {
appendTextToDiv(prevEnd.divIdx, prevEnd.offset, infinity.offset);
}
}
}, {
key: 'updateMatches',
value: function updateMatches() {
if (!this.renderingDone) {
return;
}
var matches = this.matches;
var textDivs = this.textDivs;
var textContentItemsStr = this.textContentItemsStr;
var clearedUntilDivIdx = -1;
for (var i = 0, len = matches.length; i < len; i++) {
var match = matches[i];
var begin = Math.max(clearedUntilDivIdx, match.begin.divIdx);
for (var n = begin, end = match.end.divIdx; n <= end; n++) {
var div = textDivs[n];
div.textContent = textContentItemsStr[n];
div.className = '';
}
clearedUntilDivIdx = match.end.divIdx + 1;
}
if (this.findController === null || !this.findController.active) {
return;
}
var pageMatches = void 0,
pageMatchesLength = void 0;
if (this.findController !== null) {
pageMatches = this.findController.pageMatches[this.pageIdx] || null;
pageMatchesLength = this.findController.pageMatchesLength ? this.findController.pageMatchesLength[this.pageIdx] || null : null;
}
this.matches = this.convertMatches(pageMatches, pageMatchesLength);
this.renderMatches(this.matches);
}
}, {
key: '_bindMouse',
value: function _bindMouse() {
var _this2 = this;
var div = this.textLayerDiv;
var expandDivsTimer = null;
div.addEventListener('mousedown', function (evt) {
if (_this2.enhanceTextSelection && _this2.textLayerRenderTask) {
_this2.textLayerRenderTask.expandTextDivs(true);
if (expandDivsTimer) {
clearTimeout(expandDivsTimer);
expandDivsTimer = null;
}
return;
}
var end = div.querySelector('.endOfContent');
if (!end) {
return;
}
var adjustTop = evt.target !== div;
adjustTop = adjustTop && window.getComputedStyle(end).getPropertyValue('-moz-user-select') !== 'none';
if (adjustTop) {
var divBounds = div.getBoundingClientRect();
var r = Math.max(0, (evt.pageY - divBounds.top) / divBounds.height);
end.style.top = (r * 100).toFixed(2) + '%';
}
end.classList.add('active');
});
div.addEventListener('mouseup', function () {
if (_this2.enhanceTextSelection && _this2.textLayerRenderTask) {
expandDivsTimer = setTimeout(function () {
if (_this2.textLayerRenderTask) {
_this2.textLayerRenderTask.expandTextDivs(false);
}
expandDivsTimer = null;
}, EXPAND_DIVS_TIMEOUT);
return;
}
var end = div.querySelector('.endOfContent');
if (!end) {
return;
}
end.style.top = '';
end.classList.remove('active');
});
}
}]);
return TextLayerBuilder;
}();
var DefaultTextLayerFactory = function () {
function DefaultTextLayerFactory() {
_classCallCheck(this, DefaultTextLayerFactory);
}
_createClass(DefaultTextLayerFactory, [{
key: 'createTextLayerBuilder',
value: function createTextLayerBuilder(textLayerDiv, pageIndex, viewport) {
var enhanceTextSelection = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
return new TextLayerBuilder({
textLayerDiv: textLayerDiv,
pageIndex: pageIndex,
viewport: viewport,
enhanceTextSelection: enhanceTextSelection
});
}
}]);
return DefaultTextLayerFactory;
}();
exports.TextLayerBuilder = TextLayerBuilder;
exports.DefaultTextLayerFactory = DefaultTextLayerFactory;
/***/ }),
/* 7 */
/***/ (function(module, exports, __w_pdfjs_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
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; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var CLEANUP_TIMEOUT = 30000;
var RenderingStates = {
INITIAL: 0,
RUNNING: 1,
PAUSED: 2,
FINISHED: 3
};
var PDFRenderingQueue = function () {
function PDFRenderingQueue() {
_classCallCheck(this, PDFRenderingQueue);
this.pdfViewer = null;
this.pdfThumbnailViewer = null;
this.onIdle = null;
this.highestPriorityPage = null;
this.idleTimeout = null;
this.printing = false;
this.isThumbnailViewEnabled = false;
}
_createClass(PDFRenderingQueue, [{
key: "setViewer",
value: function setViewer(pdfViewer) {
this.pdfViewer = pdfViewer;
}
}, {
key: "setThumbnailViewer",
value: function setThumbnailViewer(pdfThumbnailViewer) {
this.pdfThumbnailViewer = pdfThumbnailViewer;
}
}, {
key: "isHighestPriority",
value: function isHighestPriority(view) {
return this.highestPriorityPage === view.renderingId;
}
}, {
key: "renderHighestPriority",
value: function renderHighestPriority(currentlyVisiblePages) {
if (this.idleTimeout) {
clearTimeout(this.idleTimeout);
this.idleTimeout = null;
}
if (this.pdfViewer.forceRendering(currentlyVisiblePages)) {
return;
}
if (this.pdfThumbnailViewer && this.isThumbnailViewEnabled) {
if (this.pdfThumbnailViewer.forceRendering()) {
return;
}
}
if (this.printing) {
return;
}
if (this.onIdle) {
this.idleTimeout = setTimeout(this.onIdle.bind(this), CLEANUP_TIMEOUT);
}
}
}, {
key: "getHighestPriority",
value: function getHighestPriority(visible, views, scrolledDown) {
var visibleViews = visible.views;
var numVisible = visibleViews.length;
if (numVisible === 0) {
return false;
}
for (var i = 0; i < numVisible; ++i) {
var view = visibleViews[i].view;
if (!this.isViewFinished(view)) {
return view;
}
}
if (scrolledDown) {
var nextPageIndex = visible.last.id;
if (views[nextPageIndex] && !this.isViewFinished(views[nextPageIndex])) {
return views[nextPageIndex];
}
} else {
var previousPageIndex = visible.first.id - 2;
if (views[previousPageIndex] && !this.isViewFinished(views[previousPageIndex])) {
return views[previousPageIndex];
}
}
return null;
}
}, {
key: "isViewFinished",
value: function isViewFinished(view) {
return view.renderingState === RenderingStates.FINISHED;
}
}, {
key: "renderView",
value: function renderView(view) {
var _this = this;
switch (view.renderingState) {
case RenderingStates.FINISHED:
return false;
case RenderingStates.PAUSED:
this.highestPriorityPage = view.renderingId;
view.resume();
break;
case RenderingStates.RUNNING:
this.highestPriorityPage = view.renderingId;
break;
case RenderingStates.INITIAL:
this.highestPriorityPage = view.renderingId;
var continueRendering = function continueRendering() {
_this.renderHighestPriority();
};
view.draw().then(continueRendering, continueRendering);
break;
}
return true;
}
}]);
return PDFRenderingQueue;
}();
exports.RenderingStates = RenderingStates;
exports.PDFRenderingQueue = PDFRenderingQueue;
/***/ }),
/* 8 */
/***/ (function(module, exports, __w_pdfjs_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DownloadManager = undefined;
var _pdfjsLib = __w_pdfjs_require__(0);
;
function download(blobUrl, filename) {
var a = document.createElement('a');
if (a.click) {
a.href = blobUrl;
a.target = '_parent';
if ('download' in a) {
a.download = filename;
}
(document.body || document.documentElement).appendChild(a);
a.click();
a.parentNode.removeChild(a);
} else {
if (window.top === window && blobUrl.split('#')[0] === window.location.href.split('#')[0]) {
var padCharacter = blobUrl.indexOf('?') === -1 ? '?' : '&';
blobUrl = blobUrl.replace(/#|$/, padCharacter + '$&');
}
window.open(blobUrl, '_parent');
}
}
function DownloadManager() {}
DownloadManager.prototype = {
downloadUrl: function DownloadManager_downloadUrl(url, filename) {
if (!(0, _pdfjsLib.createValidAbsoluteUrl)(url, 'http://example.com')) {
return;
}
download(url + '#pdfjs.action=download', filename);
},
downloadData: function DownloadManager_downloadData(data, filename, contentType) {
if (navigator.msSaveBlob) {
return navigator.msSaveBlob(new Blob([data], { type: contentType }), filename);
}
var blobUrl = (0, _pdfjsLib.createObjectURL)(data, contentType, _pdfjsLib.PDFJS.disableCreateObjectURL);
download(blobUrl, filename);
},
download: function DownloadManager_download(blob, url, filename) {
if (navigator.msSaveBlob) {
if (!navigator.msSaveBlob(blob, filename)) {
this.downloadUrl(url, filename);
}
return;
}
if (_pdfjsLib.PDFJS.disableCreateObjectURL) {
this.downloadUrl(url, filename);
return;
}
var blobUrl = URL.createObjectURL(blob);
download(blobUrl, filename);
}
};
exports.DownloadManager = DownloadManager;
/***/ }),
/* 9 */
/***/ (function(module, exports, __w_pdfjs_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.GenericL10n = undefined;
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; }; }();
__w_pdfjs_require__(13);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var webL10n = document.webL10n;
var GenericL10n = function () {
function GenericL10n(lang) {
_classCallCheck(this, GenericL10n);
this._lang = lang;
this._ready = new Promise(function (resolve, reject) {
webL10n.setLanguage(lang, function () {
resolve(webL10n);
});
});
}
_createClass(GenericL10n, [{
key: 'getDirection',
value: function getDirection() {
return this._ready.then(function (l10n) {
return l10n.getDirection();
});
}
}, {
key: 'get',
value: function get(property, args, fallback) {
return this._ready.then(function (l10n) {
return l10n.get(property, args, fallback);
});
}
}, {
key: 'translate',
value: function translate(element) {
return this._ready.then(function (l10n) {
return l10n.translate(element);
});
}
}]);
return GenericL10n;
}();
exports.GenericL10n = GenericL10n;
/***/ }),
/* 10 */
/***/ (function(module, exports, __w_pdfjs_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PDFFindController = exports.FindState = undefined;
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 _pdfjsLib = __w_pdfjs_require__(0);
var _ui_utils = __w_pdfjs_require__(1);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var FindState = {
FOUND: 0,
NOT_FOUND: 1,
WRAPPED: 2,
PENDING: 3
};
var FIND_SCROLL_OFFSET_TOP = -50;
var FIND_SCROLL_OFFSET_LEFT = -400;
var FIND_TIMEOUT = 250;
var CHARACTERS_TO_NORMALIZE = {
'\u2018': '\'',
'\u2019': '\'',
'\u201A': '\'',
'\u201B': '\'',
'\u201C': '"',
'\u201D': '"',
'\u201E': '"',
'\u201F': '"',
'\xBC': '1/4',
'\xBD': '1/2',
'\xBE': '3/4'
};
var PDFFindController = function () {
function PDFFindController(_ref) {
var pdfViewer = _ref.pdfViewer;
_classCallCheck(this, PDFFindController);
this.pdfViewer = pdfViewer;
this.onUpdateResultsCount = null;
this.onUpdateState = null;
this.reset();
var replace = Object.keys(CHARACTERS_TO_NORMALIZE).join('');
this.normalizationRegex = new RegExp('[' + replace + ']', 'g');
}
_createClass(PDFFindController, [{
key: 'reset',
value: function reset() {
var _this = this;
this.startedTextExtraction = false;
this.extractTextPromises = [];
this.pendingFindMatches = Object.create(null);
this.active = false;
this.pageContents = [];
this.pageMatches = [];
this.pageMatchesLength = null;
this.matchCount = 0;
this.selected = {
pageIdx: -1,
matchIdx: -1
};
this.offset = {
pageIdx: null,
matchIdx: null
};
this.pagesToSearch = null;
this.resumePageIdx = null;
this.state = null;
this.dirtyMatch = false;
this.findTimeout = null;
this._firstPagePromise = new Promise(function (resolve) {
_this.resolveFirstPage = resolve;
});
}
}, {
key: 'normalize',
value: function normalize(text) {
return text.replace(this.normalizationRegex, function (ch) {
return CHARACTERS_TO_NORMALIZE[ch];
});
}
}, {
key: '_prepareMatches',
value: function _prepareMatches(matchesWithLength, matches, matchesLength) {
function isSubTerm(matchesWithLength, currentIndex) {
var currentElem = matchesWithLength[currentIndex];
var nextElem = matchesWithLength[currentIndex + 1];
if (currentIndex < matchesWithLength.length - 1 && currentElem.match === nextElem.match) {
currentElem.skipped = true;
return true;
}
for (var i = currentIndex - 1; i >= 0; i--) {
var prevElem = matchesWithLength[i];
if (prevElem.skipped) {
continue;
}
if (prevElem.match + prevElem.matchLength < currentElem.match) {
break;
}
if (prevElem.match + prevElem.matchLength >= currentElem.match + currentElem.matchLength) {
currentElem.skipped = true;
return true;
}
}
return false;
}
matchesWithLength.sort(function (a, b) {
return a.match === b.match ? a.matchLength - b.matchLength : a.match - b.match;
});
for (var i = 0, len = matchesWithLength.length; i < len; i++) {
if (isSubTerm(matchesWithLength, i)) {
continue;
}
matches.push(matchesWithLength[i].match);
matchesLength.push(matchesWithLength[i].matchLength);
}
}
}, {
key: 'calcFindPhraseMatch',
value: function calcFindPhraseMatch(query, pageIndex, pageContent) {
var matches = [];
var queryLen = query.length;
var matchIdx = -queryLen;
while (true) {
matchIdx = pageContent.indexOf(query, matchIdx + queryLen);
if (matchIdx === -1) {
break;
}
matches.push(matchIdx);
}
this.pageMatches[pageIndex] = matches;
}
}, {
key: 'calcFindWordMatch',
value: function calcFindWordMatch(query, pageIndex, pageContent) {
var matchesWithLength = [];
var queryArray = query.match(/\S+/g);
for (var i = 0, len = queryArray.length; i < len; i++) {
var subquery = queryArray[i];
var subqueryLen = subquery.length;
var matchIdx = -subqueryLen;
while (true) {
matchIdx = pageContent.indexOf(subquery, matchIdx + subqueryLen);
if (matchIdx === -1) {
break;
}
matchesWithLength.push({
match: matchIdx,
matchLength: subqueryLen,
skipped: false
});
}
}
if (!this.pageMatchesLength) {
this.pageMatchesLength = [];
}
this.pageMatchesLength[pageIndex] = [];
this.pageMatches[pageIndex] = [];
this._prepareMatches(matchesWithLength, this.pageMatches[pageIndex], this.pageMatchesLength[pageIndex]);
}
}, {
key: 'calcFindMatch',
value: function calcFindMatch(pageIndex) {
var pageContent = this.normalize(this.pageContents[pageIndex]);
var query = this.normalize(this.state.query);
var caseSensitive = this.state.caseSensitive;
var phraseSearch = this.state.phraseSearch;
var queryLen = query.length;
if (queryLen === 0) {
return;
}
if (!caseSensitive) {
pageContent = pageContent.toLowerCase();
query = query.toLowerCase();
}
if (phraseSearch) {
this.calcFindPhraseMatch(query, pageIndex, pageContent);
} else {
this.calcFindWordMatch(query, pageIndex, pageContent);
}
this.updatePage(pageIndex);
if (this.resumePageIdx === pageIndex) {
this.resumePageIdx = null;
this.nextPageMatch();
}
if (this.pageMatches[pageIndex].length > 0) {
this.matchCount += this.pageMatches[pageIndex].length;
this.updateUIResultsCount();
}
}
}, {
key: 'extractText',
value: function extractText() {
var _this2 = this;
if (this.startedTextExtraction) {
return;
}
this.startedTextExtraction = true;
this.pageContents.length = 0;
var promise = Promise.resolve();
var _loop = function _loop(i, ii) {
var extractTextCapability = (0, _pdfjsLib.createPromiseCapability)();
_this2.extractTextPromises[i] = extractTextCapability.promise;
promise = promise.then(function () {
return _this2.pdfViewer.getPageTextContent(i).then(function (textContent) {
var textItems = textContent.items;
var strBuf = [];
for (var j = 0, jj = textItems.length; j < jj; j++) {
strBuf.push(textItems[j].str);
}
_this2.pageContents[i] = strBuf.join('');
extractTextCapability.resolve(i);
});
});
};
for (var i = 0, ii = this.pdfViewer.pagesCount; i < ii; i++) {
_loop(i, ii);
}
}
}, {
key: 'executeCommand',
value: function executeCommand(cmd, state) {
var _this3 = this;
if (this.state === null || cmd !== 'findagain') {
this.dirtyMatch = true;
}
this.state = state;
this.updateUIState(FindState.PENDING);
this._firstPagePromise.then(function () {
_this3.extractText();
clearTimeout(_this3.findTimeout);
if (cmd === 'find') {
_this3.findTimeout = setTimeout(_this3.nextMatch.bind(_this3), FIND_TIMEOUT);
} else {
_this3.nextMatch();
}
});
}
}, {
key: 'updatePage',
value: function updatePage(index) {
if (this.selected.pageIdx === index) {
this.pdfViewer.currentPageNumber = index + 1;
}
var page = this.pdfViewer.getPageView(index);
if (page.textLayer) {
page.textLayer.updateMatches();
}
}
}, {
key: 'nextMatch',
value: function nextMatch() {
var _this4 = this;
var previous = this.state.findPrevious;
var currentPageIndex = this.pdfViewer.currentPageNumber - 1;
var numPages = this.pdfViewer.pagesCount;
this.active = true;
if (this.dirtyMatch) {
this.dirtyMatch = false;
this.selected.pageIdx = this.selected.matchIdx = -1;
this.offset.pageIdx = currentPageIndex;
this.offset.matchIdx = null;
this.hadMatch = false;
this.resumePageIdx = null;
this.pageMatches = [];
this.matchCount = 0;
this.pageMatchesLength = null;
for (var i = 0; i < numPages; i++) {
this.updatePage(i);
if (!(i in this.pendingFindMatches)) {
this.pendingFindMatches[i] = true;
this.extractTextPromises[i].then(function (pageIdx) {
delete _this4.pendingFindMatches[pageIdx];
_this4.calcFindMatch(pageIdx);
});
}
}
}
if (this.state.query === '') {
this.updateUIState(FindState.FOUND);
return;
}
if (this.resumePageIdx) {
return;
}
var offset = this.offset;
this.pagesToSearch = numPages;
if (offset.matchIdx !== null) {
var numPageMatches = this.pageMatches[offset.pageIdx].length;
if (!previous && offset.matchIdx + 1 < numPageMatches || previous && offset.matchIdx > 0) {
this.hadMatch = true;
offset.matchIdx = previous ? offset.matchIdx - 1 : offset.matchIdx + 1;
this.updateMatch(true);
return;
}
this.advanceOffsetPage(previous);
}
this.nextPageMatch();
}
}, {
key: 'matchesReady',
value: function matchesReady(matches) {
var offset = this.offset;
var numMatches = matches.length;
var previous = this.state.findPrevious;
if (numMatches) {
this.hadMatch = true;
offset.matchIdx = previous ? numMatches - 1 : 0;
this.updateMatch(true);
return true;
}
this.advanceOffsetPage(previous);
if (offset.wrapped) {
offset.matchIdx = null;
if (this.pagesToSearch < 0) {
this.updateMatch(false);
return true;
}
}
return false;
}
}, {
key: 'updateMatchPosition',
value: function updateMatchPosition(pageIndex, matchIndex, elements, beginIdx) {
if (this.selected.matchIdx === matchIndex && this.selected.pageIdx === pageIndex) {
var spot = {
top: FIND_SCROLL_OFFSET_TOP,
left: FIND_SCROLL_OFFSET_LEFT
};
(0, _ui_utils.scrollIntoView)(elements[beginIdx], spot, true);
}
}
}, {
key: 'nextPageMatch',
value: function nextPageMatch() {
if (this.resumePageIdx !== null) {
console.error('There can only be one pending page.');
}
var matches = null;
do {
var pageIdx = this.offset.pageIdx;
matches = this.pageMatches[pageIdx];
if (!matches) {
this.resumePageIdx = pageIdx;
break;
}
} while (!this.matchesReady(matches));
}
}, {
key: 'advanceOffsetPage',
value: function advanceOffsetPage(previous) {
var offset = this.offset;
var numPages = this.extractTextPromises.length;
offset.pageIdx = previous ? offset.pageIdx - 1 : offset.pageIdx + 1;
offset.matchIdx = null;
this.pagesToSearch--;
if (offset.pageIdx >= numPages || offset.pageIdx < 0) {
offset.pageIdx = previous ? numPages - 1 : 0;
offset.wrapped = true;
}
}
}, {
key: 'updateMatch',
value: function updateMatch() {
var found = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var state = FindState.NOT_FOUND;
var wrapped = this.offset.wrapped;
this.offset.wrapped = false;
if (found) {
var previousPage = this.selected.pageIdx;
this.selected.pageIdx = this.offset.pageIdx;
this.selected.matchIdx = this.offset.matchIdx;
state = wrapped ? FindState.WRAPPED : FindState.FOUND;
if (previousPage !== -1 && previousPage !== this.selected.pageIdx) {
this.updatePage(previousPage);
}
}
this.updateUIState(state, this.state.findPrevious);
if (this.selected.pageIdx !== -1) {
this.updatePage(this.selected.pageIdx);
}
}
}, {
key: 'updateUIResultsCount',
value: function updateUIResultsCount() {
if (this.onUpdateResultsCount) {
this.onUpdateResultsCount(this.matchCount);
}
}
}, {
key: 'updateUIState',
value: function updateUIState(state, previous) {
if (this.onUpdateState) {
this.onUpdateState(state, previous, this.matchCount);
}
}
}]);
return PDFFindController;
}();
exports.FindState = FindState;
exports.PDFFindController = PDFFindController;
/***/ }),
/* 11 */
/***/ (function(module, exports, __w_pdfjs_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PDFHistory = undefined;
var _dom_events = __w_pdfjs_require__(2);
function PDFHistory(options) {
this.linkService = options.linkService;
this.eventBus = options.eventBus || (0, _dom_events.getGlobalEventBus)();
this.initialized = false;
this.initialDestination = null;
this.initialBookmark = null;
}
PDFHistory.prototype = {
initialize: function pdfHistoryInitialize(fingerprint) {
this.initialized = true;
this.reInitialized = false;
this.allowHashChange = true;
this.historyUnlocked = true;
this.isViewerInPresentationMode = false;
this.previousHash = window.location.hash.substring(1);
this.currentBookmark = '';
this.currentPage = 0;
this.updatePreviousBookmark = false;
this.previousBookmark = '';
this.previousPage = 0;
this.nextHashParam = '';
this.fingerprint = fingerprint;
this.currentUid = this.uid = 0;
this.current = {};
var state = window.history.state;
if (this._isStateObjectDefined(state)) {
if (state.target.dest) {
this.initialDestination = state.target.dest;
} else {
this.initialBookmark = state.target.hash;
}
this.currentUid = state.uid;
this.uid = state.uid + 1;
this.current = state.target;
} else {
if (state && state.fingerprint && this.fingerprint !== state.fingerprint) {
this.reInitialized = true;
}
this._pushOrReplaceState({ fingerprint: this.fingerprint }, true);
}
var self = this;
window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
if (!self.historyUnlocked) {
return;
}
if (evt.state) {
self._goTo(evt.state);
return;
}
if (self.uid === 0) {
var previousParams = self.previousHash && self.currentBookmark && self.previousHash !== self.currentBookmark ? {
hash: self.currentBookmark,
page: self.currentPage
} : { page: 1 };
replacePreviousHistoryState(previousParams, function () {
updateHistoryWithCurrentHash();
});
} else {
updateHistoryWithCurrentHash();
}
});
function updateHistoryWithCurrentHash() {
self.previousHash = window.location.hash.slice(1);
self._pushToHistory({ hash: self.previousHash }, false, true);
self._updatePreviousBookmark();
}
function replacePreviousHistoryState(params, callback) {
self.historyUnlocked = false;
self.allowHashChange = false;
window.addEventListener('popstate', rewriteHistoryAfterBack);
history.back();
function rewriteHistoryAfterBack() {
window.removeEventListener('popstate', rewriteHistoryAfterBack);
window.addEventListener('popstate', rewriteHistoryAfterForward);
self._pushToHistory(params, false, true);
history.forward();
}
function rewriteHistoryAfterForward() {
window.removeEventListener('popstate', rewriteHistoryAfterForward);
self.allowHashChange = true;
self.historyUnlocked = true;
callback();
}
}
function pdfHistoryBeforeUnload() {
var previousParams = self._getPreviousParams(null, true);
if (previousParams) {
var replacePrevious = !self.current.dest && self.current.hash !== self.previousHash;
self._pushToHistory(previousParams, false, replacePrevious);
self._updatePreviousBookmark();
}
window.removeEventListener('beforeunload', pdfHistoryBeforeUnload);
}
window.addEventListener('beforeunload', pdfHistoryBeforeUnload);
window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
window.addEventListener('beforeunload', pdfHistoryBeforeUnload);
});
self.eventBus.on('presentationmodechanged', function (e) {
self.isViewerInPresentationMode = e.active;
});
},
clearHistoryState: function pdfHistory_clearHistoryState() {
this._pushOrReplaceState(null, true);
},
_isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
return state && state.uid >= 0 && state.fingerprint && this.fingerprint === state.fingerprint && state.target && state.target.hash ? true : false;
},
_pushOrReplaceState: function pdfHistory_pushOrReplaceState(stateObj, replace) {
if (replace) {
window.history.replaceState(stateObj, '', document.URL);
} else {
window.history.pushState(stateObj, '', document.URL);
}
},
get isHashChangeUnlocked() {
if (!this.initialized) {
return true;
}
return this.allowHashChange;
},
_updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
if (this.updatePreviousBookmark && this.currentBookmark && this.currentPage) {
this.previousBookmark = this.currentBookmark;
this.previousPage = this.currentPage;
this.updatePreviousBookmark = false;
}
},
updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark, pageNum) {
if (this.initialized) {
this.currentBookmark = bookmark.substring(1);
this.currentPage = pageNum | 0;
this._updatePreviousBookmark();
}
},
updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
if (this.initialized) {
this.nextHashParam = param;
}
},
push: function pdfHistoryPush(params, isInitialBookmark) {
if (!(this.initialized && this.historyUnlocked)) {
return;
}
if (params.dest && !params.hash) {
params.hash = this.current.hash && this.current.dest && this.current.dest === params.dest ? this.current.hash : this.linkService.getDestinationHash(params.dest).split('#')[1];
}
if (params.page) {
params.page |= 0;
}
if (isInitialBookmark) {
var target = window.history.state.target;
if (!target) {
this._pushToHistory(params, false);
this.previousHash = window.location.hash.substring(1);
}
this.updatePreviousBookmark = this.nextHashParam ? false : true;
if (target) {
this._updatePreviousBookmark();
}
return;
}
if (this.nextHashParam) {
if (this.nextHashParam === params.hash) {
this.nextHashParam = null;
this.updatePreviousBookmark = true;
return;
}
this.nextHashParam = null;
}
if (params.hash) {
if (this.current.hash) {
if (this.current.hash !== params.hash) {
this._pushToHistory(params, true);
} else {
if (!this.current.page && params.page) {
this._pushToHistory(params, false, true);
}
this.updatePreviousBookmark = true;
}
} else {
this._pushToHistory(params, true);
}
} else if (this.current.page && params.page && this.current.page !== params.page) {
this._pushToHistory(params, true);
}
},
_getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage, beforeUnload) {
if (!(this.currentBookmark && this.currentPage)) {
return null;
} else if (this.updatePreviousBookmark) {
this.updatePreviousBookmark = false;
}
if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
return null;
}
if (!this.current.dest && !onlyCheckPage || beforeUnload) {
if (this.previousBookmark === this.currentBookmark) {
return null;
}
} else if (this.current.page || onlyCheckPage) {
if (this.previousPage === this.currentPage) {
return null;
}
} else {
return null;
}
var params = {
hash: this.currentBookmark,
page: this.currentPage
};
if (this.isViewerInPresentationMode) {
params.hash = null;
}
return params;
},
_stateObj: function pdfHistory_stateObj(params) {
return {
fingerprint: this.fingerprint,
uid: this.uid,
target: params
};
},
_pushToHistory: function pdfHistory_pushToHistory(params, addPrevious, overwrite) {
if (!this.initialized) {
return;
}
if (!params.hash && params.page) {
params.hash = 'page=' + params.page;
}
if (addPrevious && !overwrite) {
var previousParams = this._getPreviousParams();
if (previousParams) {
var replacePrevious = !this.current.dest && this.current.hash !== this.previousHash;
this._pushToHistory(previousParams, false, replacePrevious);
}
}
this._pushOrReplaceState(this._stateObj(params), overwrite || this.uid === 0);
this.currentUid = this.uid++;
this.current = params;
this.updatePreviousBookmark = true;
},
_goTo: function pdfHistory_goTo(state) {
if (!(this.initialized && this.historyUnlocked && this._isStateObjectDefined(state))) {
return;
}
if (!this.reInitialized && state.uid < this.currentUid) {
var previousParams = this._getPreviousParams(true);
if (previousParams) {
this._pushToHistory(this.current, false);
this._pushToHistory(previousParams, false);
this.currentUid = state.uid;
window.history.back();
return;
}
}
this.historyUnlocked = false;
if (state.target.dest) {
this.linkService.navigateTo(state.target.dest);
} else {
this.linkService.setHash(state.target.hash);
}
this.currentUid = state.uid;
if (state.uid > this.uid) {
this.uid = state.uid;
}
this.current = state.target;
this.updatePreviousBookmark = true;
var currentHash = window.location.hash.substring(1);
if (this.previousHash !== currentHash) {
this.allowHashChange = false;
}
this.previousHash = currentHash;
this.historyUnlocked = true;
},
back: function pdfHistoryBack() {
this.go(-1);
},
forward: function pdfHistoryForward() {
this.go(1);
},
go: function pdfHistoryGo(direction) {
if (this.initialized && this.historyUnlocked) {
var state = window.history.state;
if (direction === -1 && state && state.uid > 0) {
window.history.back();
} else if (direction === 1 && state && state.uid < this.uid - 1) {
window.history.forward();
}
}
}
};
exports.PDFHistory = PDFHistory;
/***/ }),
/* 12 */
/***/ (function(module, exports, __w_pdfjs_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PDFViewer = exports.PresentationModeState = undefined;
var _pdfjsLib = __w_pdfjs_require__(0);
var _ui_utils = __w_pdfjs_require__(1);
var _pdf_rendering_queue = __w_pdfjs_require__(7);
var _annotation_layer_builder = __w_pdfjs_require__(4);
var _dom_events = __w_pdfjs_require__(2);
var _pdf_page_view = __w_pdfjs_require__(5);
var _pdf_link_service = __w_pdfjs_require__(3);
var _text_layer_builder = __w_pdfjs_require__(6);
var PresentationModeState = {
UNKNOWN: 0,
NORMAL: 1,
CHANGING: 2,
FULLSCREEN: 3
};
var DEFAULT_CACHE_SIZE = 10;
var PDFViewer = function pdfViewer() {
function PDFPageViewBuffer(size) {
var data = [];
this.push = function cachePush(view) {
var i = data.indexOf(view);
if (i >= 0) {
data.splice(i, 1);
}
data.push(view);
if (data.length > size) {
data.shift().destroy();
}
};
this.resize = function (newSize) {
size = newSize;
while (data.length > size) {
data.shift().destroy();
}
};
}
function isSameScale(oldScale, newScale) {
if (newScale === oldScale) {
return true;
}
if (Math.abs(newScale - oldScale) < 1e-15) {
return true;
}
return false;
}
function isPortraitOrientation(size) {
return size.width <= size.height;
}
function PDFViewer(options) {
this.container = options.container;
this.viewer = options.viewer || options.container.firstElementChild;
this.eventBus = options.eventBus || (0, _dom_events.getGlobalEventBus)();
this.linkService = options.linkService || new _pdf_link_service.SimpleLinkService();
this.downloadManager = options.downloadManager || null;
this.removePageBorders = options.removePageBorders || false;
this.enhanceTextSelection = options.enhanceTextSelection || false;
this.renderInteractiveForms = options.renderInteractiveForms || false;
this.enablePrintAutoRotate = options.enablePrintAutoRotate || false;
this.renderer = options.renderer || _ui_utils.RendererType.CANVAS;
this.l10n = options.l10n || _ui_utils.NullL10n;
this.defaultRenderingQueue = !options.renderingQueue;
if (this.defaultRenderingQueue) {
this.renderingQueue = new _pdf_rendering_queue.PDFRenderingQueue();
this.renderingQueue.setViewer(this);
} else {
this.renderingQueue = options.renderingQueue;
}
this.scroll = (0, _ui_utils.watchScroll)(this.container, this._scrollUpdate.bind(this));
this.presentationModeState = PresentationModeState.UNKNOWN;
this._resetView();
if (this.removePageBorders) {
this.viewer.classList.add('removePageBorders');
}
}
PDFViewer.prototype = {
get pagesCount() {
return this._pages.length;
},
getPageView: function getPageView(index) {
return this._pages[index];
},
get pageViewsReady() {
return this._pageViewsReady;
},
get currentPageNumber() {
return this._currentPageNumber;
},
set currentPageNumber(val) {
if ((val | 0) !== val) {
throw new Error('Invalid page number.');
}
if (!this.pdfDocument) {
return;
}
this._setCurrentPageNumber(val, true);
},
_setCurrentPageNumber: function PDFViewer_setCurrentPageNumber(val, resetCurrentPageView) {
if (this._currentPageNumber === val) {
if (resetCurrentPageView) {
this._resetCurrentPageView();
}
return;
}
if (!(0 < val && val <= this.pagesCount)) {
console.error('PDFViewer_setCurrentPageNumber: "' + val + '" is out of bounds.');
return;
}
var arg = {
source: this,
pageNumber: val,
pageLabel: this._pageLabels && this._pageLabels[val - 1]
};
this._currentPageNumber = val;
this.eventBus.dispatch('pagechanging', arg);
this.eventBus.dispatch('pagechange', arg);
if (resetCurrentPageView) {
this._resetCurrentPageView();
}
},
get currentPageLabel() {
return this._pageLabels && this._pageLabels[this._currentPageNumber - 1];
},
set currentPageLabel(val) {
var pageNumber = val | 0;
if (this._pageLabels) {
var i = this._pageLabels.indexOf(val);
if (i >= 0) {
pageNumber = i + 1;
}
}
this.currentPageNumber = pageNumber;
},
get currentScale() {
return this._currentScale !== _ui_utils.UNKNOWN_SCALE ? this._currentScale : _ui_utils.DEFAULT_SCALE;
},
set currentScale(val) {
if (isNaN(val)) {
throw new Error('Invalid numeric scale');
}
if (!this.pdfDocument) {
return;
}
this._setScale(val, false);
},
get currentScaleValue() {
return this._currentScaleValue;
},
set currentScaleValue(val) {
if (!this.pdfDocument) {
return;
}
this._setScale(val, false);
},
get pagesRotation() {
return this._pagesRotation;
},
set pagesRotation(rotation) {
if (!(typeof rotation === 'number' && rotation % 90 === 0)) {
throw new Error('Invalid pages rotation angle.');
}
if (!this.pdfDocument) {
return;
}
this._pagesRotation = rotation;
for (var i = 0, ii = this._pages.length; i < ii; i++) {
var pageView = this._pages[i];
pageView.update(pageView.scale, rotation);
}
this._setScale(this._currentScaleValue, true);
if (this.defaultRenderingQueue) {
this.update();
}
},
setDocument: function setDocument(pdfDocument) {
var _this = this;
if (this.pdfDocument) {
this._cancelRendering();
this._resetView();
}
this.pdfDocument = pdfDocument;
if (!pdfDocument) {
return;
}
var pagesCount = pdfDocument.numPages;
var pagesCapability = (0, _pdfjsLib.createPromiseCapability)();
this.pagesPromise = pagesCapability.promise;
pagesCapability.promise.then(function () {
_this._pageViewsReady = true;
_this.eventBus.dispatch('pagesloaded', {
source: _this,
pagesCount: pagesCount
});
});
var isOnePageRenderedResolved = false;
var onePageRenderedCapability = (0, _pdfjsLib.createPromiseCapability)();
this.onePageRendered = onePageRenderedCapability.promise;
var bindOnAfterAndBeforeDraw = function bindOnAfterAndBeforeDraw(pageView) {
pageView.onBeforeDraw = function () {
_this._buffer.push(pageView);
};
pageView.onAfterDraw = function () {
if (!isOnePageRenderedResolved) {
isOnePageRenderedResolved = true;
onePageRenderedCapability.resolve();
}
};
};
var firstPagePromise = pdfDocument.getPage(1);
this.firstPagePromise = firstPagePromise;
return firstPagePromise.then(function (pdfPage) {
var scale = _this.currentScale;
var viewport = pdfPage.getViewport(scale * _ui_utils.CSS_UNITS);
for (var pageNum = 1; pageNum <= pagesCount; ++pageNum) {
var textLayerFactory = null;
if (!_pdfjsLib.PDFJS.disableTextLayer) {
textLayerFactory = _this;
}
var pageView = new _pdf_page_view.PDFPageView({
container: _this.viewer,
eventBus: _this.eventBus,
id: pageNum,
scale: scale,
defaultViewport: viewport.clone(),
renderingQueue: _this.renderingQueue,
textLayerFactory: textLayerFactory,
annotationLayerFactory: _this,
enhanceTextSelection: _this.enhanceTextSelection,
renderInteractiveForms: _this.renderInteractiveForms,
renderer: _this.renderer,
l10n: _this.l10n
});
bindOnAfterAndBeforeDraw(pageView);
_this._pages.push(pageView);
}
onePageRenderedCapability.promise.then(function () {
if (_pdfjsLib.PDFJS.disableAutoFetch) {
pagesCapability.resolve();
return;
}
var getPagesLeft = pagesCount;
var _loop = function _loop(_pageNum) {
pdfDocument.getPage(_pageNum).then(function (pdfPage) {
var pageView = _this._pages[_pageNum - 1];
if (!pageView.pdfPage) {
pageView.setPdfPage(pdfPage);
}
_this.linkService.cachePageRef(_pageNum, pdfPage.ref);
if (--getPagesLeft === 0) {
pagesCapability.resolve();
}
});
};
for (var _pageNum = 1; _pageNum <= pagesCount; ++_pageNum) {
_loop(_pageNum);
}
});
_this.eventBus.dispatch('pagesinit', { source: _this });
if (_this.defaultRenderingQueue) {
_this.update();
}
if (_this.findController) {
_this.findController.resolveFirstPage();
}
});
},
setPageLabels: function PDFViewer_setPageLabels(labels) {
if (!this.pdfDocument) {
return;
}
if (!labels) {
this._pageLabels = null;
} else if (!(labels instanceof Array && this.pdfDocument.numPages === labels.length)) {
this._pageLabels = null;
console.error('PDFViewer_setPageLabels: Invalid page labels.');
} else {
this._pageLabels = labels;
}
for (var i = 0, ii = this._pages.length; i < ii; i++) {
var pageView = this._pages[i];
var label = this._pageLabels && this._pageLabels[i];
pageView.setPageLabel(label);
}
},
_resetView: function _resetView() {
this._pages = [];
this._currentPageNumber = 1;
this._currentScale = _ui_utils.UNKNOWN_SCALE;
this._currentScaleValue = null;
this._pageLabels = null;
this._buffer = new PDFPageViewBuffer(DEFAULT_CACHE_SIZE);
this._location = null;
this._pagesRotation = 0;
this._pagesRequests = [];
this._pageViewsReady = false;
this.viewer.textContent = '';
},
_scrollUpdate: function _scrollUpdate() {
if (this.pagesCount === 0) {
return;
}
this.update();
},
_setScaleDispatchEvent: function pdfViewer_setScaleDispatchEvent(newScale, newValue, preset) {
var arg = {
source: this,
scale: newScale,
presetValue: preset ? newValue : undefined
};
this.eventBus.dispatch('scalechanging', arg);
this.eventBus.dispatch('scalechange', arg);
},
_setScaleUpdatePages: function pdfViewer_setScaleUpdatePages(newScale, newValue, noScroll, preset) {
this._currentScaleValue = newValue.toString();
if (isSameScale(this._currentScale, newScale)) {
if (preset) {
this._setScaleDispatchEvent(newScale, newValue, true);
}
return;
}
for (var i = 0, ii = this._pages.length; i < ii; i++) {
this._pages[i].update(newScale);
}
this._currentScale = newScale;
if (!noScroll) {
var page = this._currentPageNumber,
dest;
if (this._location && !_pdfjsLib.PDFJS.ignoreCurrentPositionOnZoom && !(this.isInPresentationMode || this.isChangingPresentationMode)) {
page = this._location.pageNumber;
dest = [null, { name: 'XYZ' }, this._location.left, this._location.top, null];
}
this.scrollPageIntoView({
pageNumber: page,
destArray: dest,
allowNegativeOffset: true
});
}
this._setScaleDispatchEvent(newScale, newValue, preset);
if (this.defaultRenderingQueue) {
this.update();
}
},
_setScale: function PDFViewer_setScale(value, noScroll) {
var scale = parseFloat(value);
if (scale > 0) {
this._setScaleUpdatePages(scale, value, noScroll, false);
} else {
var currentPage = this._pages[this._currentPageNumber - 1];
if (!currentPage) {
return;
}
var hPadding = this.isInPresentationMode || this.removePageBorders ? 0 : _ui_utils.SCROLLBAR_PADDING;
var vPadding = this.isInPresentationMode || this.removePageBorders ? 0 : _ui_utils.VERTICAL_PADDING;
var pageWidthScale = (this.container.clientWidth - hPadding) / currentPage.width * currentPage.scale;
var pageHeightScale = (this.container.clientHeight - vPadding) / currentPage.height * currentPage.scale;
switch (value) {
case 'page-actual':
scale = 1;
break;
case 'page-width':
scale = pageWidthScale;
break;
case 'page-height':
scale = pageHeightScale;
break;
case 'page-fit':
scale = Math.min(pageWidthScale, pageHeightScale);
break;
case 'auto':
var isLandscape = currentPage.width > currentPage.height;
var horizontalScale = isLandscape ? Math.min(pageHeightScale, pageWidthScale) : pageWidthScale;
scale = Math.min(_ui_utils.MAX_AUTO_SCALE, horizontalScale);
break;
default:
console.error('PDFViewer_setScale: "' + value + '" is an unknown zoom value.');
return;
}
this._setScaleUpdatePages(scale, value, noScroll, true);
}
},
_resetCurrentPageView: function _resetCurrentPageView() {
if (this.isInPresentationMode) {
this._setScale(this._currentScaleValue, true);
}
var pageView = this._pages[this._currentPageNumber - 1];
(0, _ui_utils.scrollIntoView)(pageView.div);
},
scrollPageIntoView: function PDFViewer_scrollPageIntoView(params) {
if (!this.pdfDocument) {
return;
}
if (arguments.length > 1 || typeof params === 'number') {
console.warn('Call of scrollPageIntoView() with obsolete signature.');
var paramObj = {};
if (typeof params === 'number') {
paramObj.pageNumber = params;
}
if (arguments[1] instanceof Array) {
paramObj.destArray = arguments[1];
}
params = paramObj;
}
var pageNumber = params.pageNumber || 0;
var dest = params.destArray || null;
var allowNegativeOffset = params.allowNegativeOffset || false;
if (this.isInPresentationMode || !dest) {
this._setCurrentPageNumber(pageNumber, true);
return;
}
var pageView = this._pages[pageNumber - 1];
if (!pageView) {
console.error('PDFViewer_scrollPageIntoView: ' + 'Invalid "pageNumber" parameter.');
return;
}
var x = 0,
y = 0;
var width = 0,
height = 0,
widthScale,
heightScale;
var changeOrientation = pageView.rotation % 180 === 0 ? false : true;
var pageWidth = (changeOrientation ? pageView.height : pageView.width) / pageView.scale / _ui_utils.CSS_UNITS;
var pageHeight = (changeOrientation ? pageView.width : pageView.height) / pageView.scale / _ui_utils.CSS_UNITS;
var scale = 0;
switch (dest[1].name) {
case 'XYZ':
x = dest[2];
y = dest[3];
scale = dest[4];
x = x !== null ? x : 0;
y = y !== null ? y : pageHeight;
break;
case 'Fit':
case 'FitB':
scale = 'page-fit';
break;
case 'FitH':
case 'FitBH':
y = dest[2];
scale = 'page-width';
if (y === null && this._location) {
x = this._location.left;
y = this._location.top;
}
break;
case 'FitV':
case 'FitBV':
x = dest[2];
width = pageWidth;
height = pageHeight;
scale = 'page-height';
break;
case 'FitR':
x = dest[2];
y = dest[3];
width = dest[4] - x;
height = dest[5] - y;
var hPadding = this.removePageBorders ? 0 : _ui_utils.SCROLLBAR_PADDING;
var vPadding = this.removePageBorders ? 0 : _ui_utils.VERTICAL_PADDING;
widthScale = (this.container.clientWidth - hPadding) / width / _ui_utils.CSS_UNITS;
heightScale = (this.container.clientHeight - vPadding) / height / _ui_utils.CSS_UNITS;
scale = Math.min(Math.abs(widthScale), Math.abs(heightScale));
break;
default:
console.error('PDFViewer_scrollPageIntoView: \'' + dest[1].name + '\' is not a valid destination type.');
return;
}
if (scale && scale !== this._currentScale) {
this.currentScaleValue = scale;
} else if (this._currentScale === _ui_utils.UNKNOWN_SCALE) {
this.currentScaleValue = _ui_utils.DEFAULT_SCALE_VALUE;
}
if (scale === 'page-fit' && !dest[4]) {
(0, _ui_utils.scrollIntoView)(pageView.div);
return;
}
var boundingRect = [pageView.viewport.convertToViewportPoint(x, y), pageView.viewport.convertToViewportPoint(x + width, y + height)];
var left = Math.min(boundingRect[0][0], boundingRect[1][0]);
var top = Math.min(boundingRect[0][1], boundingRect[1][1]);
if (!allowNegativeOffset) {
left = Math.max(left, 0);
top = Math.max(top, 0);
}
(0, _ui_utils.scrollIntoView)(pageView.div, {
left: left,
top: top
});
},
_updateLocation: function _updateLocation(firstPage) {
var currentScale = this._currentScale;
var currentScaleValue = this._currentScaleValue;
var normalizedScaleValue = parseFloat(currentScaleValue) === currentScale ? Math.round(currentScale * 10000) / 100 : currentScaleValue;
var pageNumber = firstPage.id;
var pdfOpenParams = '#page=' + pageNumber;
pdfOpenParams += '&zoom=' + normalizedScaleValue;
var currentPageView = this._pages[pageNumber - 1];
var container = this.container;
var topLeft = currentPageView.getPagePoint(container.scrollLeft - firstPage.x, container.scrollTop - firstPage.y);
var intLeft = Math.round(topLeft[0]);
var intTop = Math.round(topLeft[1]);
pdfOpenParams += ',' + intLeft + ',' + intTop;
this._location = {
pageNumber: pageNumber,
scale: normalizedScaleValue,
top: intTop,
left: intLeft,
pdfOpenParams: pdfOpenParams
};
},
update: function PDFViewer_update() {
var visible = this._getVisiblePages();
var visiblePages = visible.views;
if (visiblePages.length === 0) {
return;
}
var suggestedCacheSize = Math.max(DEFAULT_CACHE_SIZE, 2 * visiblePages.length + 1);
this._buffer.resize(suggestedCacheSize);
this.renderingQueue.renderHighestPriority(visible);
var currentId = this._currentPageNumber;
var firstPage = visible.first;
for (var i = 0, ii = visiblePages.length, stillFullyVisible = false; i < ii; ++i) {
var page = visiblePages[i];
if (page.percent < 100) {
break;
}
if (page.id === currentId) {
stillFullyVisible = true;
break;
}
}
if (!stillFullyVisible) {
currentId = visiblePages[0].id;
}
if (!this.isInPresentationMode) {
this._setCurrentPageNumber(currentId);
}
this._updateLocation(firstPage);
this.eventBus.dispatch('updateviewarea', {
source: this,
location: this._location
});
},
containsElement: function containsElement(element) {
return this.container.contains(element);
},
focus: function focus() {
this.container.focus();
},
get isInPresentationMode() {
return this.presentationModeState === PresentationModeState.FULLSCREEN;
},
get isChangingPresentationMode() {
return this.presentationModeState === PresentationModeState.CHANGING;
},
get isHorizontalScrollbarEnabled() {
return this.isInPresentationMode ? false : this.container.scrollWidth > this.container.clientWidth;
},
_getVisiblePages: function _getVisiblePages() {
if (!this.isInPresentationMode) {
return (0, _ui_utils.getVisibleElements)(this.container, this._pages, true);
}
var visible = [];
var currentPage = this._pages[this._currentPageNumber - 1];
visible.push({
id: currentPage.id,
view: currentPage
});
return {
first: currentPage,
last: currentPage,
views: visible
};
},
cleanup: function cleanup() {
for (var i = 0, ii = this._pages.length; i < ii; i++) {
if (this._pages[i] && this._pages[i].renderingState !== _pdf_rendering_queue.RenderingStates.FINISHED) {
this._pages[i].reset();
}
}
},
_cancelRendering: function PDFViewer_cancelRendering() {
for (var i = 0, ii = this._pages.length; i < ii; i++) {
if (this._pages[i]) {
this._pages[i].cancelRendering();
}
}
},
_ensurePdfPageLoaded: function _ensurePdfPageLoaded(pageView) {
var _this2 = this;
if (pageView.pdfPage) {
return Promise.resolve(pageView.pdfPage);
}
var pageNumber = pageView.id;
if (this._pagesRequests[pageNumber]) {
return this._pagesRequests[pageNumber];
}
var promise = this.pdfDocument.getPage(pageNumber).then(function (pdfPage) {
if (!pageView.pdfPage) {
pageView.setPdfPage(pdfPage);
}
_this2._pagesRequests[pageNumber] = null;
return pdfPage;
});
this._pagesRequests[pageNumber] = promise;
return promise;
},
forceRendering: function forceRendering(currentlyVisiblePages) {
var _this3 = this;
var visiblePages = currentlyVisiblePages || this._getVisiblePages();
var pageView = this.renderingQueue.getHighestPriority(visiblePages, this._pages, this.scroll.down);
if (pageView) {
this._ensurePdfPageLoaded(pageView).then(function () {
_this3.renderingQueue.renderView(pageView);
});
return true;
}
return false;
},
getPageTextContent: function getPageTextContent(pageIndex) {
return this.pdfDocument.getPage(pageIndex + 1).then(function (page) {
return page.getTextContent({ normalizeWhitespace: true });
});
},
createTextLayerBuilder: function createTextLayerBuilder(textLayerDiv, pageIndex, viewport) {
var enhanceTextSelection = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
return new _text_layer_builder.TextLayerBuilder({
textLayerDiv: textLayerDiv,
eventBus: this.eventBus,
pageIndex: pageIndex,
viewport: viewport,
findController: this.isInPresentationMode ? null : this.findController,
enhanceTextSelection: this.isInPresentationMode ? false : enhanceTextSelection
});
},
createAnnotationLayerBuilder: function createAnnotationLayerBuilder(pageDiv, pdfPage) {
var renderInteractiveForms = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
var l10n = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _ui_utils.NullL10n;
return new _annotation_layer_builder.AnnotationLayerBuilder({
pageDiv: pageDiv,
pdfPage: pdfPage,
renderInteractiveForms: renderInteractiveForms,
linkService: this.linkService,
downloadManager: this.downloadManager,
l10n: l10n
});
},
setFindController: function setFindController(findController) {
this.findController = findController;
},
getPagesOverview: function getPagesOverview() {
var pagesOverview = this._pages.map(function (pageView) {
var viewport = pageView.pdfPage.getViewport(1);
return {
width: viewport.width,
height: viewport.height,
rotation: viewport.rotation
};
});
if (!this.enablePrintAutoRotate) {
return pagesOverview;
}
var isFirstPagePortrait = isPortraitOrientation(pagesOverview[0]);
return pagesOverview.map(function (size) {
if (isFirstPagePortrait === isPortraitOrientation(size)) {
return size;
}
return {
width: size.height,
height: size.width,
rotation: (size.rotation + 90) % 360
};
});
}
};
return PDFViewer;
}();
exports.PresentationModeState = PresentationModeState;
exports.PDFViewer = PDFViewer;
/***/ }),
/* 13 */
/***/ (function(module, exports, __w_pdfjs_require__) {
"use strict";
document.webL10n = function (window, document, undefined) {
var gL10nData = {};
var gTextData = '';
var gTextProp = 'textContent';
var gLanguage = '';
var gMacros = {};
var gReadyState = 'loading';
var gAsyncResourceLoading = true;
function getL10nResourceLinks() {
return document.querySelectorAll('link[type="application/l10n"]');
}
function getL10nDictionary() {
var script = document.querySelector('script[type="application/l10n"]');
return script ? JSON.parse(script.innerHTML) : null;
}
function getTranslatableChildren(element) {
return element ? element.querySelectorAll('*[data-l10n-id]') : [];
}
function getL10nAttributes(element) {
if (!element) return {};
var l10nId = element.getAttribute('data-l10n-id');
var l10nArgs = element.getAttribute('data-l10n-args');
var args = {};
if (l10nArgs) {
try {
args = JSON.parse(l10nArgs);
} catch (e) {
console.warn('could not parse arguments for #' + l10nId);
}
}
return {
id: l10nId,
args: args
};
}
function fireL10nReadyEvent(lang) {
var evtObject = document.createEvent('Event');
evtObject.initEvent('localized', true, false);
evtObject.language = lang;
document.dispatchEvent(evtObject);
}
function xhrLoadText(url, onSuccess, onFailure) {
onSuccess = onSuccess || function _onSuccess(data) {};
onFailure = onFailure || function _onFailure() {};
var xhr = new XMLHttpRequest();
xhr.open('GET', url, gAsyncResourceLoading);
if (xhr.overrideMimeType) {
xhr.overrideMimeType('text/plain; charset=utf-8');
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200 || xhr.status === 0) {
onSuccess(xhr.responseText);
} else {
onFailure();
}
}
};
xhr.onerror = onFailure;
xhr.ontimeout = onFailure;
try {
xhr.send(null);
} catch (e) {
onFailure();
}
}
function parseResource(href, lang, successCallback, failureCallback) {
var baseURL = href.replace(/[^\/]*$/, '') || './';
function evalString(text) {
if (text.lastIndexOf('\\') < 0) return text;
return text.replace(/\\\\/g, '\\').replace(/\\n/g, '\n').replace(/\\r/g, '\r').replace(/\\t/g, '\t').replace(/\\b/g, '\b').replace(/\\f/g, '\f').replace(/\\{/g, '{').replace(/\\}/g, '}').replace(/\\"/g, '"').replace(/\\'/g, "'");
}
function parseProperties(text, parsedPropertiesCallback) {
var dictionary = {};
var reBlank = /^\s*|\s*$/;
var reComment = /^\s*#|^\s*$/;
var reSection = /^\s*\[(.*)\]\s*$/;
var reImport = /^\s*@import\s+url\((.*)\)\s*$/i;
var reSplit = /^([^=\s]*)\s*=\s*(.+)$/;
function parseRawLines(rawText, extendedSyntax, parsedRawLinesCallback) {
var entries = rawText.replace(reBlank, '').split(/[\r\n]+/);
var currentLang = '*';
var genericLang = lang.split('-', 1)[0];
var skipLang = false;
var match = '';
function nextEntry() {
while (true) {
if (!entries.length) {
parsedRawLinesCallback();
return;
}
var line = entries.shift();
if (reComment.test(line)) continue;
if (extendedSyntax) {
match = reSection.exec(line);
if (match) {
currentLang = match[1].toLowerCase();
skipLang = currentLang !== '*' && currentLang !== lang && currentLang !== genericLang;
continue;
} else if (skipLang) {
continue;
}
match = reImport.exec(line);
if (match) {
loadImport(baseURL + match[1], nextEntry);
return;
}
}
var tmp = line.match(reSplit);
if (tmp && tmp.length == 3) {
dictionary[tmp[1]] = evalString(tmp[2]);
}
}
}
nextEntry();
}
function loadImport(url, callback) {
xhrLoadText(url, function (content) {
parseRawLines(content, false, callback);
}, function () {
console.warn(url + ' not found.');
callback();
});
}
parseRawLines(text, true, function () {
parsedPropertiesCallback(dictionary);
});
}
xhrLoadText(href, function (response) {
gTextData += response;
parseProperties(response, function (data) {
for (var key in data) {
var id,
prop,
index = key.lastIndexOf('.');
if (index > 0) {
id = key.substring(0, index);
prop = key.substr(index + 1);
} else {
id = key;
prop = gTextProp;
}
if (!gL10nData[id]) {
gL10nData[id] = {};
}
gL10nData[id][prop] = data[key];
}
if (successCallback) {
successCallback();
}
});
}, failureCallback);
}
function loadLocale(lang, callback) {
if (lang) {
lang = lang.toLowerCase();
}
callback = callback || function _callback() {};
clear();
gLanguage = lang;
var langLinks = getL10nResourceLinks();
var langCount = langLinks.length;
if (langCount === 0) {
var dict = getL10nDictionary();
if (dict && dict.locales && dict.default_locale) {
console.log('using the embedded JSON directory, early way out');
gL10nData = dict.locales[lang];
if (!gL10nData) {
var defaultLocale = dict.default_locale.toLowerCase();
for (var anyCaseLang in dict.locales) {
anyCaseLang = anyCaseLang.toLowerCase();
if (anyCaseLang === lang) {
gL10nData = dict.locales[lang];
break;
} else if (anyCaseLang === defaultLocale) {
gL10nData = dict.locales[defaultLocale];
}
}
}
callback();
} else {
console.log('no resource to load, early way out');
}
fireL10nReadyEvent(lang);
gReadyState = 'complete';
return;
}
var onResourceLoaded = null;
var gResourceCount = 0;
onResourceLoaded = function onResourceLoaded() {
gResourceCount++;
if (gResourceCount >= langCount) {
callback();
fireL10nReadyEvent(lang);
gReadyState = 'complete';
}
};
function L10nResourceLink(link) {
var href = link.href;
this.load = function (lang, callback) {
parseResource(href, lang, callback, function () {
console.warn(href + ' not found.');
console.warn('"' + lang + '" resource not found');
gLanguage = '';
callback();
});
};
}
for (var i = 0; i < langCount; i++) {
var resource = new L10nResourceLink(langLinks[i]);
resource.load(lang, onResourceLoaded);
}
}
function clear() {
gL10nData = {};
gTextData = '';
gLanguage = '';
}
function getPluralRules(lang) {
var locales2rules = {
'af': 3,
'ak': 4,
'am': 4,
'ar': 1,
'asa': 3,
'az': 0,
'be': 11,
'bem': 3,
'bez': 3,
'bg': 3,
'bh': 4,
'bm': 0,
'bn': 3,
'bo': 0,
'br': 20,
'brx': 3,
'bs': 11,
'ca': 3,
'cgg': 3,
'chr': 3,
'cs': 12,
'cy': 17,
'da': 3,
'de': 3,
'dv': 3,
'dz': 0,
'ee': 3,
'el': 3,
'en': 3,
'eo': 3,
'es': 3,
'et': 3,
'eu': 3,
'fa': 0,
'ff': 5,
'fi': 3,
'fil': 4,
'fo': 3,
'fr': 5,
'fur': 3,
'fy': 3,
'ga': 8,
'gd': 24,
'gl': 3,
'gsw': 3,
'gu': 3,
'guw': 4,
'gv': 23,
'ha': 3,
'haw': 3,
'he': 2,
'hi': 4,
'hr': 11,
'hu': 0,
'id': 0,
'ig': 0,
'ii': 0,
'is': 3,
'it': 3,
'iu': 7,
'ja': 0,
'jmc': 3,
'jv': 0,
'ka': 0,
'kab': 5,
'kaj': 3,
'kcg': 3,
'kde': 0,
'kea': 0,
'kk': 3,
'kl': 3,
'km': 0,
'kn': 0,
'ko': 0,
'ksb': 3,
'ksh': 21,
'ku': 3,
'kw': 7,
'lag': 18,
'lb': 3,
'lg': 3,
'ln': 4,
'lo': 0,
'lt': 10,
'lv': 6,
'mas': 3,
'mg': 4,
'mk': 16,
'ml': 3,
'mn': 3,
'mo': 9,
'mr': 3,
'ms': 0,
'mt': 15,
'my': 0,
'nah': 3,
'naq': 7,
'nb': 3,
'nd': 3,
'ne': 3,
'nl': 3,
'nn': 3,
'no': 3,
'nr': 3,
'nso': 4,
'ny': 3,
'nyn': 3,
'om': 3,
'or': 3,
'pa': 3,
'pap': 3,
'pl': 13,
'ps': 3,
'pt': 3,
'rm': 3,
'ro': 9,
'rof': 3,
'ru': 11,
'rwk': 3,
'sah': 0,
'saq': 3,
'se': 7,
'seh': 3,
'ses': 0,
'sg': 0,
'sh': 11,
'shi': 19,
'sk': 12,
'sl': 14,
'sma': 7,
'smi': 7,
'smj': 7,
'smn': 7,
'sms': 7,
'sn': 3,
'so': 3,
'sq': 3,
'sr': 11,
'ss': 3,
'ssy': 3,
'st': 3,
'sv': 3,
'sw': 3,
'syr': 3,
'ta': 3,
'te': 3,
'teo': 3,
'th': 0,
'ti': 4,
'tig': 3,
'tk': 3,
'tl': 4,
'tn': 3,
'to': 0,
'tr': 0,
'ts': 3,
'tzm': 22,
'uk': 11,
'ur': 3,
've': 3,
'vi': 0,
'vun': 3,
'wa': 4,
'wae': 3,
'wo': 0,
'xh': 3,
'xog': 3,
'yo': 0,
'zh': 0,
'zu': 3
};
function isIn(n, list) {
return list.indexOf(n) !== -1;
}
function isBetween(n, start, end) {
return start <= n && n <= end;
}
var pluralRules = {
'0': function _(n) {
return 'other';
},
'1': function _(n) {
if (isBetween(n % 100, 3, 10)) return 'few';
if (n === 0) return 'zero';
if (isBetween(n % 100, 11, 99)) return 'many';
if (n == 2) return 'two';
if (n == 1) return 'one';
return 'other';
},
'2': function _(n) {
if (n !== 0 && n % 10 === 0) return 'many';
if (n == 2) return 'two';
if (n == 1) return 'one';
return 'other';
},
'3': function _(n) {
if (n == 1) return 'one';
return 'other';
},
'4': function _(n) {
if (isBetween(n, 0, 1)) return 'one';
return 'other';
},
'5': function _(n) {
if (isBetween(n, 0, 2) && n != 2) return 'one';
return 'other';
},
'6': function _(n) {
if (n === 0) return 'zero';
if (n % 10 == 1 && n % 100 != 11) return 'one';
return 'other';
},
'7': function _(n) {
if (n == 2) return 'two';
if (n == 1) return 'one';
return 'other';
},
'8': function _(n) {
if (isBetween(n, 3, 6)) return 'few';
if (isBetween(n, 7, 10)) return 'many';
if (n == 2) return 'two';
if (n == 1) return 'one';
return 'other';
},
'9': function _(n) {
if (n === 0 || n != 1 && isBetween(n % 100, 1, 19)) return 'few';
if (n == 1) return 'one';
return 'other';
},
'10': function _(n) {
if (isBetween(n % 10, 2, 9) && !isBetween(n % 100, 11, 19)) return 'few';
if (n % 10 == 1 && !isBetween(n % 100, 11, 19)) return 'one';
return 'other';
},
'11': function _(n) {
if (isBetween(n % 10, 2, 4) && !isBetween(n % 100, 12, 14)) return 'few';
if (n % 10 === 0 || isBetween(n % 10, 5, 9) || isBetween(n % 100, 11, 14)) return 'many';
if (n % 10 == 1 && n % 100 != 11) return 'one';
return 'other';
},
'12': function _(n) {
if (isBetween(n, 2, 4)) return 'few';
if (n == 1) return 'one';
return 'other';
},
'13': function _(n) {
if (isBetween(n % 10, 2, 4) && !isBetween(n % 100, 12, 14)) return 'few';
if (n != 1 && isBetween(n % 10, 0, 1) || isBetween(n % 10, 5, 9) || isBetween(n % 100, 12, 14)) return 'many';
if (n == 1) return 'one';
return 'other';
},
'14': function _(n) {
if (isBetween(n % 100, 3, 4)) return 'few';
if (n % 100 == 2) return 'two';
if (n % 100 == 1) return 'one';
return 'other';
},
'15': function _(n) {
if (n === 0 || isBetween(n % 100, 2, 10)) return 'few';
if (isBetween(n % 100, 11, 19)) return 'many';
if (n == 1) return 'one';
return 'other';
},
'16': function _(n) {
if (n % 10 == 1 && n != 11) return 'one';
return 'other';
},
'17': function _(n) {
if (n == 3) return 'few';
if (n === 0) return 'zero';
if (n == 6) return 'many';
if (n == 2) return 'two';
if (n == 1) return 'one';
return 'other';
},
'18': function _(n) {
if (n === 0) return 'zero';
if (isBetween(n, 0, 2) && n !== 0 && n != 2) return 'one';
return 'other';
},
'19': function _(n) {
if (isBetween(n, 2, 10)) return 'few';
if (isBetween(n, 0, 1)) return 'one';
return 'other';
},
'20': function _(n) {
if ((isBetween(n % 10, 3, 4) || n % 10 == 9) && !(isBetween(n % 100, 10, 19) || isBetween(n % 100, 70, 79) || isBetween(n % 100, 90, 99))) return 'few';
if (n % 1000000 === 0 && n !== 0) return 'many';
if (n % 10 == 2 && !isIn(n % 100, [12, 72, 92])) return 'two';
if (n % 10 == 1 && !isIn(n % 100, [11, 71, 91])) return 'one';
return 'other';
},
'21': function _(n) {
if (n === 0) return 'zero';
if (n == 1) return 'one';
return 'other';
},
'22': function _(n) {
if (isBetween(n, 0, 1) || isBetween(n, 11, 99)) return 'one';
return 'other';
},
'23': function _(n) {
if (isBetween(n % 10, 1, 2) || n % 20 === 0) return 'one';
return 'other';
},
'24': function _(n) {
if (isBetween(n, 3, 10) || isBetween(n, 13, 19)) return 'few';
if (isIn(n, [2, 12])) return 'two';
if (isIn(n, [1, 11])) return 'one';
return 'other';
}
};
var index = locales2rules[lang.replace(/-.*$/, '')];
if (!(index in pluralRules)) {
console.warn('plural form unknown for [' + lang + ']');
return function () {
return 'other';
};
}
return pluralRules[index];
}
gMacros.plural = function (str, param, key, prop) {
var n = parseFloat(param);
if (isNaN(n)) return str;
if (prop != gTextProp) return str;
if (!gMacros._pluralRules) {
gMacros._pluralRules = getPluralRules(gLanguage);
}
var index = '[' + gMacros._pluralRules(n) + ']';
if (n === 0 && key + '[zero]' in gL10nData) {
str = gL10nData[key + '[zero]'][prop];
} else if (n == 1 && key + '[one]' in gL10nData) {
str = gL10nData[key + '[one]'][prop];
} else if (n == 2 && key + '[two]' in gL10nData) {
str = gL10nData[key + '[two]'][prop];
} else if (key + index in gL10nData) {
str = gL10nData[key + index][prop];
} else if (key + '[other]' in gL10nData) {
str = gL10nData[key + '[other]'][prop];
}
return str;
};
function getL10nData(key, args, fallback) {
var data = gL10nData[key];
if (!data) {
console.warn('#' + key + ' is undefined.');
if (!fallback) {
return null;
}
data = fallback;
}
var rv = {};
for (var prop in data) {
var str = data[prop];
str = substIndexes(str, args, key, prop);
str = substArguments(str, args, key);
rv[prop] = str;
}
return rv;
}
function substIndexes(str, args, key, prop) {
var reIndex = /\{\[\s*([a-zA-Z]+)\(([a-zA-Z]+)\)\s*\]\}/;
var reMatch = reIndex.exec(str);
if (!reMatch || !reMatch.length) return str;
var macroName = reMatch[1];
var paramName = reMatch[2];
var param;
if (args && paramName in args) {
param = args[paramName];
} else if (paramName in gL10nData) {
param = gL10nData[paramName];
}
if (macroName in gMacros) {
var macro = gMacros[macroName];
str = macro(str, param, key, prop);
}
return str;
}
function substArguments(str, args, key) {
var reArgs = /\{\{\s*(.+?)\s*\}\}/g;
return str.replace(reArgs, function (matched_text, arg) {
if (args && arg in args) {
return args[arg];
}
if (arg in gL10nData) {
return gL10nData[arg];
}
console.log('argument {{' + arg + '}} for #' + key + ' is undefined.');
return matched_text;
});
}
function translateElement(element) {
var l10n = getL10nAttributes(element);
if (!l10n.id) return;
var data = getL10nData(l10n.id, l10n.args);
if (!data) {
console.warn('#' + l10n.id + ' is undefined.');
return;
}
if (data[gTextProp]) {
if (getChildElementCount(element) === 0) {
element[gTextProp] = data[gTextProp];
} else {
var children = element.childNodes;
var found = false;
for (var i = 0, l = children.length; i < l; i++) {
if (children[i].nodeType === 3 && /\S/.test(children[i].nodeValue)) {
if (found) {
children[i].nodeValue = '';
} else {
children[i].nodeValue = data[gTextProp];
found = true;
}
}
}
if (!found) {
var textNode = document.createTextNode(data[gTextProp]);
element.insertBefore(textNode, element.firstChild);
}
}
delete data[gTextProp];
}
for (var k in data) {
element[k] = data[k];
}
}
function getChildElementCount(element) {
if (element.children) {
return element.children.length;
}
if (typeof element.childElementCount !== 'undefined') {
return element.childElementCount;
}
var count = 0;
for (var i = 0; i < element.childNodes.length; i++) {
count += element.nodeType === 1 ? 1 : 0;
}
return count;
}
function translateFragment(element) {
element = element || document.documentElement;
var children = getTranslatableChildren(element);
var elementCount = children.length;
for (var i = 0; i < elementCount; i++) {
translateElement(children[i]);
}
translateElement(element);
}
return {
get: function get(key, args, fallbackString) {
var index = key.lastIndexOf('.');
var prop = gTextProp;
if (index > 0) {
prop = key.substr(index + 1);
key = key.substring(0, index);
}
var fallback;
if (fallbackString) {
fallback = {};
fallback[prop] = fallbackString;
}
var data = getL10nData(key, args, fallback);
if (data && prop in data) {
return data[prop];
}
return '{{' + key + '}}';
},
getData: function getData() {
return gL10nData;
},
getText: function getText() {
return gTextData;
},
getLanguage: function getLanguage() {
return gLanguage;
},
setLanguage: function setLanguage(lang, callback) {
loadLocale(lang, function () {
if (callback) callback();
});
},
getDirection: function getDirection() {
var rtlList = ['ar', 'he', 'fa', 'ps', 'ur'];
var shortCode = gLanguage.split('-', 1)[0];
return rtlList.indexOf(shortCode) >= 0 ? 'rtl' : 'ltr';
},
translate: translateFragment,
getReadyState: function getReadyState() {
return gReadyState;
},
ready: function ready(callback) {
if (!callback) {
return;
} else if (gReadyState == 'complete' || gReadyState == 'interactive') {
window.setTimeout(function () {
callback();
});
} else if (document.addEventListener) {
document.addEventListener('localized', function once() {
document.removeEventListener('localized', once);
callback();
});
}
}
};
}(window, document);
/***/ }),
/* 14 */
/***/ (function(module, exports, __w_pdfjs_require__) {
"use strict";
var pdfjsLib = __w_pdfjs_require__(0);
var pdfjsWebPDFViewer = __w_pdfjs_require__(12);
var pdfjsWebPDFPageView = __w_pdfjs_require__(5);
var pdfjsWebPDFLinkService = __w_pdfjs_require__(3);
var pdfjsWebTextLayerBuilder = __w_pdfjs_require__(6);
var pdfjsWebAnnotationLayerBuilder = __w_pdfjs_require__(4);
var pdfjsWebPDFHistory = __w_pdfjs_require__(11);
var pdfjsWebPDFFindController = __w_pdfjs_require__(10);
var pdfjsWebUIUtils = __w_pdfjs_require__(1);
var pdfjsWebDownloadManager = __w_pdfjs_require__(8);
var pdfjsWebGenericL10n = __w_pdfjs_require__(9);
var PDFJS = pdfjsLib.PDFJS;
PDFJS.PDFViewer = pdfjsWebPDFViewer.PDFViewer;
PDFJS.PDFPageView = pdfjsWebPDFPageView.PDFPageView;
PDFJS.PDFLinkService = pdfjsWebPDFLinkService.PDFLinkService;
PDFJS.TextLayerBuilder = pdfjsWebTextLayerBuilder.TextLayerBuilder;
PDFJS.DefaultTextLayerFactory = pdfjsWebTextLayerBuilder.DefaultTextLayerFactory;
PDFJS.AnnotationLayerBuilder = pdfjsWebAnnotationLayerBuilder.AnnotationLayerBuilder;
PDFJS.DefaultAnnotationLayerFactory = pdfjsWebAnnotationLayerBuilder.DefaultAnnotationLayerFactory;
PDFJS.PDFHistory = pdfjsWebPDFHistory.PDFHistory;
PDFJS.PDFFindController = pdfjsWebPDFFindController.PDFFindController;
PDFJS.EventBus = pdfjsWebUIUtils.EventBus;
PDFJS.DownloadManager = pdfjsWebDownloadManager.DownloadManager;
PDFJS.ProgressBar = pdfjsWebUIUtils.ProgressBar;
PDFJS.GenericL10n = pdfjsWebGenericL10n.GenericL10n;
PDFJS.NullL10n = pdfjsWebUIUtils.NullL10n;
exports.PDFJS = PDFJS;
/***/ })
/******/ ]);
});
//# sourceMappingURL=pdf_viewer.js.map | sashberd/cdnjs | ajax/libs/pdf.js/1.8.529/pdf_viewer.js | JavaScript | mit | 150,295 |
var Pos = CodeMirror.Pos;
CodeMirror.defaults.rtlMoveVisually = true;
function forEach(arr, f) {
for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]);
}
function addDoc(cm, width, height) {
var content = [], line = "";
for (var i = 0; i < width; ++i) line += "x";
for (var i = 0; i < height; ++i) content.push(line);
cm.setValue(content.join("\n"));
}
function byClassName(elt, cls) {
if (elt.getElementsByClassName) return elt.getElementsByClassName(cls);
var found = [], re = new RegExp("\\b" + cls + "\\b");
function search(elt) {
if (elt.nodeType == 3) return;
if (re.test(elt.className)) found.push(elt);
for (var i = 0, e = elt.childNodes.length; i < e; ++i)
search(elt.childNodes[i]);
}
search(elt);
return found;
}
var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent);
var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent);
var mac = /Mac/.test(navigator.platform);
var phantom = /PhantomJS/.test(navigator.userAgent);
var opera = /Opera\/\./.test(navigator.userAgent);
var opera_version = opera && navigator.userAgent.match(/Version\/(\d+\.\d+)/);
if (opera_version) opera_version = Number(opera_version);
var opera_lt10 = opera && (!opera_version || opera_version < 10);
namespace = "core_";
test("core_fromTextArea", function() {
var te = document.getElementById("code");
te.value = "CONTENT";
var cm = CodeMirror.fromTextArea(te);
is(!te.offsetHeight);
eq(cm.getValue(), "CONTENT");
cm.setValue("foo\nbar");
eq(cm.getValue(), "foo\nbar");
cm.save();
is(/^foo\r?\nbar$/.test(te.value));
cm.setValue("xxx");
cm.toTextArea();
is(te.offsetHeight);
eq(te.value, "xxx");
});
testCM("getRange", function(cm) {
eq(cm.getLine(0), "1234");
eq(cm.getLine(1), "5678");
eq(cm.getLine(2), null);
eq(cm.getLine(-1), null);
eq(cm.getRange(Pos(0, 0), Pos(0, 3)), "123");
eq(cm.getRange(Pos(0, -1), Pos(0, 200)), "1234");
eq(cm.getRange(Pos(0, 2), Pos(1, 2)), "34\n56");
eq(cm.getRange(Pos(1, 2), Pos(100, 0)), "78");
}, {value: "1234\n5678"});
testCM("replaceRange", function(cm) {
eq(cm.getValue(), "");
cm.replaceRange("foo\n", Pos(0, 0));
eq(cm.getValue(), "foo\n");
cm.replaceRange("a\nb", Pos(0, 1));
eq(cm.getValue(), "fa\nboo\n");
eq(cm.lineCount(), 3);
cm.replaceRange("xyzzy", Pos(0, 0), Pos(1, 1));
eq(cm.getValue(), "xyzzyoo\n");
cm.replaceRange("abc", Pos(0, 0), Pos(10, 0));
eq(cm.getValue(), "abc");
eq(cm.lineCount(), 1);
});
testCM("selection", function(cm) {
cm.setSelection(Pos(0, 4), Pos(2, 2));
is(cm.somethingSelected());
eq(cm.getSelection(), "11\n222222\n33");
eqPos(cm.getCursor(false), Pos(2, 2));
eqPos(cm.getCursor(true), Pos(0, 4));
cm.setSelection(Pos(1, 0));
is(!cm.somethingSelected());
eq(cm.getSelection(), "");
eqPos(cm.getCursor(true), Pos(1, 0));
cm.replaceSelection("abc", "around");
eq(cm.getSelection(), "abc");
eq(cm.getValue(), "111111\nabc222222\n333333");
cm.replaceSelection("def", "end");
eq(cm.getSelection(), "");
eqPos(cm.getCursor(true), Pos(1, 3));
cm.setCursor(Pos(2, 1));
eqPos(cm.getCursor(true), Pos(2, 1));
cm.setCursor(1, 2);
eqPos(cm.getCursor(true), Pos(1, 2));
}, {value: "111111\n222222\n333333"});
testCM("extendSelection", function(cm) {
cm.setExtending(true);
addDoc(cm, 10, 10);
cm.setSelection(Pos(3, 5));
eqPos(cm.getCursor("head"), Pos(3, 5));
eqPos(cm.getCursor("anchor"), Pos(3, 5));
cm.setSelection(Pos(2, 5), Pos(5, 5));
eqPos(cm.getCursor("head"), Pos(5, 5));
eqPos(cm.getCursor("anchor"), Pos(2, 5));
eqPos(cm.getCursor("start"), Pos(2, 5));
eqPos(cm.getCursor("end"), Pos(5, 5));
cm.setSelection(Pos(5, 5), Pos(2, 5));
eqPos(cm.getCursor("head"), Pos(2, 5));
eqPos(cm.getCursor("anchor"), Pos(5, 5));
eqPos(cm.getCursor("start"), Pos(2, 5));
eqPos(cm.getCursor("end"), Pos(5, 5));
cm.extendSelection(Pos(3, 2));
eqPos(cm.getCursor("head"), Pos(3, 2));
eqPos(cm.getCursor("anchor"), Pos(5, 5));
cm.extendSelection(Pos(6, 2));
eqPos(cm.getCursor("head"), Pos(6, 2));
eqPos(cm.getCursor("anchor"), Pos(5, 5));
cm.extendSelection(Pos(6, 3), Pos(6, 4));
eqPos(cm.getCursor("head"), Pos(6, 4));
eqPos(cm.getCursor("anchor"), Pos(5, 5));
cm.extendSelection(Pos(0, 3), Pos(0, 4));
eqPos(cm.getCursor("head"), Pos(0, 3));
eqPos(cm.getCursor("anchor"), Pos(5, 5));
cm.extendSelection(Pos(4, 5), Pos(6, 5));
eqPos(cm.getCursor("head"), Pos(6, 5));
eqPos(cm.getCursor("anchor"), Pos(4, 5));
cm.setExtending(false);
cm.extendSelection(Pos(0, 3), Pos(0, 4));
eqPos(cm.getCursor("head"), Pos(0, 3));
eqPos(cm.getCursor("anchor"), Pos(0, 4));
});
testCM("lines", function(cm) {
eq(cm.getLine(0), "111111");
eq(cm.getLine(1), "222222");
eq(cm.getLine(-1), null);
cm.replaceRange("", Pos(1, 0), Pos(2, 0))
cm.replaceRange("abc", Pos(1, 0), Pos(1));
eq(cm.getValue(), "111111\nabc");
}, {value: "111111\n222222\n333333"});
testCM("indent", function(cm) {
cm.indentLine(1);
eq(cm.getLine(1), " blah();");
cm.setOption("indentUnit", 8);
cm.indentLine(1);
eq(cm.getLine(1), "\tblah();");
cm.setOption("indentUnit", 10);
cm.setOption("tabSize", 4);
cm.indentLine(1);
eq(cm.getLine(1), "\t\t blah();");
}, {value: "if (x) {\nblah();\n}", indentUnit: 3, indentWithTabs: true, tabSize: 8});
testCM("indentByNumber", function(cm) {
cm.indentLine(0, 2);
eq(cm.getLine(0), " foo");
cm.indentLine(0, -200);
eq(cm.getLine(0), "foo");
cm.setSelection(Pos(0, 0), Pos(1, 2));
cm.indentSelection(3);
eq(cm.getValue(), " foo\n bar\nbaz");
}, {value: "foo\nbar\nbaz"});
test("core_defaults", function() {
var defsCopy = {}, defs = CodeMirror.defaults;
for (var opt in defs) defsCopy[opt] = defs[opt];
defs.indentUnit = 5;
defs.value = "uu";
defs.indentWithTabs = true;
defs.tabindex = 55;
var place = document.getElementById("testground"), cm = CodeMirror(place);
try {
eq(cm.getOption("indentUnit"), 5);
cm.setOption("indentUnit", 10);
eq(defs.indentUnit, 5);
eq(cm.getValue(), "uu");
eq(cm.getOption("indentWithTabs"), true);
eq(cm.getInputField().tabIndex, 55);
}
finally {
for (var opt in defsCopy) defs[opt] = defsCopy[opt];
place.removeChild(cm.getWrapperElement());
}
});
testCM("lineInfo", function(cm) {
eq(cm.lineInfo(-1), null);
var mark = document.createElement("span");
var lh = cm.setGutterMarker(1, "FOO", mark);
var info = cm.lineInfo(1);
eq(info.text, "222222");
eq(info.gutterMarkers.FOO, mark);
eq(info.line, 1);
eq(cm.lineInfo(2).gutterMarkers, null);
cm.setGutterMarker(lh, "FOO", null);
eq(cm.lineInfo(1).gutterMarkers, null);
cm.setGutterMarker(1, "FOO", mark);
cm.setGutterMarker(0, "FOO", mark);
cm.clearGutter("FOO");
eq(cm.lineInfo(0).gutterMarkers, null);
eq(cm.lineInfo(1).gutterMarkers, null);
}, {value: "111111\n222222\n333333"});
testCM("coords", function(cm) {
cm.setSize(null, 100);
addDoc(cm, 32, 200);
var top = cm.charCoords(Pos(0, 0));
var bot = cm.charCoords(Pos(200, 30));
is(top.left < bot.left);
is(top.top < bot.top);
is(top.top < top.bottom);
cm.scrollTo(null, 100);
var top2 = cm.charCoords(Pos(0, 0));
is(top.top > top2.top);
eq(top.left, top2.left);
});
testCM("coordsChar", function(cm) {
addDoc(cm, 35, 70);
for (var i = 0; i < 2; ++i) {
var sys = i ? "local" : "page";
for (var ch = 0; ch <= 35; ch += 5) {
for (var line = 0; line < 70; line += 5) {
cm.setCursor(line, ch);
var coords = cm.charCoords(Pos(line, ch), sys);
var pos = cm.coordsChar({left: coords.left + 1, top: coords.top + 1}, sys);
eqPos(pos, Pos(line, ch));
}
}
}
}, {lineNumbers: true});
testCM("posFromIndex", function(cm) {
cm.setValue(
"This function should\n" +
"convert a zero based index\n" +
"to line and ch."
);
var examples = [
{ index: -1, line: 0, ch: 0 }, // <- Tests clipping
{ index: 0, line: 0, ch: 0 },
{ index: 10, line: 0, ch: 10 },
{ index: 39, line: 1, ch: 18 },
{ index: 55, line: 2, ch: 7 },
{ index: 63, line: 2, ch: 15 },
{ index: 64, line: 2, ch: 15 } // <- Tests clipping
];
for (var i = 0; i < examples.length; i++) {
var example = examples[i];
var pos = cm.posFromIndex(example.index);
eq(pos.line, example.line);
eq(pos.ch, example.ch);
if (example.index >= 0 && example.index < 64)
eq(cm.indexFromPos(pos), example.index);
}
});
testCM("undo", function(cm) {
cm.replaceRange("def", Pos(0, 0), Pos(0));
eq(cm.historySize().undo, 1);
cm.undo();
eq(cm.getValue(), "abc");
eq(cm.historySize().undo, 0);
eq(cm.historySize().redo, 1);
cm.redo();
eq(cm.getValue(), "def");
eq(cm.historySize().undo, 1);
eq(cm.historySize().redo, 0);
cm.setValue("1\n\n\n2");
cm.clearHistory();
eq(cm.historySize().undo, 0);
for (var i = 0; i < 20; ++i) {
cm.replaceRange("a", Pos(0, 0));
cm.replaceRange("b", Pos(3, 0));
}
eq(cm.historySize().undo, 40);
for (var i = 0; i < 40; ++i)
cm.undo();
eq(cm.historySize().redo, 40);
eq(cm.getValue(), "1\n\n\n2");
}, {value: "abc"});
testCM("undoDepth", function(cm) {
cm.replaceRange("d", Pos(0));
cm.replaceRange("e", Pos(0));
cm.replaceRange("f", Pos(0));
cm.undo(); cm.undo(); cm.undo();
eq(cm.getValue(), "abcd");
}, {value: "abc", undoDepth: 4});
testCM("undoDoesntClearValue", function(cm) {
cm.undo();
eq(cm.getValue(), "x");
}, {value: "x"});
testCM("undoMultiLine", function(cm) {
cm.operation(function() {
cm.replaceRange("x", Pos(0, 0));
cm.replaceRange("y", Pos(1, 0));
});
cm.undo();
eq(cm.getValue(), "abc\ndef\nghi");
cm.operation(function() {
cm.replaceRange("y", Pos(1, 0));
cm.replaceRange("x", Pos(0, 0));
});
cm.undo();
eq(cm.getValue(), "abc\ndef\nghi");
cm.operation(function() {
cm.replaceRange("y", Pos(2, 0));
cm.replaceRange("x", Pos(1, 0));
cm.replaceRange("z", Pos(2, 0));
});
cm.undo();
eq(cm.getValue(), "abc\ndef\nghi", 3);
}, {value: "abc\ndef\nghi"});
testCM("undoComposite", function(cm) {
cm.replaceRange("y", Pos(1));
cm.operation(function() {
cm.replaceRange("x", Pos(0));
cm.replaceRange("z", Pos(2));
});
eq(cm.getValue(), "ax\nby\ncz\n");
cm.undo();
eq(cm.getValue(), "a\nby\nc\n");
cm.undo();
eq(cm.getValue(), "a\nb\nc\n");
cm.redo(); cm.redo();
eq(cm.getValue(), "ax\nby\ncz\n");
}, {value: "a\nb\nc\n"});
testCM("undoSelection", function(cm) {
cm.setSelection(Pos(0, 2), Pos(0, 4));
cm.replaceSelection("");
cm.setCursor(Pos(1, 0));
cm.undo();
eqPos(cm.getCursor(true), Pos(0, 2));
eqPos(cm.getCursor(false), Pos(0, 4));
cm.setCursor(Pos(1, 0));
cm.redo();
eqPos(cm.getCursor(true), Pos(0, 2));
eqPos(cm.getCursor(false), Pos(0, 2));
}, {value: "abcdefgh\n"});
testCM("undoSelectionAsBefore", function(cm) {
cm.replaceSelection("abc", "around");
cm.undo();
cm.redo();
eq(cm.getSelection(), "abc");
});
testCM("markTextSingleLine", function(cm) {
forEach([{a: 0, b: 1, c: "", f: 2, t: 5},
{a: 0, b: 4, c: "", f: 0, t: 2},
{a: 1, b: 2, c: "x", f: 3, t: 6},
{a: 4, b: 5, c: "", f: 3, t: 5},
{a: 4, b: 5, c: "xx", f: 3, t: 7},
{a: 2, b: 5, c: "", f: 2, t: 3},
{a: 2, b: 5, c: "abcd", f: 6, t: 7},
{a: 2, b: 6, c: "x", f: null, t: null},
{a: 3, b: 6, c: "", f: null, t: null},
{a: 0, b: 9, c: "hallo", f: null, t: null},
{a: 4, b: 6, c: "x", f: 3, t: 4},
{a: 4, b: 8, c: "", f: 3, t: 4},
{a: 6, b: 6, c: "a", f: 3, t: 6},
{a: 8, b: 9, c: "", f: 3, t: 6}], function(test) {
cm.setValue("1234567890");
var r = cm.markText(Pos(0, 3), Pos(0, 6), {className: "foo"});
cm.replaceRange(test.c, Pos(0, test.a), Pos(0, test.b));
var f = r.find();
eq(f && f.from.ch, test.f); eq(f && f.to.ch, test.t);
});
});
testCM("markTextMultiLine", function(cm) {
function p(v) { return v && Pos(v[0], v[1]); }
forEach([{a: [0, 0], b: [0, 5], c: "", f: [0, 0], t: [2, 5]},
{a: [0, 0], b: [0, 5], c: "foo\n", f: [1, 0], t: [3, 5]},
{a: [0, 1], b: [0, 10], c: "", f: [0, 1], t: [2, 5]},
{a: [0, 5], b: [0, 6], c: "x", f: [0, 6], t: [2, 5]},
{a: [0, 0], b: [1, 0], c: "", f: [0, 0], t: [1, 5]},
{a: [0, 6], b: [2, 4], c: "", f: [0, 5], t: [0, 7]},
{a: [0, 6], b: [2, 4], c: "aa", f: [0, 5], t: [0, 9]},
{a: [1, 2], b: [1, 8], c: "", f: [0, 5], t: [2, 5]},
{a: [0, 5], b: [2, 5], c: "xx", f: null, t: null},
{a: [0, 0], b: [2, 10], c: "x", f: null, t: null},
{a: [1, 5], b: [2, 5], c: "", f: [0, 5], t: [1, 5]},
{a: [2, 0], b: [2, 3], c: "", f: [0, 5], t: [2, 2]},
{a: [2, 5], b: [3, 0], c: "a\nb", f: [0, 5], t: [2, 5]},
{a: [2, 3], b: [3, 0], c: "x", f: [0, 5], t: [2, 3]},
{a: [1, 1], b: [1, 9], c: "1\n2\n3", f: [0, 5], t: [4, 5]}], function(test) {
cm.setValue("aaaaaaaaaa\nbbbbbbbbbb\ncccccccccc\ndddddddd\n");
var r = cm.markText(Pos(0, 5), Pos(2, 5),
{className: "CodeMirror-matchingbracket"});
cm.replaceRange(test.c, p(test.a), p(test.b));
var f = r.find();
eqPos(f && f.from, p(test.f)); eqPos(f && f.to, p(test.t));
});
});
testCM("markTextUndo", function(cm) {
var marker1, marker2, bookmark;
marker1 = cm.markText(Pos(0, 1), Pos(0, 3),
{className: "CodeMirror-matchingbracket"});
marker2 = cm.markText(Pos(0, 0), Pos(2, 1),
{className: "CodeMirror-matchingbracket"});
bookmark = cm.setBookmark(Pos(1, 5));
cm.operation(function(){
cm.replaceRange("foo", Pos(0, 2));
cm.replaceRange("bar\nbaz\nbug\n", Pos(2, 0), Pos(3, 0));
});
var v1 = cm.getValue();
cm.setValue("");
eq(marker1.find(), null); eq(marker2.find(), null); eq(bookmark.find(), null);
cm.undo();
eqPos(bookmark.find(), Pos(1, 5), "still there");
cm.undo();
var m1Pos = marker1.find(), m2Pos = marker2.find();
eqPos(m1Pos.from, Pos(0, 1)); eqPos(m1Pos.to, Pos(0, 3));
eqPos(m2Pos.from, Pos(0, 0)); eqPos(m2Pos.to, Pos(2, 1));
eqPos(bookmark.find(), Pos(1, 5));
cm.redo(); cm.redo();
eq(bookmark.find(), null);
cm.undo();
eqPos(bookmark.find(), Pos(1, 5));
eq(cm.getValue(), v1);
}, {value: "1234\n56789\n00\n"});
testCM("markTextStayGone", function(cm) {
var m1 = cm.markText(Pos(0, 0), Pos(0, 1));
cm.replaceRange("hi", Pos(0, 2));
m1.clear();
cm.undo();
eq(m1.find(), null);
}, {value: "hello"});
testCM("markTextAllowEmpty", function(cm) {
var m1 = cm.markText(Pos(0, 1), Pos(0, 2), {clearWhenEmpty: false});
is(m1.find());
cm.replaceRange("x", Pos(0, 0));
is(m1.find());
cm.replaceRange("y", Pos(0, 2));
is(m1.find());
cm.replaceRange("z", Pos(0, 3), Pos(0, 4));
is(!m1.find());
var m2 = cm.markText(Pos(0, 1), Pos(0, 2), {clearWhenEmpty: false,
inclusiveLeft: true,
inclusiveRight: true});
cm.replaceRange("q", Pos(0, 1), Pos(0, 2));
is(m2.find());
cm.replaceRange("", Pos(0, 0), Pos(0, 3));
is(!m2.find());
var m3 = cm.markText(Pos(0, 1), Pos(0, 1), {clearWhenEmpty: false});
cm.replaceRange("a", Pos(0, 3));
is(m3.find());
cm.replaceRange("b", Pos(0, 1));
is(!m3.find());
}, {value: "abcde"});
testCM("markTextStacked", function(cm) {
var m1 = cm.markText(Pos(0, 0), Pos(0, 0), {clearWhenEmpty: false});
var m2 = cm.markText(Pos(0, 0), Pos(0, 0), {clearWhenEmpty: false});
cm.replaceRange("B", Pos(0, 1));
is(m1.find() && m2.find());
}, {value: "A"});
testCM("undoPreservesNewMarks", function(cm) {
cm.markText(Pos(0, 3), Pos(0, 4));
cm.markText(Pos(1, 1), Pos(1, 3));
cm.replaceRange("", Pos(0, 3), Pos(3, 1));
var mBefore = cm.markText(Pos(0, 0), Pos(0, 1));
var mAfter = cm.markText(Pos(0, 5), Pos(0, 6));
var mAround = cm.markText(Pos(0, 2), Pos(0, 4));
cm.undo();
eqPos(mBefore.find().from, Pos(0, 0));
eqPos(mBefore.find().to, Pos(0, 1));
eqPos(mAfter.find().from, Pos(3, 3));
eqPos(mAfter.find().to, Pos(3, 4));
eqPos(mAround.find().from, Pos(0, 2));
eqPos(mAround.find().to, Pos(3, 2));
var found = cm.findMarksAt(Pos(2, 2));
eq(found.length, 1);
eq(found[0], mAround);
}, {value: "aaaa\nbbbb\ncccc\ndddd"});
testCM("markClearBetween", function(cm) {
cm.setValue("aaa\nbbb\nccc\nddd\n");
cm.markText(Pos(0, 0), Pos(2));
cm.replaceRange("aaa\nbbb\nccc", Pos(0, 0), Pos(2));
eq(cm.findMarksAt(Pos(1, 1)).length, 0);
});
testCM("deleteSpanCollapsedInclusiveLeft", function(cm) {
var from = Pos(1, 0), to = Pos(1, 1);
var m = cm.markText(from, to, {collapsed: true, inclusiveLeft: true});
// Delete collapsed span.
cm.replaceRange("", from, to);
}, {value: "abc\nX\ndef"});
testCM("bookmark", function(cm) {
function p(v) { return v && Pos(v[0], v[1]); }
forEach([{a: [1, 0], b: [1, 1], c: "", d: [1, 4]},
{a: [1, 1], b: [1, 1], c: "xx", d: [1, 7]},
{a: [1, 4], b: [1, 5], c: "ab", d: [1, 6]},
{a: [1, 4], b: [1, 6], c: "", d: null},
{a: [1, 5], b: [1, 6], c: "abc", d: [1, 5]},
{a: [1, 6], b: [1, 8], c: "", d: [1, 5]},
{a: [1, 4], b: [1, 4], c: "\n\n", d: [3, 1]},
{bm: [1, 9], a: [1, 1], b: [1, 1], c: "\n", d: [2, 8]}], function(test) {
cm.setValue("1234567890\n1234567890\n1234567890");
var b = cm.setBookmark(p(test.bm) || Pos(1, 5));
cm.replaceRange(test.c, p(test.a), p(test.b));
eqPos(b.find(), p(test.d));
});
});
testCM("bookmarkInsertLeft", function(cm) {
var br = cm.setBookmark(Pos(0, 2), {insertLeft: false});
var bl = cm.setBookmark(Pos(0, 2), {insertLeft: true});
cm.setCursor(Pos(0, 2));
cm.replaceSelection("hi");
eqPos(br.find(), Pos(0, 2));
eqPos(bl.find(), Pos(0, 4));
cm.replaceRange("", Pos(0, 4), Pos(0, 5));
cm.replaceRange("", Pos(0, 2), Pos(0, 4));
cm.replaceRange("", Pos(0, 1), Pos(0, 2));
// Verify that deleting next to bookmarks doesn't kill them
eqPos(br.find(), Pos(0, 1));
eqPos(bl.find(), Pos(0, 1));
}, {value: "abcdef"});
testCM("bookmarkCursor", function(cm) {
var pos01 = cm.cursorCoords(Pos(0, 1)), pos11 = cm.cursorCoords(Pos(1, 1)),
pos20 = cm.cursorCoords(Pos(2, 0)), pos30 = cm.cursorCoords(Pos(3, 0)),
pos41 = cm.cursorCoords(Pos(4, 1));
cm.setBookmark(Pos(0, 1), {widget: document.createTextNode("←"), insertLeft: true});
cm.setBookmark(Pos(2, 0), {widget: document.createTextNode("←"), insertLeft: true});
cm.setBookmark(Pos(1, 1), {widget: document.createTextNode("→")});
cm.setBookmark(Pos(3, 0), {widget: document.createTextNode("→")});
var new01 = cm.cursorCoords(Pos(0, 1)), new11 = cm.cursorCoords(Pos(1, 1)),
new20 = cm.cursorCoords(Pos(2, 0)), new30 = cm.cursorCoords(Pos(3, 0));
near(new01.left, pos01.left, 1);
near(new01.top, pos01.top, 1);
is(new11.left > pos11.left, "at right, middle of line");
near(new11.top == pos11.top, 1);
near(new20.left, pos20.left, 1);
near(new20.top, pos20.top, 1);
is(new30.left > pos30.left, "at right, empty line");
near(new30.top, pos30, 1);
cm.setBookmark(Pos(4, 0), {widget: document.createTextNode("→")});
is(cm.cursorCoords(Pos(4, 1)).left > pos41.left, "single-char bug");
}, {value: "foo\nbar\n\n\nx\ny"});
testCM("multiBookmarkCursor", function(cm) {
if (phantom) return;
var ms = [], m;
function add(insertLeft) {
for (var i = 0; i < 3; ++i) {
var node = document.createElement("span");
node.innerHTML = "X";
ms.push(cm.setBookmark(Pos(0, 1), {widget: node, insertLeft: insertLeft}));
}
}
var base1 = cm.cursorCoords(Pos(0, 1)).left, base4 = cm.cursorCoords(Pos(0, 4)).left;
add(true);
near(base1, cm.cursorCoords(Pos(0, 1)).left, 1);
while (m = ms.pop()) m.clear();
add(false);
near(base4, cm.cursorCoords(Pos(0, 1)).left, 1);
}, {value: "abcdefg"});
testCM("getAllMarks", function(cm) {
addDoc(cm, 10, 10);
var m1 = cm.setBookmark(Pos(0, 2));
var m2 = cm.markText(Pos(0, 2), Pos(3, 2));
var m3 = cm.markText(Pos(1, 2), Pos(1, 8));
var m4 = cm.markText(Pos(8, 0), Pos(9, 0));
eq(cm.getAllMarks().length, 4);
m1.clear();
m3.clear();
eq(cm.getAllMarks().length, 2);
});
testCM("bug577", function(cm) {
cm.setValue("a\nb");
cm.clearHistory();
cm.setValue("fooooo");
cm.undo();
});
testCM("scrollSnap", function(cm) {
cm.setSize(100, 100);
addDoc(cm, 200, 200);
cm.setCursor(Pos(100, 180));
var info = cm.getScrollInfo();
is(info.left > 0 && info.top > 0);
cm.setCursor(Pos(0, 0));
info = cm.getScrollInfo();
is(info.left == 0 && info.top == 0, "scrolled clean to top");
cm.setCursor(Pos(100, 180));
cm.setCursor(Pos(199, 0));
info = cm.getScrollInfo();
is(info.left == 0 && info.top + 2 > info.height - cm.getScrollerElement().clientHeight, "scrolled clean to bottom");
});
testCM("scrollIntoView", function(cm) {
if (phantom) return;
var outer = cm.getWrapperElement().getBoundingClientRect();
function test(line, ch, msg) {
var pos = Pos(line, ch);
cm.scrollIntoView(pos);
var box = cm.charCoords(pos, "window");
is(box.left >= outer.left, msg + " (left)");
is(box.right <= outer.right, msg + " (right)");
is(box.top >= outer.top, msg + " (top)");
is(box.bottom <= outer.bottom, msg + " (bottom)");
}
addDoc(cm, 200, 200);
test(199, 199, "bottom right");
test(0, 0, "top left");
test(100, 100, "center");
test(199, 0, "bottom left");
test(0, 199, "top right");
test(100, 100, "center again");
});
testCM("scrollBackAndForth", function(cm) {
addDoc(cm, 1, 200);
cm.operation(function() {
cm.scrollIntoView(Pos(199, 0));
cm.scrollIntoView(Pos(4, 0));
});
is(cm.getScrollInfo().top > 0);
});
testCM("selectAllNoScroll", function(cm) {
addDoc(cm, 1, 200);
cm.execCommand("selectAll");
eq(cm.getScrollInfo().top, 0);
cm.setCursor(199);
cm.execCommand("selectAll");
is(cm.getScrollInfo().top > 0);
});
testCM("selectionPos", function(cm) {
if (phantom) return;
cm.setSize(100, 100);
addDoc(cm, 200, 100);
cm.setSelection(Pos(1, 100), Pos(98, 100));
var lineWidth = cm.charCoords(Pos(0, 200), "local").left;
var lineHeight = (cm.charCoords(Pos(99)).top - cm.charCoords(Pos(0)).top) / 100;
cm.scrollTo(0, 0);
var selElt = byClassName(cm.getWrapperElement(), "CodeMirror-selected");
var outer = cm.getWrapperElement().getBoundingClientRect();
var sawMiddle, sawTop, sawBottom;
for (var i = 0, e = selElt.length; i < e; ++i) {
var box = selElt[i].getBoundingClientRect();
var atLeft = box.left - outer.left < 30;
var width = box.right - box.left;
var atRight = box.right - outer.left > .8 * lineWidth;
if (atLeft && atRight) {
sawMiddle = true;
is(box.bottom - box.top > 90 * lineHeight, "middle high");
is(width > .9 * lineWidth, "middle wide");
} else {
is(width > .4 * lineWidth, "top/bot wide enough");
is(width < .6 * lineWidth, "top/bot slim enough");
if (atLeft) {
sawBottom = true;
is(box.top - outer.top > 96 * lineHeight, "bot below");
} else if (atRight) {
sawTop = true;
is(box.top - outer.top < 2.1 * lineHeight, "top above");
}
}
}
is(sawTop && sawBottom && sawMiddle, "all parts");
}, null);
testCM("restoreHistory", function(cm) {
cm.setValue("abc\ndef");
cm.replaceRange("hello", Pos(1, 0), Pos(1));
cm.replaceRange("goop", Pos(0, 0), Pos(0));
cm.undo();
var storedVal = cm.getValue(), storedHist = cm.getHistory();
if (window.JSON) storedHist = JSON.parse(JSON.stringify(storedHist));
eq(storedVal, "abc\nhello");
cm.setValue("");
cm.clearHistory();
eq(cm.historySize().undo, 0);
cm.setValue(storedVal);
cm.setHistory(storedHist);
cm.redo();
eq(cm.getValue(), "goop\nhello");
cm.undo(); cm.undo();
eq(cm.getValue(), "abc\ndef");
});
testCM("doubleScrollbar", function(cm) {
var dummy = document.body.appendChild(document.createElement("p"));
dummy.style.cssText = "height: 50px; overflow: scroll; width: 50px";
var scrollbarWidth = dummy.offsetWidth + 1 - dummy.clientWidth;
document.body.removeChild(dummy);
if (scrollbarWidth < 2) return;
cm.setSize(null, 100);
addDoc(cm, 1, 300);
var wrap = cm.getWrapperElement();
is(wrap.offsetWidth - byClassName(wrap, "CodeMirror-lines")[0].offsetWidth <= scrollbarWidth * 1.5);
});
testCM("weirdLinebreaks", function(cm) {
cm.setValue("foo\nbar\rbaz\r\nquux\n\rplop");
is(cm.getValue(), "foo\nbar\nbaz\nquux\n\nplop");
is(cm.lineCount(), 6);
cm.setValue("\n\n");
is(cm.lineCount(), 3);
});
testCM("setSize", function(cm) {
cm.setSize(100, 100);
var wrap = cm.getWrapperElement();
is(wrap.offsetWidth, 100);
is(wrap.offsetHeight, 100);
cm.setSize("100%", "3em");
is(wrap.style.width, "100%");
is(wrap.style.height, "3em");
cm.setSize(null, 40);
is(wrap.style.width, "100%");
is(wrap.style.height, "40px");
});
function foldLines(cm, start, end, autoClear) {
return cm.markText(Pos(start, 0), Pos(end - 1), {
inclusiveLeft: true,
inclusiveRight: true,
collapsed: true,
clearOnEnter: autoClear
});
}
testCM("collapsedLines", function(cm) {
addDoc(cm, 4, 10);
var range = foldLines(cm, 4, 5), cleared = 0;
CodeMirror.on(range, "clear", function() {cleared++;});
cm.setCursor(Pos(3, 0));
CodeMirror.commands.goLineDown(cm);
eqPos(cm.getCursor(), Pos(5, 0));
cm.replaceRange("abcdefg", Pos(3, 0), Pos(3));
cm.setCursor(Pos(3, 6));
CodeMirror.commands.goLineDown(cm);
eqPos(cm.getCursor(), Pos(5, 4));
cm.replaceRange("ab", Pos(3, 0), Pos(3));
cm.setCursor(Pos(3, 2));
CodeMirror.commands.goLineDown(cm);
eqPos(cm.getCursor(), Pos(5, 2));
cm.operation(function() {range.clear(); range.clear();});
eq(cleared, 1);
});
testCM("collapsedRangeCoordsChar", function(cm) {
var pos_1_3 = cm.charCoords(Pos(1, 3));
pos_1_3.left += 2; pos_1_3.top += 2;
var opts = {collapsed: true, inclusiveLeft: true, inclusiveRight: true};
var m1 = cm.markText(Pos(0, 0), Pos(2, 0), opts);
eqPos(cm.coordsChar(pos_1_3), Pos(3, 3));
m1.clear();
var m1 = cm.markText(Pos(0, 0), Pos(1, 1), {collapsed: true, inclusiveLeft: true});
var m2 = cm.markText(Pos(1, 1), Pos(2, 0), {collapsed: true, inclusiveRight: true});
eqPos(cm.coordsChar(pos_1_3), Pos(3, 3));
m1.clear(); m2.clear();
var m1 = cm.markText(Pos(0, 0), Pos(1, 6), opts);
eqPos(cm.coordsChar(pos_1_3), Pos(3, 3));
}, {value: "123456\nabcdef\nghijkl\nmnopqr\n"});
testCM("collapsedRangeBetweenLinesSelected", function(cm) {
var widget = document.createElement("span");
widget.textContent = "\u2194";
cm.markText(Pos(0, 3), Pos(1, 0), {replacedWith: widget});
cm.setSelection(Pos(0, 3), Pos(1, 0));
var selElts = byClassName(cm.getWrapperElement(), "CodeMirror-selected");
for (var i = 0, w = 0; i < selElts.length; i++)
w += selElts[i].offsetWidth;
is(w > 0);
}, {value: "one\ntwo"});
testCM("randomCollapsedRanges", function(cm) {
addDoc(cm, 20, 500);
cm.operation(function() {
for (var i = 0; i < 200; i++) {
var start = Pos(Math.floor(Math.random() * 500), Math.floor(Math.random() * 20));
if (i % 4)
try { cm.markText(start, Pos(start.line + 2, 1), {collapsed: true}); }
catch(e) { if (!/overlapping/.test(String(e))) throw e; }
else
cm.markText(start, Pos(start.line, start.ch + 4), {"className": "foo"});
}
});
});
testCM("hiddenLinesAutoUnfold", function(cm) {
var range = foldLines(cm, 1, 3, true), cleared = 0;
CodeMirror.on(range, "clear", function() {cleared++;});
cm.setCursor(Pos(3, 0));
eq(cleared, 0);
cm.execCommand("goCharLeft");
eq(cleared, 1);
range = foldLines(cm, 1, 3, true);
CodeMirror.on(range, "clear", function() {cleared++;});
eqPos(cm.getCursor(), Pos(3, 0));
cm.setCursor(Pos(0, 3));
cm.execCommand("goCharRight");
eq(cleared, 2);
}, {value: "abc\ndef\nghi\njkl"});
testCM("hiddenLinesSelectAll", function(cm) { // Issue #484
addDoc(cm, 4, 20);
foldLines(cm, 0, 10);
foldLines(cm, 11, 20);
CodeMirror.commands.selectAll(cm);
eqPos(cm.getCursor(true), Pos(10, 0));
eqPos(cm.getCursor(false), Pos(10, 4));
});
testCM("everythingFolded", function(cm) {
addDoc(cm, 2, 2);
function enterPress() {
cm.triggerOnKeyDown({type: "keydown", keyCode: 13, preventDefault: function(){}, stopPropagation: function(){}});
}
var fold = foldLines(cm, 0, 2);
enterPress();
eq(cm.getValue(), "xx\nxx");
fold.clear();
fold = foldLines(cm, 0, 2, true);
eq(fold.find(), null);
enterPress();
eq(cm.getValue(), "\nxx\nxx");
});
testCM("structuredFold", function(cm) {
if (phantom) return;
addDoc(cm, 4, 8);
var range = cm.markText(Pos(1, 2), Pos(6, 2), {
replacedWith: document.createTextNode("Q")
});
cm.setCursor(0, 3);
CodeMirror.commands.goLineDown(cm);
eqPos(cm.getCursor(), Pos(6, 2));
CodeMirror.commands.goCharLeft(cm);
eqPos(cm.getCursor(), Pos(1, 2));
CodeMirror.commands.delCharAfter(cm);
eq(cm.getValue(), "xxxx\nxxxx\nxxxx");
addDoc(cm, 4, 8);
range = cm.markText(Pos(1, 2), Pos(6, 2), {
replacedWith: document.createTextNode("M"),
clearOnEnter: true
});
var cleared = 0;
CodeMirror.on(range, "clear", function(){++cleared;});
cm.setCursor(0, 3);
CodeMirror.commands.goLineDown(cm);
eqPos(cm.getCursor(), Pos(6, 2));
CodeMirror.commands.goCharLeft(cm);
eqPos(cm.getCursor(), Pos(6, 1));
eq(cleared, 1);
range.clear();
eq(cleared, 1);
range = cm.markText(Pos(1, 2), Pos(6, 2), {
replacedWith: document.createTextNode("Q"),
clearOnEnter: true
});
range.clear();
cm.setCursor(1, 2);
CodeMirror.commands.goCharRight(cm);
eqPos(cm.getCursor(), Pos(1, 3));
range = cm.markText(Pos(2, 0), Pos(4, 4), {
replacedWith: document.createTextNode("M")
});
cm.setCursor(1, 0);
CodeMirror.commands.goLineDown(cm);
eqPos(cm.getCursor(), Pos(2, 0));
}, null);
testCM("nestedFold", function(cm) {
addDoc(cm, 10, 3);
function fold(ll, cl, lr, cr) {
return cm.markText(Pos(ll, cl), Pos(lr, cr), {collapsed: true});
}
var inner1 = fold(0, 6, 1, 3), inner2 = fold(0, 2, 1, 8), outer = fold(0, 1, 2, 3), inner0 = fold(0, 5, 0, 6);
cm.setCursor(0, 1);
CodeMirror.commands.goCharRight(cm);
eqPos(cm.getCursor(), Pos(2, 3));
inner0.clear();
CodeMirror.commands.goCharLeft(cm);
eqPos(cm.getCursor(), Pos(0, 1));
outer.clear();
CodeMirror.commands.goCharRight(cm);
eqPos(cm.getCursor(), Pos(0, 2));
CodeMirror.commands.goCharRight(cm);
eqPos(cm.getCursor(), Pos(1, 8));
inner2.clear();
CodeMirror.commands.goCharLeft(cm);
eqPos(cm.getCursor(), Pos(1, 7));
cm.setCursor(0, 5);
CodeMirror.commands.goCharRight(cm);
eqPos(cm.getCursor(), Pos(0, 6));
CodeMirror.commands.goCharRight(cm);
eqPos(cm.getCursor(), Pos(1, 3));
});
testCM("badNestedFold", function(cm) {
addDoc(cm, 4, 4);
cm.markText(Pos(0, 2), Pos(3, 2), {collapsed: true});
var caught;
try {cm.markText(Pos(0, 1), Pos(0, 3), {collapsed: true});}
catch(e) {caught = e;}
is(caught instanceof Error, "no error");
is(/overlap/i.test(caught.message), "wrong error");
});
testCM("nestedFoldOnSide", function(cm) {
var m1 = cm.markText(Pos(0, 1), Pos(2, 1), {collapsed: true, inclusiveRight: true});
var m2 = cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true});
cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true}).clear();
try { cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true, inclusiveLeft: true}); }
catch(e) { var caught = e; }
is(caught && /overlap/i.test(caught.message));
var m3 = cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true});
var m4 = cm.markText(Pos(2, 0), Pos(2, 1), {collapse: true, inclusiveRight: true});
m1.clear(); m4.clear();
m1 = cm.markText(Pos(0, 1), Pos(2, 1), {collapsed: true});
cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true}).clear();
try { cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true, inclusiveRight: true}); }
catch(e) { var caught = e; }
is(caught && /overlap/i.test(caught.message));
}, {value: "ab\ncd\ef"});
testCM("editInFold", function(cm) {
addDoc(cm, 4, 6);
var m = cm.markText(Pos(1, 2), Pos(3, 2), {collapsed: true});
cm.replaceRange("", Pos(0, 0), Pos(1, 3));
cm.replaceRange("", Pos(2, 1), Pos(3, 3));
cm.replaceRange("a\nb\nc\nd", Pos(0, 1), Pos(1, 0));
cm.cursorCoords(Pos(0, 0));
});
testCM("wrappingInlineWidget", function(cm) {
cm.setSize("11em");
var w = document.createElement("span");
w.style.color = "red";
w.innerHTML = "one two three four";
cm.markText(Pos(0, 6), Pos(0, 9), {replacedWith: w});
var cur0 = cm.cursorCoords(Pos(0, 0)), cur1 = cm.cursorCoords(Pos(0, 10));
is(cur0.top < cur1.top);
is(cur0.bottom < cur1.bottom);
var curL = cm.cursorCoords(Pos(0, 6)), curR = cm.cursorCoords(Pos(0, 9));
eq(curL.top, cur0.top);
eq(curL.bottom, cur0.bottom);
eq(curR.top, cur1.top);
eq(curR.bottom, cur1.bottom);
cm.replaceRange("", Pos(0, 9), Pos(0));
curR = cm.cursorCoords(Pos(0, 9));
if (phantom) return;
eq(curR.top, cur1.top);
eq(curR.bottom, cur1.bottom);
}, {value: "1 2 3 xxx 4", lineWrapping: true});
testCM("changedInlineWidget", function(cm) {
cm.setSize("10em");
var w = document.createElement("span");
w.innerHTML = "x";
var m = cm.markText(Pos(0, 4), Pos(0, 5), {replacedWith: w});
w.innerHTML = "and now the widget is really really long all of a sudden and a scrollbar is needed";
m.changed();
var hScroll = byClassName(cm.getWrapperElement(), "CodeMirror-hscrollbar")[0];
is(hScroll.scrollWidth > hScroll.clientWidth);
}, {value: "hello there"});
testCM("changedBookmark", function(cm) {
cm.setSize("10em");
var w = document.createElement("span");
w.innerHTML = "x";
var m = cm.setBookmark(Pos(0, 4), {widget: w});
w.innerHTML = "and now the widget is really really long all of a sudden and a scrollbar is needed";
m.changed();
var hScroll = byClassName(cm.getWrapperElement(), "CodeMirror-hscrollbar")[0];
is(hScroll.scrollWidth > hScroll.clientWidth);
}, {value: "abcdefg"});
testCM("inlineWidget", function(cm) {
var w = cm.setBookmark(Pos(0, 2), {widget: document.createTextNode("uu")});
cm.setCursor(0, 2);
CodeMirror.commands.goLineDown(cm);
eqPos(cm.getCursor(), Pos(1, 4));
cm.setCursor(0, 2);
cm.replaceSelection("hi");
eqPos(w.find(), Pos(0, 2));
cm.setCursor(0, 1);
cm.replaceSelection("ay");
eqPos(w.find(), Pos(0, 4));
eq(cm.getLine(0), "uayuhiuu");
}, {value: "uuuu\nuuuuuu"});
testCM("wrappingAndResizing", function(cm) {
cm.setSize(null, "auto");
cm.setOption("lineWrapping", true);
var wrap = cm.getWrapperElement(), h0 = wrap.offsetHeight;
var doc = "xxx xxx xxx xxx xxx";
cm.setValue(doc);
for (var step = 10, w = cm.charCoords(Pos(0, 18), "div").right;; w += step) {
cm.setSize(w);
if (wrap.offsetHeight <= h0 * (opera_lt10 ? 1.2 : 1.5)) {
if (step == 10) { w -= 10; step = 1; }
else break;
}
}
// Ensure that putting the cursor at the end of the maximally long
// line doesn't cause wrapping to happen.
cm.setCursor(Pos(0, doc.length));
eq(wrap.offsetHeight, h0);
cm.replaceSelection("x");
is(wrap.offsetHeight > h0, "wrapping happens");
// Now add a max-height and, in a document consisting of
// almost-wrapped lines, go over it so that a scrollbar appears.
cm.setValue(doc + "\n" + doc + "\n");
cm.getScrollerElement().style.maxHeight = "100px";
cm.replaceRange("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n!\n", Pos(2, 0));
forEach([Pos(0, doc.length), Pos(0, doc.length - 1),
Pos(0, 0), Pos(1, doc.length), Pos(1, doc.length - 1)],
function(pos) {
var coords = cm.charCoords(pos);
eqPos(pos, cm.coordsChar({left: coords.left + 2, top: coords.top + 5}));
});
}, null, ie_lt8);
testCM("measureEndOfLine", function(cm) {
cm.setSize(null, "auto");
var inner = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild;
var lh = inner.offsetHeight;
for (var step = 10, w = cm.charCoords(Pos(0, 7), "div").right;; w += step) {
cm.setSize(w);
if (inner.offsetHeight < 2.5 * lh) {
if (step == 10) { w -= 10; step = 1; }
else break;
}
}
cm.setValue(cm.getValue() + "\n\n");
var endPos = cm.charCoords(Pos(0, 18), "local");
is(endPos.top > lh * .8, "not at top");
is(endPos.left > w - 20, "not at right");
endPos = cm.charCoords(Pos(0, 18));
eqPos(cm.coordsChar({left: endPos.left, top: endPos.top + 5}), Pos(0, 18));
}, {mode: "text/html", value: "<!-- foo barrr -->", lineWrapping: true}, ie_lt8 || opera_lt10);
testCM("scrollVerticallyAndHorizontally", function(cm) {
cm.setSize(100, 100);
addDoc(cm, 40, 40);
cm.setCursor(39);
var wrap = cm.getWrapperElement(), bar = byClassName(wrap, "CodeMirror-vscrollbar")[0];
is(bar.offsetHeight < wrap.offsetHeight, "vertical scrollbar limited by horizontal one");
var cursorBox = byClassName(wrap, "CodeMirror-cursor")[0].getBoundingClientRect();
var editorBox = wrap.getBoundingClientRect();
is(cursorBox.bottom < editorBox.top + cm.getScrollerElement().clientHeight,
"bottom line visible");
}, {lineNumbers: true});
testCM("moveVstuck", function(cm) {
var lines = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild, h0 = lines.offsetHeight;
var val = "fooooooooooooooooooooooooo baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaar\n";
cm.setValue(val);
for (var w = cm.charCoords(Pos(0, 26), "div").right * 2.8;; w += 5) {
cm.setSize(w);
if (lines.offsetHeight <= 3.5 * h0) break;
}
cm.setCursor(Pos(0, val.length - 1));
cm.moveV(-1, "line");
eqPos(cm.getCursor(), Pos(0, 26));
}, {lineWrapping: true}, ie_lt8 || opera_lt10);
testCM("collapseOnMove", function(cm) {
cm.setSelection(Pos(0, 1), Pos(2, 4));
cm.execCommand("goLineUp");
is(!cm.somethingSelected());
eqPos(cm.getCursor(), Pos(0, 1));
cm.setSelection(Pos(0, 1), Pos(2, 4));
cm.execCommand("goPageDown");
is(!cm.somethingSelected());
eqPos(cm.getCursor(), Pos(2, 4));
cm.execCommand("goLineUp");
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(0, 4));
cm.setSelection(Pos(0, 1), Pos(2, 4));
cm.execCommand("goCharLeft");
is(!cm.somethingSelected());
eqPos(cm.getCursor(), Pos(0, 1));
}, {value: "aaaaa\nb\nccccc"});
testCM("clickTab", function(cm) {
var p0 = cm.charCoords(Pos(0, 0));
eqPos(cm.coordsChar({left: p0.left + 5, top: p0.top + 5}), Pos(0, 0));
eqPos(cm.coordsChar({left: p0.right - 5, top: p0.top + 5}), Pos(0, 1));
}, {value: "\t\n\n", lineWrapping: true, tabSize: 8});
testCM("verticalScroll", function(cm) {
cm.setSize(100, 200);
cm.setValue("foo\nbar\nbaz\n");
var sc = cm.getScrollerElement(), baseWidth = sc.scrollWidth;
cm.replaceRange("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah", Pos(0, 0), Pos(0));
is(sc.scrollWidth > baseWidth, "scrollbar present");
cm.replaceRange("foo", Pos(0, 0), Pos(0));
if (!phantom) eq(sc.scrollWidth, baseWidth, "scrollbar gone");
cm.replaceRange("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah", Pos(0, 0), Pos(0));
cm.replaceRange("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbh", Pos(1, 0), Pos(1));
is(sc.scrollWidth > baseWidth, "present again");
var curWidth = sc.scrollWidth;
cm.replaceRange("foo", Pos(0, 0), Pos(0));
is(sc.scrollWidth < curWidth, "scrollbar smaller");
is(sc.scrollWidth > baseWidth, "but still present");
});
testCM("extraKeys", function(cm) {
var outcome;
function fakeKey(expected, code, props) {
if (typeof code == "string") code = code.charCodeAt(0);
var e = {type: "keydown", keyCode: code, preventDefault: function(){}, stopPropagation: function(){}};
if (props) for (var n in props) e[n] = props[n];
outcome = null;
cm.triggerOnKeyDown(e);
eq(outcome, expected);
}
CodeMirror.commands.testCommand = function() {outcome = "tc";};
CodeMirror.commands.goTestCommand = function() {outcome = "gtc";};
cm.setOption("extraKeys", {"Shift-X": function() {outcome = "sx";},
"X": function() {outcome = "x";},
"Ctrl-Alt-U": function() {outcome = "cau";},
"End": "testCommand",
"Home": "goTestCommand",
"Tab": false});
fakeKey(null, "U");
fakeKey("cau", "U", {ctrlKey: true, altKey: true});
fakeKey(null, "U", {shiftKey: true, ctrlKey: true, altKey: true});
fakeKey("x", "X");
fakeKey("sx", "X", {shiftKey: true});
fakeKey("tc", 35);
fakeKey(null, 35, {shiftKey: true});
fakeKey("gtc", 36);
fakeKey("gtc", 36, {shiftKey: true});
fakeKey(null, 9);
}, null, window.opera && mac);
testCM("wordMovementCommands", function(cm) {
cm.execCommand("goWordLeft");
eqPos(cm.getCursor(), Pos(0, 0));
cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
eqPos(cm.getCursor(), Pos(0, 7));
cm.execCommand("goWordLeft");
eqPos(cm.getCursor(), Pos(0, 5));
cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
eqPos(cm.getCursor(), Pos(0, 12));
cm.execCommand("goWordLeft");
eqPos(cm.getCursor(), Pos(0, 9));
cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
eqPos(cm.getCursor(), Pos(0, 24));
cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
eqPos(cm.getCursor(), Pos(1, 9));
cm.execCommand("goWordRight");
eqPos(cm.getCursor(), Pos(1, 13));
cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
eqPos(cm.getCursor(), Pos(2, 0));
}, {value: "this is (the) firstline.\na foo12\u00e9\u00f8\u00d7bar\n"});
testCM("groupMovementCommands", function(cm) {
cm.execCommand("goGroupLeft");
eqPos(cm.getCursor(), Pos(0, 0));
cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), Pos(0, 4));
cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), Pos(0, 7));
cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), Pos(0, 10));
cm.execCommand("goGroupLeft");
eqPos(cm.getCursor(), Pos(0, 7));
cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), Pos(0, 15));
cm.setCursor(Pos(0, 17));
cm.execCommand("goGroupLeft");
eqPos(cm.getCursor(), Pos(0, 16));
cm.execCommand("goGroupLeft");
eqPos(cm.getCursor(), Pos(0, 14));
cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), Pos(0, 20));
cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), Pos(1, 0));
cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), Pos(1, 2));
cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), Pos(1, 5));
cm.execCommand("goGroupLeft"); cm.execCommand("goGroupLeft");
eqPos(cm.getCursor(), Pos(1, 0));
cm.execCommand("goGroupLeft");
eqPos(cm.getCursor(), Pos(0, 20));
cm.execCommand("goGroupLeft");
eqPos(cm.getCursor(), Pos(0, 16));
}, {value: "booo ba---quux. ffff\n abc d"});
testCM("groupsAndWhitespace", function(cm) {
var positions = [Pos(0, 0), Pos(0, 2), Pos(0, 5), Pos(0, 9), Pos(0, 11),
Pos(1, 0), Pos(1, 2), Pos(1, 5)];
for (var i = 1; i < positions.length; i++) {
cm.execCommand("goGroupRight");
eqPos(cm.getCursor(), positions[i]);
}
for (var i = positions.length - 2; i >= 0; i--) {
cm.execCommand("goGroupLeft");
eqPos(cm.getCursor(), i == 2 ? Pos(0, 6) : positions[i]);
}
}, {value: " foo +++ \n bar"});
testCM("charMovementCommands", function(cm) {
cm.execCommand("goCharLeft"); cm.execCommand("goColumnLeft");
eqPos(cm.getCursor(), Pos(0, 0));
cm.execCommand("goCharRight"); cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(0, 2));
cm.setCursor(Pos(1, 0));
cm.execCommand("goColumnLeft");
eqPos(cm.getCursor(), Pos(1, 0));
cm.execCommand("goCharLeft");
eqPos(cm.getCursor(), Pos(0, 5));
cm.execCommand("goColumnRight");
eqPos(cm.getCursor(), Pos(0, 5));
cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(1, 0));
cm.execCommand("goLineEnd");
eqPos(cm.getCursor(), Pos(1, 5));
cm.execCommand("goLineStartSmart");
eqPos(cm.getCursor(), Pos(1, 1));
cm.execCommand("goLineStartSmart");
eqPos(cm.getCursor(), Pos(1, 0));
cm.setCursor(Pos(2, 0));
cm.execCommand("goCharRight"); cm.execCommand("goColumnRight");
eqPos(cm.getCursor(), Pos(2, 0));
}, {value: "line1\n ine2\n"});
testCM("verticalMovementCommands", function(cm) {
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(0, 0));
cm.execCommand("goLineDown");
if (!phantom) // This fails in PhantomJS, though not in a real Webkit
eqPos(cm.getCursor(), Pos(1, 0));
cm.setCursor(Pos(1, 12));
cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(2, 5));
cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(3, 0));
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(2, 5));
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(1, 12));
cm.execCommand("goPageDown");
eqPos(cm.getCursor(), Pos(5, 0));
cm.execCommand("goPageDown"); cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(5, 0));
cm.execCommand("goPageUp");
eqPos(cm.getCursor(), Pos(0, 0));
}, {value: "line1\nlong long line2\nline3\n\nline5\n"});
testCM("verticalMovementCommandsWrapping", function(cm) {
cm.setSize(120);
cm.setCursor(Pos(0, 5));
cm.execCommand("goLineDown");
eq(cm.getCursor().line, 0);
is(cm.getCursor().ch > 5, "moved beyond wrap");
for (var i = 0; ; ++i) {
is(i < 20, "no endless loop");
cm.execCommand("goLineDown");
var cur = cm.getCursor();
if (cur.line == 1) eq(cur.ch, 5);
if (cur.line == 2) { eq(cur.ch, 1); break; }
}
}, {value: "a very long line that wraps around somehow so that we can test cursor movement\nshortone\nk",
lineWrapping: true});
testCM("rtlMovement", function(cm) {
forEach(["خحج", "خحabcخحج", "abخحخحجcd", "abخde", "abخح2342خ1حج", "خ1ح2خح3حxج",
"خحcd", "1خحcd", "abcdeح1ج", "خمرحبها مها!", "foobarر", "خ ة ق",
"<img src=\"/בדיקה3.jpg\">"], function(line) {
var inv = line.charAt(0) == "خ";
cm.setValue(line + "\n"); cm.execCommand(inv ? "goLineEnd" : "goLineStart");
var cursors = byClassName(cm.getWrapperElement(), "CodeMirror-cursors")[0];
var cursor = cursors.firstChild;
var prevX = cursor.offsetLeft, prevY = cursor.offsetTop;
for (var i = 0; i <= line.length; ++i) {
cm.execCommand("goCharRight");
cursor = cursors.firstChild;
if (i == line.length) is(cursor.offsetTop > prevY, "next line");
else is(cursor.offsetLeft > prevX, "moved right");
prevX = cursor.offsetLeft; prevY = cursor.offsetTop;
}
cm.setCursor(0, 0); cm.execCommand(inv ? "goLineStart" : "goLineEnd");
prevX = cursors.firstChild.offsetLeft;
for (var i = 0; i < line.length; ++i) {
cm.execCommand("goCharLeft");
cursor = cursors.firstChild;
is(cursor.offsetLeft < prevX, "moved left");
prevX = cursor.offsetLeft;
}
});
}, null, ie_lt9);
// Verify that updating a line clears its bidi ordering
testCM("bidiUpdate", function(cm) {
cm.setCursor(Pos(0, 2));
cm.replaceSelection("خحج", "start");
cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(0, 4));
}, {value: "abcd\n"});
testCM("movebyTextUnit", function(cm) {
cm.setValue("בְּרֵאשִ\nééé́\n");
cm.execCommand("goLineEnd");
for (var i = 0; i < 4; ++i) cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(0, 0));
cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(1, 0));
cm.execCommand("goCharRight");
cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(1, 4));
cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(1, 7));
});
testCM("lineChangeEvents", function(cm) {
addDoc(cm, 3, 5);
var log = [], want = ["ch 0", "ch 1", "del 2", "ch 0", "ch 0", "del 1", "del 3", "del 4"];
for (var i = 0; i < 5; ++i) {
CodeMirror.on(cm.getLineHandle(i), "delete", function(i) {
return function() {log.push("del " + i);};
}(i));
CodeMirror.on(cm.getLineHandle(i), "change", function(i) {
return function() {log.push("ch " + i);};
}(i));
}
cm.replaceRange("x", Pos(0, 1));
cm.replaceRange("xy", Pos(1, 1), Pos(2));
cm.replaceRange("foo\nbar", Pos(0, 1));
cm.replaceRange("", Pos(0, 0), Pos(cm.lineCount()));
eq(log.length, want.length, "same length");
for (var i = 0; i < log.length; ++i)
eq(log[i], want[i]);
});
testCM("scrollEntirelyToRight", function(cm) {
if (phantom) return;
addDoc(cm, 500, 2);
cm.setCursor(Pos(0, 500));
var wrap = cm.getWrapperElement(), cur = byClassName(wrap, "CodeMirror-cursor")[0];
is(wrap.getBoundingClientRect().right > cur.getBoundingClientRect().left);
});
testCM("lineWidgets", function(cm) {
addDoc(cm, 500, 3);
var last = cm.charCoords(Pos(2, 0));
var node = document.createElement("div");
node.innerHTML = "hi";
var widget = cm.addLineWidget(1, node);
is(last.top < cm.charCoords(Pos(2, 0)).top, "took up space");
cm.setCursor(Pos(1, 1));
cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(2, 1));
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(1, 1));
});
testCM("lineWidgetFocus", function(cm) {
var place = document.getElementById("testground");
place.className = "offscreen";
try {
addDoc(cm, 500, 10);
var node = document.createElement("input");
var widget = cm.addLineWidget(1, node);
node.focus();
eq(document.activeElement, node);
cm.replaceRange("new stuff", Pos(1, 0));
eq(document.activeElement, node);
} finally {
place.className = "";
}
});
testCM("lineWidgetCautiousRedraw", function(cm) {
var node = document.createElement("div");
node.innerHTML = "hahah";
var w = cm.addLineWidget(0, node);
var redrawn = false;
w.on("redraw", function() { redrawn = true; });
cm.replaceSelection("0");
is(!redrawn);
}, {value: "123\n456"});
testCM("lineWidgetChanged", function(cm) {
addDoc(cm, 2, 300);
cm.setSize(null, cm.defaultTextHeight() * 50);
cm.scrollTo(null, cm.heightAtLine(125, "local"));
function w() {
var node = document.createElement("div");
node.style.cssText = "background: yellow; height: 50px;";
return node;
}
var info0 = cm.getScrollInfo();
var w0 = cm.addLineWidget(0, w());
var w150 = cm.addLineWidget(150, w());
var w300 = cm.addLineWidget(300, w());
var info1 = cm.getScrollInfo();
eq(info0.height + 150, info1.height);
eq(info0.top + 50, info1.top);
w0.node.style.height = w150.node.style.height = w300.node.style.height = "10px";
w0.changed(); w150.changed(); w300.changed();
var info2 = cm.getScrollInfo();
eq(info0.height + 30, info2.height);
eq(info0.top + 10, info2.top);
});
testCM("getLineNumber", function(cm) {
addDoc(cm, 2, 20);
var h1 = cm.getLineHandle(1);
eq(cm.getLineNumber(h1), 1);
cm.replaceRange("hi\nbye\n", Pos(0, 0));
eq(cm.getLineNumber(h1), 3);
cm.setValue("");
eq(cm.getLineNumber(h1), null);
});
testCM("jumpTheGap", function(cm) {
if (phantom) return;
var longLine = "abcdef ghiklmnop qrstuvw xyz ";
longLine += longLine; longLine += longLine; longLine += longLine;
cm.replaceRange(longLine, Pos(2, 0), Pos(2));
cm.setSize("200px", null);
cm.getWrapperElement().style.lineHeight = 2;
cm.refresh();
cm.setCursor(Pos(0, 1));
cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(1, 1));
cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(2, 1));
cm.execCommand("goLineDown");
eq(cm.getCursor().line, 2);
is(cm.getCursor().ch > 1);
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(2, 1));
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(1, 1));
var node = document.createElement("div");
node.innerHTML = "hi"; node.style.height = "30px";
cm.addLineWidget(0, node);
cm.addLineWidget(1, node.cloneNode(true), {above: true});
cm.setCursor(Pos(0, 2));
cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(1, 2));
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(0, 2));
}, {lineWrapping: true, value: "abc\ndef\nghi\njkl\n"});
testCM("addLineClass", function(cm) {
function cls(line, text, bg, wrap) {
var i = cm.lineInfo(line);
eq(i.textClass, text);
eq(i.bgClass, bg);
eq(i.wrapClass, wrap);
}
cm.addLineClass(0, "text", "foo");
cm.addLineClass(0, "text", "bar");
cm.addLineClass(1, "background", "baz");
cm.addLineClass(1, "wrap", "foo");
cls(0, "foo bar", null, null);
cls(1, null, "baz", "foo");
var lines = cm.display.lineDiv;
eq(byClassName(lines, "foo").length, 2);
eq(byClassName(lines, "bar").length, 1);
eq(byClassName(lines, "baz").length, 1);
cm.removeLineClass(0, "text", "foo");
cls(0, "bar", null, null);
cm.removeLineClass(0, "text", "foo");
cls(0, "bar", null, null);
cm.removeLineClass(0, "text", "bar");
cls(0, null, null, null);
cm.addLineClass(1, "wrap", "quux");
cls(1, null, "baz", "foo quux");
cm.removeLineClass(1, "wrap");
cls(1, null, "baz", null);
}, {value: "hohoho\n"});
testCM("atomicMarker", function(cm) {
addDoc(cm, 10, 10);
function atom(ll, cl, lr, cr, li, ri) {
return cm.markText(Pos(ll, cl), Pos(lr, cr),
{atomic: true, inclusiveLeft: li, inclusiveRight: ri});
}
var m = atom(0, 1, 0, 5);
cm.setCursor(Pos(0, 1));
cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(0, 5));
cm.execCommand("goCharLeft");
eqPos(cm.getCursor(), Pos(0, 1));
m.clear();
m = atom(0, 0, 0, 5, true);
eqPos(cm.getCursor(), Pos(0, 5), "pushed out");
cm.execCommand("goCharLeft");
eqPos(cm.getCursor(), Pos(0, 5));
m.clear();
m = atom(8, 4, 9, 10, false, true);
cm.setCursor(Pos(9, 8));
eqPos(cm.getCursor(), Pos(8, 4), "set");
cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(8, 4), "char right");
cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(8, 4), "line down");
cm.execCommand("goCharLeft");
eqPos(cm.getCursor(), Pos(8, 3));
m.clear();
m = atom(1, 1, 3, 8);
cm.setCursor(Pos(0, 0));
cm.setCursor(Pos(2, 0));
eqPos(cm.getCursor(), Pos(3, 8));
cm.execCommand("goCharLeft");
eqPos(cm.getCursor(), Pos(1, 1));
cm.execCommand("goCharRight");
eqPos(cm.getCursor(), Pos(3, 8));
cm.execCommand("goLineUp");
eqPos(cm.getCursor(), Pos(1, 1));
cm.execCommand("goLineDown");
eqPos(cm.getCursor(), Pos(3, 8));
cm.execCommand("delCharBefore");
eq(cm.getValue().length, 80, "del chunk");
m = atom(3, 0, 5, 5);
cm.setCursor(Pos(3, 0));
cm.execCommand("delWordAfter");
eq(cm.getValue().length, 53, "del chunk");
});
testCM("selectionBias", function(cm) {
cm.markText(Pos(0, 1), Pos(0, 3), {atomic: true});
cm.setCursor(Pos(0, 2));
eqPos(cm.getCursor(), Pos(0, 3));
cm.setCursor(Pos(0, 2));
eqPos(cm.getCursor(), Pos(0, 1));
cm.setCursor(Pos(0, 2), null, {bias: -1});
eqPos(cm.getCursor(), Pos(0, 1));
cm.setCursor(Pos(0, 4));
cm.setCursor(Pos(0, 2), null, {bias: 1});
eqPos(cm.getCursor(), Pos(0, 3), "A");
}, {value: "12345"});
testCM("readOnlyMarker", function(cm) {
function mark(ll, cl, lr, cr, at) {
return cm.markText(Pos(ll, cl), Pos(lr, cr),
{readOnly: true, atomic: at});
}
var m = mark(0, 1, 0, 4);
cm.setCursor(Pos(0, 2));
cm.replaceSelection("hi", "end");
eqPos(cm.getCursor(), Pos(0, 2));
eq(cm.getLine(0), "abcde");
cm.execCommand("selectAll");
cm.replaceSelection("oops", "around");
eq(cm.getValue(), "oopsbcd");
cm.undo();
eqPos(m.find().from, Pos(0, 1));
eqPos(m.find().to, Pos(0, 4));
m.clear();
cm.setCursor(Pos(0, 2));
cm.replaceSelection("hi", "around");
eq(cm.getLine(0), "abhicde");
eqPos(cm.getCursor(), Pos(0, 4));
m = mark(0, 2, 2, 2, true);
cm.setSelection(Pos(1, 1), Pos(2, 4));
cm.replaceSelection("t", "end");
eqPos(cm.getCursor(), Pos(2, 3));
eq(cm.getLine(2), "klto");
cm.execCommand("goCharLeft");
cm.execCommand("goCharLeft");
eqPos(cm.getCursor(), Pos(0, 2));
cm.setSelection(Pos(0, 1), Pos(0, 3));
cm.replaceSelection("xx", "around");
eqPos(cm.getCursor(), Pos(0, 3));
eq(cm.getLine(0), "axxhicde");
}, {value: "abcde\nfghij\nklmno\n"});
testCM("dirtyBit", function(cm) {
eq(cm.isClean(), true);
cm.replaceSelection("boo", null, "test");
eq(cm.isClean(), false);
cm.undo();
eq(cm.isClean(), true);
cm.replaceSelection("boo", null, "test");
cm.replaceSelection("baz", null, "test");
cm.undo();
eq(cm.isClean(), false);
cm.markClean();
eq(cm.isClean(), true);
cm.undo();
eq(cm.isClean(), false);
cm.redo();
eq(cm.isClean(), true);
});
testCM("changeGeneration", function(cm) {
cm.replaceSelection("x");
var softGen = cm.changeGeneration();
cm.replaceSelection("x");
cm.undo();
eq(cm.getValue(), "");
is(!cm.isClean(softGen));
cm.replaceSelection("x");
var hardGen = cm.changeGeneration(true);
cm.replaceSelection("x");
cm.undo();
eq(cm.getValue(), "x");
is(cm.isClean(hardGen));
});
testCM("addKeyMap", function(cm) {
function sendKey(code) {
cm.triggerOnKeyDown({type: "keydown", keyCode: code,
preventDefault: function(){}, stopPropagation: function(){}});
}
sendKey(39);
eqPos(cm.getCursor(), Pos(0, 1));
var test = 0;
var map1 = {Right: function() { ++test; }}, map2 = {Right: function() { test += 10; }}
cm.addKeyMap(map1);
sendKey(39);
eqPos(cm.getCursor(), Pos(0, 1));
eq(test, 1);
cm.addKeyMap(map2, true);
sendKey(39);
eq(test, 2);
cm.removeKeyMap(map1);
sendKey(39);
eq(test, 12);
cm.removeKeyMap(map2);
sendKey(39);
eq(test, 12);
eqPos(cm.getCursor(), Pos(0, 2));
cm.addKeyMap({Right: function() { test = 55; }, name: "mymap"});
sendKey(39);
eq(test, 55);
cm.removeKeyMap("mymap");
sendKey(39);
eqPos(cm.getCursor(), Pos(0, 3));
}, {value: "abc"});
testCM("findPosH", function(cm) {
forEach([{from: Pos(0, 0), to: Pos(0, 1), by: 1},
{from: Pos(0, 0), to: Pos(0, 0), by: -1, hitSide: true},
{from: Pos(0, 0), to: Pos(0, 4), by: 1, unit: "word"},
{from: Pos(0, 0), to: Pos(0, 8), by: 2, unit: "word"},
{from: Pos(0, 0), to: Pos(2, 0), by: 20, unit: "word", hitSide: true},
{from: Pos(0, 7), to: Pos(0, 5), by: -1, unit: "word"},
{from: Pos(0, 4), to: Pos(0, 8), by: 1, unit: "word"},
{from: Pos(1, 0), to: Pos(1, 18), by: 3, unit: "word"},
{from: Pos(1, 22), to: Pos(1, 5), by: -3, unit: "word"},
{from: Pos(1, 15), to: Pos(1, 10), by: -5},
{from: Pos(1, 15), to: Pos(1, 10), by: -5, unit: "column"},
{from: Pos(1, 15), to: Pos(1, 0), by: -50, unit: "column", hitSide: true},
{from: Pos(1, 15), to: Pos(1, 24), by: 50, unit: "column", hitSide: true},
{from: Pos(1, 15), to: Pos(2, 0), by: 50, hitSide: true}], function(t) {
var r = cm.findPosH(t.from, t.by, t.unit || "char");
eqPos(r, t.to);
eq(!!r.hitSide, !!t.hitSide);
});
}, {value: "line one\nline two.something.other\n"});
testCM("beforeChange", function(cm) {
cm.on("beforeChange", function(cm, change) {
var text = [];
for (var i = 0; i < change.text.length; ++i)
text.push(change.text[i].replace(/\s/g, "_"));
change.update(null, null, text);
});
cm.setValue("hello, i am a\nnew document\n");
eq(cm.getValue(), "hello,_i_am_a\nnew_document\n");
CodeMirror.on(cm.getDoc(), "beforeChange", function(doc, change) {
if (change.from.line == 0) change.cancel();
});
cm.setValue("oops"); // Canceled
eq(cm.getValue(), "hello,_i_am_a\nnew_document\n");
cm.replaceRange("hey hey hey", Pos(1, 0), Pos(2, 0));
eq(cm.getValue(), "hello,_i_am_a\nhey_hey_hey");
}, {value: "abcdefghijk"});
testCM("beforeChangeUndo", function(cm) {
cm.replaceRange("hi", Pos(0, 0), Pos(0));
cm.replaceRange("bye", Pos(0, 0), Pos(0));
eq(cm.historySize().undo, 2);
cm.on("beforeChange", function(cm, change) {
is(!change.update);
change.cancel();
});
cm.undo();
eq(cm.historySize().undo, 0);
eq(cm.getValue(), "bye\ntwo");
}, {value: "one\ntwo"});
testCM("beforeSelectionChange", function(cm) {
function notAtEnd(cm, pos) {
var len = cm.getLine(pos.line).length;
if (!len || pos.ch == len) return Pos(pos.line, pos.ch - 1);
return pos;
}
cm.on("beforeSelectionChange", function(cm, obj) {
obj.update([{anchor: notAtEnd(cm, obj.ranges[0].anchor),
head: notAtEnd(cm, obj.ranges[0].head)}]);
});
addDoc(cm, 10, 10);
cm.execCommand("goLineEnd");
eqPos(cm.getCursor(), Pos(0, 9));
cm.execCommand("selectAll");
eqPos(cm.getCursor("start"), Pos(0, 0));
eqPos(cm.getCursor("end"), Pos(9, 9));
});
testCM("change_removedText", function(cm) {
cm.setValue("abc\ndef");
var removedText = [];
cm.on("change", function(cm, change) {
removedText.push(change.removed);
});
cm.operation(function() {
cm.replaceRange("xyz", Pos(0, 0), Pos(1,1));
cm.replaceRange("123", Pos(0,0));
});
eq(removedText.length, 2);
eq(removedText[0].join("\n"), "abc\nd");
eq(removedText[1].join("\n"), "");
var removedText = [];
cm.undo();
eq(removedText.length, 2);
eq(removedText[0].join("\n"), "123");
eq(removedText[1].join("\n"), "xyz");
var removedText = [];
cm.redo();
eq(removedText.length, 2);
eq(removedText[0].join("\n"), "abc\nd");
eq(removedText[1].join("\n"), "");
});
testCM("lineStyleFromMode", function(cm) {
CodeMirror.defineMode("test_mode", function() {
return {token: function(stream) {
if (stream.match(/^\[[^\]]*\]/)) return " line-brackets ";
if (stream.match(/^\([^\)]*\)/)) return " line-background-parens ";
if (stream.match(/^<[^>]*>/)) return " span line-line line-background-bg ";
stream.match(/^\s+|^\S+/);
}};
});
cm.setOption("mode", "test_mode");
var bracketElts = byClassName(cm.getWrapperElement(), "brackets");
eq(bracketElts.length, 1, "brackets count");
eq(bracketElts[0].nodeName, "PRE");
is(!/brackets.*brackets/.test(bracketElts[0].className));
var parenElts = byClassName(cm.getWrapperElement(), "parens");
eq(parenElts.length, 1, "parens count");
eq(parenElts[0].nodeName, "DIV");
is(!/parens.*parens/.test(parenElts[0].className));
eq(parenElts[0].parentElement.nodeName, "DIV");
eq(byClassName(cm.getWrapperElement(), "bg").length, 1);
eq(byClassName(cm.getWrapperElement(), "line").length, 1);
var spanElts = byClassName(cm.getWrapperElement(), "cm-span");
eq(spanElts.length, 2);
is(/^\s*cm-span\s*$/.test(spanElts[0].className));
}, {value: "line1: [br] [br]\nline2: (par) (par)\nline3: <tag> <tag>"});
testCM("lineStyleFromBlankLine", function(cm) {
CodeMirror.defineMode("lineStyleFromBlankLine_mode", function() {
return {token: function(stream) { stream.skipToEnd(); return "comment"; },
blankLine: function() { return "line-blank"; }};
});
cm.setOption("mode", "lineStyleFromBlankLine_mode");
var blankElts = byClassName(cm.getWrapperElement(), "blank");
eq(blankElts.length, 1);
eq(blankElts[0].nodeName, "PRE");
cm.replaceRange("x", Pos(1, 0));
blankElts = byClassName(cm.getWrapperElement(), "blank");
eq(blankElts.length, 0);
}, {value: "foo\n\nbar"});
CodeMirror.registerHelper("xxx", "a", "A");
CodeMirror.registerHelper("xxx", "b", "B");
CodeMirror.defineMode("yyy", function() {
return {
token: function(stream) { stream.skipToEnd(); },
xxx: ["a", "b", "q"]
};
});
CodeMirror.registerGlobalHelper("xxx", "c", function(m) { return m.enableC; }, "C");
testCM("helpers", function(cm) {
cm.setOption("mode", "yyy");
eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), "A/B");
cm.setOption("mode", {name: "yyy", modeProps: {xxx: "b", enableC: true}});
eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), "B/C");
cm.setOption("mode", "javascript");
eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), "");
});
testCM("selectionHistory", function(cm) {
for (var i = 0; i < 3; i++) {
cm.setExtending(true);
cm.execCommand("goCharRight");
cm.setExtending(false);
cm.execCommand("goCharRight");
cm.execCommand("goCharRight");
}
cm.execCommand("undoSelection");
eq(cm.getSelection(), "c");
cm.execCommand("undoSelection");
eq(cm.getSelection(), "");
eqPos(cm.getCursor(), Pos(0, 4));
cm.execCommand("undoSelection");
eq(cm.getSelection(), "b");
cm.execCommand("redoSelection");
eq(cm.getSelection(), "");
eqPos(cm.getCursor(), Pos(0, 4));
cm.execCommand("redoSelection");
eq(cm.getSelection(), "c");
cm.execCommand("redoSelection");
eq(cm.getSelection(), "");
eqPos(cm.getCursor(), Pos(0, 6));
}, {value: "a b c d"});
testCM("selectionChangeReducesRedo", function(cm) {
cm.replaceSelection("X");
cm.execCommand("goCharRight");
cm.undoSelection();
cm.execCommand("selectAll");
cm.undoSelection();
eq(cm.getValue(), "Xabc");
eqPos(cm.getCursor(), Pos(0, 1));
cm.undoSelection();
eq(cm.getValue(), "abc");
}, {value: "abc"});
testCM("selectionHistoryNonOverlapping", function(cm) {
cm.setSelection(Pos(0, 0), Pos(0, 1));
cm.setSelection(Pos(0, 2), Pos(0, 3));
cm.execCommand("undoSelection");
eqPos(cm.getCursor("anchor"), Pos(0, 0));
eqPos(cm.getCursor("head"), Pos(0, 1));
}, {value: "1234"});
testCM("cursorMotionSplitsHistory", function(cm) {
cm.replaceSelection("a");
cm.execCommand("goCharRight");
cm.replaceSelection("b");
cm.replaceSelection("c");
cm.undo();
eq(cm.getValue(), "a1234");
eqPos(cm.getCursor(), Pos(0, 2));
cm.undo();
eq(cm.getValue(), "1234");
eqPos(cm.getCursor(), Pos(0, 0));
}, {value: "1234"});
testCM("selChangeInOperationDoesNotSplit", function(cm) {
for (var i = 0; i < 4; i++) {
cm.operation(function() {
cm.replaceSelection("x");
cm.setCursor(Pos(0, cm.getCursor().ch - 1));
});
}
eqPos(cm.getCursor(), Pos(0, 0));
eq(cm.getValue(), "xxxxa");
cm.undo();
eq(cm.getValue(), "a");
}, {value: "a"});
testCM("alwaysMergeSelEventWithChangeOrigin", function(cm) {
cm.replaceSelection("U", null, "foo");
cm.setSelection(Pos(0, 0), Pos(0, 1), {origin: "foo"});
cm.undoSelection();
eq(cm.getValue(), "a");
cm.replaceSelection("V", null, "foo");
cm.setSelection(Pos(0, 0), Pos(0, 1), {origin: "bar"});
cm.undoSelection();
eq(cm.getValue(), "Va");
}, {value: "a"});
testCM("getTokenTypeAt", function(cm) {
eq(cm.getTokenTypeAt(Pos(0, 0)), "number");
eq(cm.getTokenTypeAt(Pos(0, 6)), "string");
cm.addOverlay({
token: function(stream) {
if (stream.match("foo")) return "foo";
else stream.next();
}
});
eq(byClassName(cm.getWrapperElement(), "cm-foo").length, 1);
eq(cm.getTokenTypeAt(Pos(0, 6)), "string");
}, {value: "1 + 'foo'", mode: "javascript"});
| snappermorgan/snapgen2 | wp-content/plugins/wp-views/embedded/res/js/codemirror/test/test.js | JavaScript | gpl-2.0 | 66,950 |
/* big.js v2.4.0 https://github.com/MikeMcl/big.js/LICENCE */
;(function ( global ) {
'use strict';
/*
big.js v2.4.0
A small, fast, easy-to-use library for arbitrary-precision decimal arithmetic.
https://github.com/MikeMcl/big.js/
Copyright (c) 2012 Michael Mclaughlin <[email protected]>
MIT Expat Licence
*/
/****************************** EDITABLE DEFAULTS **********************************/
// The default values below must be integers within the stated ranges (inclusive).
/*
* The maximum number of decimal places of the results of methods involving
* division, i.e. 'div' and 'sqrt', and 'pow' with negative exponents.
*/
Big['DP'] = 20; // 0 to MAX_DP
/*
* The rounding mode used when rounding to the above decimal places.
*
* 0 Round towards zero (i.e. truncate, no rounding). (ROUND_DOWN)
* 1 Round to nearest neighbour. If equidistant, round up. (ROUND_HALF_UP)
* 2 Round to nearest neighbour. If equidistant, to even neighbour. (ROUND_HALF_EVEN)
* 3 Round away from zero. (ROUND_UP)
*/
Big['RM'] = 1; // 0, 1, 2 or 3
// The maximum value of 'Big.DP'.
var MAX_DP = 1E6, // 0 to 1e+6
// The maximum magnitude of the exponent argument to the 'pow' method.
MAX_POWER = 1E6, // 1 to 1e+6
/*
* The exponent value at and beneath which 'toString' returns exponential notation.
* Javascript's Number type: -7
* -1e+6 is the minimum recommended exponent value of a Big.
*/
TO_EXP_NEG = -7, // 0 to -1e+6
/*
* The exponent value at and above which 'toString' returns exponential notation.
* Javascript's Number type: 21
* 1e+6 is the maximum recommended exponent value of a Big, though there is no
* enforcing or checking of a limit.
*/
TO_EXP_POS = 21, // 0 to 1e+6
/***********************************************************************************/
P = Big.prototype,
isValid = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
ONE = new Big(1);
// CONSTRUCTOR
/*
* The exported function.
* Create and return a new instance of a Big object.
*
* n {number|string|Big} A numeric value.
*/
function Big( n ) {
var i, j, nL,
x = this;
// Enable constructor usage without new.
if ( !(x instanceof Big) ) {
return new Big( n )
}
// Duplicate.
if ( n instanceof Big ) {
x['s'] = n['s'];
x['e'] = n['e'];
x['c'] = n['c'].slice();
return
}
// Minus zero?
if ( n === 0 && 1 / n < 0 ) {
n = '-0'
// Ensure 'n' is string and check validity.
} else if ( !isValid.test(n += '') ) {
throwErr( NaN )
}
// Determine sign.
x['s'] = n.charAt(0) == '-' ? ( n = n.slice(1), -1 ) : 1;
// Decimal point?
if ( ( i = n.indexOf('.') ) > -1 ) {
n = n.replace( '.', '' )
}
// Exponential form?
if ( ( j = n.search(/e/i) ) > 0 ) {
// Determine exponent.
if ( i < 0 ) {
i = j
}
i += +n.slice( j + 1 );
n = n.substring( 0, j )
} else if ( i < 0 ) {
// Integer.
i = n.length
}
// Determine leading zeros.
for ( j = 0; n.charAt(j) == '0'; j++ ) {
}
if ( j == ( nL = n.length ) ) {
// Zero.
x['c'] = [ x['e'] = 0 ]
} else {
// Determine trailing zeros.
for ( ; n.charAt(--nL) == '0'; ) {
}
x['e'] = i - j - 1;
x['c'] = [];
// Convert string to array of digits (without leading and trailing zeros).
for ( i = 0; j <= nL; x['c'][i++] = +n.charAt(j++) ) {
}
}
}
// PRIVATE FUNCTIONS
/*
* Round Big 'x' to a maximum of 'dp' decimal places using rounding mode
* 'rm'. (Called by 'div', 'sqrt' and 'round'.)
*
* x {Big} The Big to round.
* dp {number} Integer, 0 to MAX_DP inclusive.
* rm {number} 0, 1, 2 or 3 ( ROUND_DOWN, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_UP )
* [more] {boolean} Whether the result of division was truncated.
*/
function rnd( x, dp, rm, more ) {
var xc = x['c'],
i = x['e'] + dp + 1;
if ( rm === 1 ) {
// 'xc[i]' is the digit after the digit that may be rounded up.
more = xc[i] >= 5
} else if ( rm === 2 ) {
more = xc[i] > 5 || xc[i] == 5 && ( more || i < 0 || xc[i + 1] != null || xc[i - 1] & 1 )
} else if ( rm === 3 ) {
more = more || xc[i] != null || i < 0
} else if ( more = false, rm !== 0 ) {
throwErr( '!Big.RM!' )
}
if ( i < 1 || !xc[0] ) {
x['c'] = more
// 1, 0.1, 0.01, 0.001, 0.0001 etc.
? ( x['e'] = -dp, [1] )
// Zero.
: [ x['e'] = 0 ];
} else {
// Remove any digits after the required decimal places.
xc.length = i--;
// Round up?
if ( more ) {
// Rounding up may mean the previous digit has to be rounded up and so on.
for ( ; ++xc[i] > 9; ) {
xc[i] = 0;
if ( !i-- ) {
++x['e'];
xc.unshift(1)
}
}
}
// Remove trailing zeros.
for ( i = xc.length; !xc[--i]; xc.pop() ) {
}
}
return x
}
/*
* Throw a BigError.
*
* message {string} The error message.
*/
function throwErr( message ) {
var err = new Error( message );
err['name'] = 'BigError';
throw err
}
// PROTOTYPE/INSTANCE METHODS
/*
* Return a new Big whose value is the absolute value of this Big.
*/
P['abs'] = function () {
var x = new Big(this);
x['s'] = 1;
return x
};
/*
* Return
* 1 if the value of this 'Big' is greater than the value of 'Big' 'y',
* -1 if the value of this 'Big' is less than the value of 'Big' 'y', or
* 0 if they have the same value.
*/
P['cmp'] = function ( y ) {
var xNeg,
x = this,
xc = x['c'],
yc = ( y = new Big( y ) )['c'],
i = x['s'],
j = y['s'],
k = x['e'],
l = y['e'];
// Either zero?
if ( !xc[0] || !yc[0] ) {
return !xc[0] ? !yc[0] ? 0 : -j : i
}
// Signs differ?
if ( i != j ) {
return i
}
xNeg = i < 0;
// Compare exponents.
if ( k != l ) {
return k > l ^ xNeg ? 1 : -1
}
// Compare digit by digit.
for ( i = -1,
j = ( k = xc.length ) < ( l = yc.length ) ? k : l;
++i < j; ) {
if ( xc[i] != yc[i] ) {
return xc[i] > yc[i] ^ xNeg ? 1 : -1
}
}
// Compare lengths.
return k == l ? 0 : k > l ^ xNeg ? 1 : -1
};
/*
* Return a new Big whose value is the value of this Big divided by the
* value of Big 'y', rounded, if necessary, to a maximum of 'Big.DP'
* decimal places using rounding mode 'Big.RM'.
*/
P['div'] = function ( y ) {
var x = this,
dvd = x['c'],
dvs = ( y = new Big(y) )['c'],
s = x['s'] == y['s'] ? 1 : -1,
dp = Big['DP'];
if ( dp !== ~~dp || dp < 0 || dp > MAX_DP ) {
throwErr( '!Big.DP!' )
}
// Either 0?
if ( !dvd[0] || !dvs[0] ) {
// Both 0?
if ( dvd[0] == dvs[0] ) {
throwErr( NaN )
}
// 'dvs' is 0?
if ( !dvs[0] ) {
// Throw +-Infinity.
throwErr( s / 0 )
}
// 'dvd' is 0. Return +-0.
return new Big( s * 0 )
}
var dvsL, dvsT, next, cmp, remI,
dvsZ = dvs.slice(),
dvdI = dvsL = dvs.length,
dvdL = dvd.length,
rem = dvd.slice( 0, dvsL ),
remL = rem.length,
quo = new Big(ONE),
qc = quo['c'] = [],
qi = 0,
digits = dp + ( quo['e'] = x['e'] - y['e'] ) + 1;
quo['s'] = s;
s = digits < 0 ? 0 : digits;
// Create version of divisor with leading zero.
dvsZ.unshift(0);
// Add zeros to make remainder as long as divisor.
for ( ; remL++ < dvsL; rem.push(0) ) {
}
do {
// 'next' is how many times the divisor goes into the current remainder.
for ( next = 0; next < 10; next++ ) {
// Compare divisor and remainder.
if ( dvsL != ( remL = rem.length ) ) {
cmp = dvsL > remL ? 1 : -1
} else {
for ( remI = -1, cmp = 0; ++remI < dvsL; ) {
if ( dvs[remI] != rem[remI] ) {
cmp = dvs[remI] > rem[remI] ? 1 : -1;
break
}
}
}
// Subtract divisor from remainder (if divisor < remainder).
if ( cmp < 0 ) {
// Remainder cannot be more than one digit longer than divisor.
// Equalise lengths using divisor with extra leading zero?
for ( dvsT = remL == dvsL ? dvs : dvsZ; remL; ) {
if ( rem[--remL] < dvsT[remL] ) {
for ( remI = remL;
remI && !rem[--remI];
rem[remI] = 9 ) {
}
--rem[remI];
rem[remL] += 10
}
rem[remL] -= dvsT[remL]
}
for ( ; !rem[0]; rem.shift() ) {
}
} else {
break
}
}
// Add the 'next' digit to the result array.
qc[qi++] = cmp ? next : ++next;
// Update the remainder.
rem[0] && cmp
? ( rem[remL] = dvd[dvdI] || 0 )
: ( rem = [ dvd[dvdI] ] )
} while ( ( dvdI++ < dvdL || rem[0] != null ) && s-- );
// Leading zero? Do not remove if result is simply zero (qi == 1).
if ( !qc[0] && qi != 1) {
// There can't be more than one zero.
qc.shift();
quo['e']--;
}
// Round?
if ( qi > digits ) {
rnd( quo, dp, Big['RM'], rem[0] != null )
}
return quo
}
/*
* Return true if the value of this Big is equal to the value of Big 'y',
* otherwise returns false.
*/
P['eq'] = function ( y ) {
return !this.cmp( y )
};
/*
* Return true if the value of this Big is greater than the value of Big 'y',
* otherwise returns false.
*/
P['gt'] = function ( y ) {
return this.cmp( y ) > 0
};
/*
* Return true if the value of this Big is greater than or equal to the
* value of Big 'y', otherwise returns false.
*/
P['gte'] = function ( y ) {
return this.cmp( y ) > -1
};
/*
* Return true if the value of this Big is less than the value of Big 'y',
* otherwise returns false.
*/
P['lt'] = function ( y ) {
return this.cmp( y ) < 0
};
/*
* Return true if the value of this Big is less than or equal to the value
* of Big 'y', otherwise returns false.
*/
P['lte'] = function ( y ) {
return this.cmp( y ) < 1
};
/*
* Return a new Big whose value is the value of this Big minus the value
* of Big 'y'.
*/
P['minus'] = function ( y ) {
var d, i, j, xLTy,
x = this,
a = x['s'],
b = ( y = new Big( y ) )['s'];
// Signs differ?
if ( a != b ) {
return y['s'] = -b, x['plus'](y)
}
var xc = x['c'].slice(),
xe = x['e'],
yc = y['c'],
ye = y['e'];
// Either zero?
if ( !xc[0] || !yc[0] ) {
// 'y' is non-zero?
return yc[0]
? ( y['s'] = -b, y )
// 'x' is non-zero?
: new Big( xc[0]
? x
// Both are zero.
: 0 )
}
// Determine which is the bigger number.
// Prepend zeros to equalise exponents.
if ( a = xe - ye ) {
d = ( xLTy = a < 0 ) ? ( a = -a, xc ) : ( ye = xe, yc );
for ( d.reverse(), b = a; b--; d.push(0) ) {
}
d.reverse()
} else {
// Exponents equal. Check digit by digit.
j = ( ( xLTy = xc.length < yc.length ) ? xc : yc ).length;
for ( a = b = 0; b < j; b++ ) {
if ( xc[b] != yc[b] ) {
xLTy = xc[b] < yc[b];
break
}
}
}
// 'x' < 'y'? Point 'xc' to the array of the bigger number.
if ( xLTy ) {
d = xc, xc = yc, yc = d;
y['s'] = -y['s']
}
/*
* Append zeros to 'xc' if shorter. No need to add zeros to 'yc' if shorter
* as subtraction only needs to start at 'yc.length'.
*/
if ( ( b = -( ( j = xc.length ) - yc.length ) ) > 0 ) {
for ( ; b--; xc[j++] = 0 ) {
}
}
// Subtract 'yc' from 'xc'.
for ( b = yc.length; b > a; ){
if ( xc[--b] < yc[b] ) {
for ( i = b; i && !xc[--i]; xc[i] = 9 ) {
}
--xc[i];
xc[b] += 10
}
xc[b] -= yc[b]
}
// Remove trailing zeros.
for ( ; xc[--j] == 0; xc.pop() ) {
}
// Remove leading zeros and adjust exponent accordingly.
for ( ; xc[0] == 0; xc.shift(), --ye ) {
}
if ( !xc[0] ) {
// Result must be zero.
xc = [ye = 0]
}
return y['c'] = xc, y['e'] = ye, y
};
/*
* Return a new Big whose value is the value of this Big modulo the
* value of Big 'y'.
*/
P['mod'] = function ( y ) {
y = new Big( y );
var c,
x = this,
i = x['s'],
j = y['s'];
if ( !y['c'][0] ) {
throwErr( NaN )
}
x['s'] = y['s'] = 1;
c = y.cmp( x ) == 1;
x['s'] = i, y['s'] = j;
return c
? new Big(x)
: ( i = Big['DP'], j = Big['RM'],
Big['DP'] = Big['RM'] = 0,
x = x['div'](y),
Big['DP'] = i, Big['RM'] = j,
this['minus']( x['times'](y) ) )
};
/*
* Return a new Big whose value is the value of this Big plus the value
* of Big 'y'.
*/
P['plus'] = function ( y ) {
var d,
x = this,
a = x['s'],
b = ( y = new Big( y ) )['s'];
// Signs differ?
if ( a != b ) {
return y['s'] = -b, x['minus'](y)
}
var xe = x['e'],
xc = x['c'],
ye = y['e'],
yc = y['c'];
// Either zero?
if ( !xc[0] || !yc[0] ) {
// 'y' is non-zero?
return yc[0]
? y
: new Big( xc[0]
// 'x' is non-zero?
? x
// Both are zero. Return zero.
: a * 0 )
}
// Prepend zeros to equalise exponents.
// Note: Faster to use reverse then do unshifts.
if ( xc = xc.slice(), a = xe - ye ) {
d = a > 0 ? ( ye = xe, yc ) : ( a = -a, xc );
for ( d.reverse(); a--; d.push(0) ) {
}
d.reverse()
}
// Point 'xc' to the longer array.
if ( xc.length - yc.length < 0 ) {
d = yc, yc = xc, xc = d
}
/*
* Only start adding at 'yc.length - 1' as the
* further digits of 'xc' can be left as they are.
*/
for ( a = yc.length, b = 0; a;
b = ( xc[--a] = xc[a] + yc[a] + b ) / 10 ^ 0, xc[a] %= 10 ) {
}
// No need to check for zero, as +x + +y != 0 && -x + -y != 0
if ( b ) {
xc.unshift(b);
++ye
}
// Remove trailing zeros.
for ( a = xc.length; xc[--a] == 0; xc.pop() ) {
}
return y['c'] = xc, y['e'] = ye, y
};
/*
* Return a Big whose value is the value of this Big raised to the power
* 'e'. If 'e' is negative, round, if necessary, to a maximum of 'Big.DP'
* decimal places using rounding mode 'Big.RM'.
*
* e {number} Integer, -MAX_POWER to MAX_POWER inclusive.
*/
P['pow'] = function ( e ) {
var isNeg = e < 0,
x = new Big(this),
y = ONE;
if ( e !== ~~e || e < -MAX_POWER || e > MAX_POWER ) {
throwErr( '!pow!' )
}
for ( e = isNeg ? -e : e; ; ) {
if ( e & 1 ) {
y = y['times'](x)
}
e >>= 1;
if ( !e ) {
break
}
x = x['times'](x)
}
return isNeg ? ONE['div'](y) : y
};
/*
* Return a new Big whose value is the value of this Big rounded, if
* necessary, to a maximum of 'dp' decimal places using rounding mode 'rm'.
* If 'dp' is not specified, round to 0 decimal places.
* If 'rm' is not specified, use 'Big.RM'.
*
* [dp] {number} Integer, 0 to MAX_DP inclusive.
* [rm] 0, 1, 2 or 3 ( ROUND_DOWN, ROUND_HALF_UP, ROUND_HALF_EVEN, ROUND_UP )
*/
P['round'] = function ( dp, rm ) {
var x = new Big(this);
if ( dp == null ) {
dp = 0
} else if ( dp !== ~~dp || dp < 0 || dp > MAX_DP ) {
throwErr( '!round!' )
}
rnd( x, dp, rm == null ? Big['RM'] : rm );
return x
};
/*
* Return a new Big whose value is the square root of the value of this
* Big, rounded, if necessary, to a maximum of 'Big.DP' decimal places
* using rounding mode 'Big.RM'.
*/
P['sqrt'] = function () {
var estimate, r, approx,
x = this,
xc = x['c'],
i = x['s'],
e = x['e'],
half = new Big('0.5');
// Zero?
if ( !xc[0] ) {
return new Big(x)
}
// Negative?
if ( i < 0 ) {
throwErr( NaN )
}
// Estimate.
i = Math.sqrt( x.toString() );
// Math.sqrt underflow/overflow?
// Pass 'x' to Math.sqrt as integer, then adjust the exponent of the result.
if ( i == 0 || i == 1 / 0 ) {
estimate = xc.join('');
if ( !( estimate.length + e & 1 ) ) {
estimate += '0'
}
r = new Big( Math.sqrt(estimate).toString() );
r['e'] = ( ( ( e + 1 ) / 2 ) | 0 ) - ( e < 0 || e & 1 )
} else {
r = new Big( i.toString() )
}
i = r['e'] + ( Big['DP'] += 4 );
// Newton-Raphson loop.
do {
approx = r;
r = half['times']( approx['plus']( x['div'](approx) ) )
} while ( approx['c'].slice( 0, i ).join('') !==
r['c'].slice( 0, i ).join('') );
rnd( r, Big['DP'] -= 4, Big['RM'] );
return r
};
/*
* Return a new Big whose value is the value of this Big times the value
* of Big 'y'.
*/
P['times'] = function ( y ) {
var c,
x = this,
xc = x['c'],
yc = ( y = new Big( y ) )['c'],
a = xc.length,
b = yc.length,
i = x['e'],
j = y['e'];
y['s'] = x['s'] == y['s'] ? 1 : -1;
// Either 0?
if ( !xc[0] || !yc[0] ) {
return new Big( y['s'] * 0 )
}
y['e'] = i + j;
if ( a < b ) {
c = xc, xc = yc, yc = c, j = a, a = b, b = j
}
for ( j = a + b, c = []; j--; c.push(0) ) {
}
// Multiply!
for ( i = b - 1; i > -1; i-- ) {
for ( b = 0, j = a + i;
j > i;
b = c[j] + yc[i] * xc[j - i - 1] + b,
c[j--] = b % 10 | 0,
b = b / 10 | 0 ) {
}
if ( b ) {
c[j] = ( c[j] + b ) % 10
}
}
b && ++y['e'];
// Remove any leading zero.
!c[0] && c.shift();
// Remove trailing zeros.
for ( j = c.length; !c[--j]; c.pop() ) {
}
return y['c'] = c, y
};
/*
* Return a string representing the value of this Big.
* Return exponential notation if this Big has a positive exponent equal
* to or greater than 'TO_EXP_POS', or a negative exponent equal to or less
* than 'TO_EXP_NEG'.
*/
P['toString'] = P['valueOf'] = function () {
var x = this,
e = x['e'],
str = x['c'].join(''),
strL = str.length;
// Exponential notation?
if ( e <= TO_EXP_NEG || e >= TO_EXP_POS ) {
str = str.charAt(0) + ( strL > 1 ? '.' + str.slice(1) : '' ) +
( e < 0 ? 'e' : 'e+' ) + e
// Negative exponent?
} else if ( e < 0 ) {
// Prepend zeros.
for ( ; ++e; str = '0' + str ) {
}
str = '0.' + str
// Positive exponent?
} else if ( e > 0 ) {
if ( ++e > strL ) {
// Append zeros.
for ( e -= strL; e-- ; str += '0' ) {
}
} else if ( e < strL ) {
str = str.slice( 0, e ) + '.' + str.slice(e)
}
// Exponent zero.
} else if ( strL > 1 ) {
str = str.charAt(0) + '.' + str.slice(1)
}
// Avoid '-0'
return x['s'] < 0 && x['c'][0] ? '-' + str : str
};
/*
***************************************************************************
* If 'toExponential', 'toFixed', 'toPrecision' and 'format' are not
* required they can safely be commented-out or deleted. No redundant code
* will be left. 'format' is used only by 'toExponential', 'toFixed' and
* 'toPrecision'.
***************************************************************************
*/
/*
* PRIVATE FUNCTION
*
* Return a string representing the value of Big 'x' in normal or
* exponential notation to a fixed number of decimal places or significant
* digits 'dp'.
* (Called by toString, toExponential, toFixed and toPrecision.)
*
* x {Big} The Big to format.
* dp {number} Integer, 0 to MAX_DP inclusive.
* toE {number} undefined (toFixed), 1 (toExponential) or 2 (toPrecision).
*/
function format( x, dp, toE ) {
// The index (in normal notation) of the digit that may be rounded up.
var i = dp - ( x = new Big(x) )['e'],
c = x['c'];
// Round?
if ( c.length > ++dp ) {
rnd( x, i, Big['RM'] )
}
// Recalculate 'i' if toFixed as 'x.e' may have changed if value rounded up.
i = !c[0] ? i + 1 : toE ? dp : ( c = x['c'], x['e'] + i + 1 );
// Append zeros?
for ( ; c.length < i; c.push(0) ) {
}
i = x['e'];
/*
* 'toPrecision' returns exponential notation if the number of
* significant digits specified is less than the number of digits
* necessary to represent the integer part of the value in normal
* notation.
*/
return toE == 1 || toE == 2 && ( dp <= i || i <= TO_EXP_NEG )
// Exponential notation.
? ( x['s'] < 0 && c[0] ? '-' : '' ) + ( c.length > 1
? ( c.splice( 1, 0, '.' ), c.join('') )
: c[0] ) + ( i < 0 ? 'e' : 'e+' ) + i
// Normal notation.
: x.toString()
}
/*
* Return a string representing the value of this Big in exponential
* notation to 'dp' fixed decimal places and rounded, if necessary, using
* 'Big.RM'.
*
* [dp] {number} Integer, 0 to MAX_DP inclusive.
*/
P['toExponential'] = function ( dp ) {
if ( dp == null ) {
dp = this['c'].length - 1
} else if ( dp !== ~~dp || dp < 0 || dp > MAX_DP ) {
throwErr( '!toExp!' )
}
return format( this, dp, 1 )
};
/*
* Return a string representing the value of this Big in normal notation
* to 'dp' fixed decimal places and rounded, if necessary, using 'Big.RM'.
*
* [dp] {number} Integer, 0 to MAX_DP inclusive.
*/
P['toFixed'] = function ( dp ) {
var str,
x = this,
neg = TO_EXP_NEG,
pos = TO_EXP_POS;
TO_EXP_NEG = -( TO_EXP_POS = 1 / 0 );
if ( dp == null ) {
str = x.toString()
} else if ( dp === ~~dp && dp >= 0 && dp <= MAX_DP ) {
str = format( x, x['e'] + dp );
// (-0).toFixed() is '0', but (-0.1).toFixed() is '-0'.
// (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
if ( x['s'] < 0 && x['c'][0] && str.indexOf('-') < 0 ) {
// As e.g. -0.5 if rounded to -0 will cause toString to omit the minus sign.
str = '-' + str
}
}
TO_EXP_NEG = neg, TO_EXP_POS = pos;
if ( !str ) {
throwErr( '!toFix!' )
}
return str
};
/*
* Return a string representing the value of this Big to 'sd' significant
* digits and rounded, if necessary, using 'Big.RM'. If 'sd' is less than
* the number of digits necessary to represent the integer part of the value
* in normal notation, then use exponential notation.
*
* sd {number} Integer, 1 to MAX_DP inclusive.
*/
P['toPrecision'] = function ( sd ) {
if ( sd == null ) {
return this.toString()
} else if ( sd !== ~~sd || sd < 1 || sd > MAX_DP ) {
throwErr( '!toPre!' )
}
return format( this, sd - 1, 2 )
};
// EXPORT
// Node and other CommonJS-like environments that support module.exports.
if ( typeof module !== 'undefined' && module.exports ) {
module.exports = Big
//AMD.
} else if ( typeof define == 'function' && define.amd ) {
define( function () {
return Big
})
//Browser.
} else {
global['Big'] = Big
}
})( this );
| dlueth/cdnjs | ajax/libs/big.js/2.4.0/big.js | JavaScript | mit | 27,639 |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v5.0.0
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var dragAndDropService_1 = require("../dragAndDrop/dragAndDropService");
var columnController_1 = require("../columnController/columnController");
var context_1 = require("../context/context");
var gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var BodyDropPivotTarget = (function () {
function BodyDropPivotTarget(pinned) {
this.columnsToAggregate = [];
this.columnsToGroup = [];
this.columnsToPivot = [];
this.pinned = pinned;
}
/** Callback for when drag enters */
BodyDropPivotTarget.prototype.onDragEnter = function (draggingEvent) {
var _this = this;
this.clearColumnsList();
// in pivot mode, we don't accept any drops if functions are read only
if (this.gridOptionsWrapper.isFunctionsReadOnly()) {
return;
}
var dragColumns = draggingEvent.dragSource.dragItem;
dragColumns.forEach(function (column) {
// we don't allow adding secondary columns
if (!column.isPrimary()) {
return;
}
if (column.isAnyFunctionActive()) {
return;
}
if (column.isAllowValue()) {
_this.columnsToAggregate.push(column);
}
else if (column.isAllowRowGroup()) {
_this.columnsToGroup.push(column);
}
else if (column.isAllowRowGroup()) {
_this.columnsToPivot.push(column);
}
});
};
BodyDropPivotTarget.prototype.getIconName = function () {
var totalColumns = this.columnsToAggregate.length + this.columnsToGroup.length + this.columnsToPivot.length;
if (totalColumns > 0) {
return this.pinned ? dragAndDropService_1.DragAndDropService.ICON_PINNED : dragAndDropService_1.DragAndDropService.ICON_MOVE;
}
else {
return null;
}
};
/** Callback for when drag leaves */
BodyDropPivotTarget.prototype.onDragLeave = function (draggingEvent) {
// if we are taking columns out of the center, then we remove them from the report
this.clearColumnsList();
};
BodyDropPivotTarget.prototype.clearColumnsList = function () {
this.columnsToAggregate.length = 0;
this.columnsToGroup.length = 0;
this.columnsToPivot.length = 0;
};
/** Callback for when dragging */
BodyDropPivotTarget.prototype.onDragging = function (draggingEvent) {
};
/** Callback for when drag stops */
BodyDropPivotTarget.prototype.onDragStop = function (draggingEvent) {
if (this.columnsToAggregate.length > 0) {
this.columnController.addValueColumns(this.columnsToAggregate);
}
if (this.columnsToGroup.length > 0) {
this.columnController.addRowGroupColumns(this.columnsToGroup);
}
if (this.columnsToPivot.length > 0) {
this.columnController.addPivotColumns(this.columnsToPivot);
}
};
__decorate([
context_1.Autowired('columnController'),
__metadata('design:type', columnController_1.ColumnController)
], BodyDropPivotTarget.prototype, "columnController", void 0);
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper)
], BodyDropPivotTarget.prototype, "gridOptionsWrapper", void 0);
return BodyDropPivotTarget;
})();
exports.BodyDropPivotTarget = BodyDropPivotTarget;
| joeyparrish/cdnjs | ajax/libs/ag-grid/5.0.0/lib/headerRendering/bodyDropPivotTarget.js | JavaScript | mit | 4,442 |
'use strict';
var EventEmitter = require('events').EventEmitter;
var fs = require('fs');
var sysPath = require('path');
var each = require('async-each');
var anymatch = require('anymatch');
var globparent = require('glob-parent');
var isglob = require('is-glob');
var arrify = require('arrify');
var isAbsolute = require('path-is-absolute');
var NodeFsHandler = require('./lib/nodefs-handler');
var FsEventsHandler = require('./lib/fsevents-handler');
// Public: Main class.
// Watches files & directories for changes.
//
// * _opts - object, chokidar options hash
//
// Emitted events:
// `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
//
// Examples
//
// var watcher = new FSWatcher()
// .add(directories)
// .on('add', function(path) {console.log('File', path, 'was added');})
// .on('change', function(path) {console.log('File', path, 'was changed');})
// .on('unlink', function(path) {console.log('File', path, 'was removed');})
// .on('all', function(event, path) {console.log(path, ' emitted ', event);})
//
function FSWatcher(_opts) {
var opts = {};
// in case _opts that is passed in is a frozen object
if (_opts) for (var opt in _opts) opts[opt] = _opts[opt];
this._watched = Object.create(null);
this._closers = Object.create(null);
this._ignoredPaths = Object.create(null);
Object.defineProperty(this, '_globIgnored', {
get: function() { return Object.keys(this._ignoredPaths); }
});
this.closed = false;
this._throttled = Object.create(null);
this._symlinkPaths = Object.create(null);
function undef(key) {
return opts[key] === undefined;
}
// Set up default options.
if (undef('persistent')) opts.persistent = true;
if (undef('ignoreInitial')) opts.ignoreInitial = false;
if (undef('ignorePermissionErrors')) opts.ignorePermissionErrors = false;
if (undef('interval')) opts.interval = 100;
if (undef('binaryInterval')) opts.binaryInterval = 300;
this.enableBinaryInterval = opts.binaryInterval !== opts.interval;
// Enable fsevents on OS X when polling isn't explicitly enabled.
if (undef('useFsEvents')) opts.useFsEvents = !opts.usePolling;
// If we can't use fsevents, ensure the options reflect it's disabled.
if (!FsEventsHandler.canUse()) opts.useFsEvents = false;
// Use polling on Mac if not using fsevents.
// Other platforms use non-polling fs.watch.
if (undef('usePolling') && !opts.useFsEvents) {
opts.usePolling = process.platform === 'darwin';
}
// Editor atomic write normalization enabled by default with fs.watch
if (undef('atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
if (opts.atomic) this._pendingUnlinks = Object.create(null);
if (undef('followSymlinks')) opts.followSymlinks = true;
this._isntIgnored = function(path, stat) {
return !this._isIgnored(path, stat);
}.bind(this);
var readyCalls = 0;
this._emitReady = function() {
if (++readyCalls >= this._readyCount) {
this._emitReady = Function.prototype;
// use process.nextTick to allow time for listener to be bound
process.nextTick(this.emit.bind(this, 'ready'));
}
}.bind(this);
this.options = opts;
// You’re frozen when your heart’s not open.
Object.freeze(opts);
}
FSWatcher.prototype = Object.create(EventEmitter.prototype);
// Common helpers
// --------------
// Private method: Normalize and emit events
//
// * event - string, type of event
// * path - string, file or directory path
// * val[1..3] - arguments to be passed with event
//
// Returns the error if defined, otherwise the value of the
// FSWatcher instance's `closed` flag
FSWatcher.prototype._emit = function(event, path, val1, val2, val3) {
if (this.options.cwd) path = sysPath.relative(this.options.cwd, path);
var args = [event, path];
if (val3 !== undefined) args.push(val1, val2, val3);
else if (val2 !== undefined) args.push(val1, val2);
else if (val1 !== undefined) args.push(val1);
if (this.options.atomic) {
if (event === 'unlink') {
this._pendingUnlinks[path] = args;
setTimeout(function() {
Object.keys(this._pendingUnlinks).forEach(function(path) {
this.emit.apply(this, this._pendingUnlinks[path]);
this.emit.apply(this, ['all'].concat(this._pendingUnlinks[path]));
delete this._pendingUnlinks[path];
}.bind(this));
}.bind(this), 100);
return this;
} else if (event === 'add' && this._pendingUnlinks[path]) {
event = args[0] = 'change';
delete this._pendingUnlinks[path];
}
}
if (event === 'change') {
if (!this._throttle('change', path, 50)) return this;
}
var emitEvent = function() {
this.emit.apply(this, args);
if (event !== 'error') this.emit.apply(this, ['all'].concat(args));
}.bind(this);
if (
this.options.alwaysStat && val1 === undefined &&
(event === 'add' || event === 'addDir' || event === 'change')
) {
fs.stat(path, function(error, stats) {
// Suppress event when fs.stat fails, to avoid sending undefined 'stat'
if (error || !stats) return;
args.push(stats);
emitEvent();
});
} else {
emitEvent();
}
return this;
};
// Private method: Common handler for errors
//
// * error - object, Error instance
//
// Returns the error if defined, otherwise the value of the
// FSWatcher instance's `closed` flag
FSWatcher.prototype._handleError = function(error) {
var code = error && error.code;
var ipe = this.options.ignorePermissionErrors;
if (error &&
code !== 'ENOENT' &&
code !== 'ENOTDIR' &&
(!ipe || (code !== 'EPERM' && code !== 'EACCES'))
) this.emit('error', error);
return error || this.closed;
};
// Private method: Helper utility for throttling
//
// * action - string, type of action being throttled
// * path - string, path being acted upon
// * timeout - int, duration of time to suppress duplicate actions
//
// Returns throttle tracking object or false if action should be suppressed
FSWatcher.prototype._throttle = function(action, path, timeout) {
if (!(action in this._throttled)) {
this._throttled[action] = Object.create(null);
}
var throttled = this._throttled[action];
if (path in throttled) return false;
function clear() {
delete throttled[path];
clearTimeout(timeoutObject);
}
var timeoutObject = setTimeout(clear, timeout);
throttled[path] = {timeoutObject: timeoutObject, clear: clear};
return throttled[path];
};
// Private method: Determines whether user has asked to ignore this path
//
// * path - string, path to file or directory
// * stats - object, result of fs.stat
//
// Returns boolean
FSWatcher.prototype._isIgnored = function(path, stats) {
if (
this.options.atomic &&
/\..*\.(sw[px])$|\~$|\.subl.*\.tmp/.test(path)
) return true;
if (!this._userIgnored) {
var cwd = this.options.cwd;
var ignored = this.options.ignored;
if (cwd && ignored) {
ignored = arrify(ignored).map(function (path) {
if (typeof path !== 'string') return path;
return isAbsolute(path) ? path : sysPath.join(cwd, path);
});
}
this._userIgnored = anymatch(this._globIgnored
.concat(ignored)
.concat(arrify(ignored)
.filter(function(path) {
return typeof path === 'string' && !isglob(path);
}).map(function(path) {
return path + '/**/*';
})
)
);
}
return this._userIgnored([path, stats]);
};
// Private method: Provides a set of common helpers and properties relating to
// symlink and glob handling
//
// * path - string, file, directory, or glob pattern being watched
// * depth - int, at any depth > 0, this isn't a glob
//
// Returns object containing helpers for this path
FSWatcher.prototype._getWatchHelpers = function(path, depth) {
path = path.replace(/^\.[\/\\]/, '');
var watchPath = depth ? path : globparent(path);
var hasGlob = watchPath !== path;
var globFilter = hasGlob ? anymatch(path) : false;
var entryPath = function(entry) {
return sysPath.join(watchPath, sysPath.relative(watchPath, entry.fullPath));
}
var filterPath = function(entry) {
return (!hasGlob || globFilter(entryPath(entry))) &&
this._isntIgnored(entryPath(entry), entry.stat) &&
(this.options.ignorePermissionErrors ||
this._hasReadPermissions(entry.stat));
}.bind(this);
var getDirParts = function(path) {
if (!hasGlob) return false;
var parts = sysPath.relative(watchPath, path).split(/[\/\\]/);
return parts;
}
var dirParts = getDirParts(path);
if (dirParts && dirParts.length > 1) dirParts.pop();
var filterDir = function(entry) {
if (hasGlob) {
var entryParts = getDirParts(entry.fullPath);
var globstar = false;
var unmatchedGlob = !dirParts.every(function(part, i) {
if (part === '**') globstar = true;
return globstar || !entryParts[i] || anymatch(part, entryParts[i]);
});
}
return !unmatchedGlob && this._isntIgnored(entryPath(entry), entry.stat);
}.bind(this);
return {
followSymlinks: this.options.followSymlinks,
statMethod: this.options.followSymlinks ? 'stat' : 'lstat',
path: path,
watchPath: watchPath,
entryPath: entryPath,
hasGlob: hasGlob,
globFilter: globFilter,
filterPath: filterPath,
filterDir: filterDir
};
}
// Directory helpers
// -----------------
// Private method: Provides directory tracking objects
//
// * directory - string, path of the directory
//
// Returns the directory's tracking object
FSWatcher.prototype._getWatchedDir = function(directory) {
var dir = sysPath.resolve(directory);
var watcherRemove = this._remove.bind(this);
if (!(dir in this._watched)) this._watched[dir] = {
_items: Object.create(null),
add: function(item) {this._items[item] = true;},
remove: function(item) {
delete this._items[item];
if (!this.children().length) {
fs.readdir(dir, function(err) {
if (err) watcherRemove(sysPath.dirname(dir), sysPath.basename(dir));
});
}
},
has: function(item) {return item in this._items;},
children: function() {return Object.keys(this._items);}
};
return this._watched[dir];
};
// File helpers
// ------------
// Private method: Check for read permissions
// Based on this answer on SO: http://stackoverflow.com/a/11781404/1358405
//
// * stats - object, result of fs.stat
//
// Returns boolean
FSWatcher.prototype._hasReadPermissions = function(stats) {
return Boolean(4 & parseInt(((stats && stats.mode) & 0x1ff).toString(8)[0], 10));
};
// Private method: Handles emitting unlink events for
// files and directories, and via recursion, for
// files and directories within directories that are unlinked
//
// * directory - string, directory within which the following item is located
// * item - string, base path of item/directory
//
// Returns nothing
FSWatcher.prototype._remove = function(directory, item) {
// if what is being deleted is a directory, get that directory's paths
// for recursive deleting and cleaning of watched object
// if it is not a directory, nestedDirectoryChildren will be empty array
var path = sysPath.join(directory, item);
var fullPath = sysPath.resolve(path);
var isDirectory = this._watched[path] || this._watched[fullPath];
// prevent duplicate handling in case of arriving here nearly simultaneously
// via multiple paths (such as _handleFile and _handleDir)
if (!this._throttle('remove', path, 100)) return;
// if the only watched file is removed, watch for its return
var watchedDirs = Object.keys(this._watched);
if (!isDirectory && !this.options.useFsEvents && watchedDirs.length === 1) {
this.add(directory, item, true);
}
// This will create a new entry in the watched object in either case
// so we got to do the directory check beforehand
var nestedDirectoryChildren = this._getWatchedDir(path).children();
// Recursively remove children directories / files.
nestedDirectoryChildren.forEach(function(nestedItem) {
this._remove(path, nestedItem);
}, this);
// Check if item was on the watched list and remove it
var parent = this._getWatchedDir(directory);
var wasTracked = parent.has(item);
parent.remove(item);
// The Entry will either be a directory that just got removed
// or a bogus entry to a file, in either case we have to remove it
delete this._watched[path];
delete this._watched[fullPath];
var eventName = isDirectory ? 'unlinkDir' : 'unlink';
if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
};
// Public method: Adds paths to be watched on an existing FSWatcher instance
// * paths - string or array of strings, file/directory paths and/or globs
// * _origAdd - private boolean, for handling non-existent paths to be watched
// * _internal - private boolean, indicates a non-user add
// Returns an instance of FSWatcher for chaining.
FSWatcher.prototype.add = function(paths, _origAdd, _internal) {
var cwd = this.options.cwd;
this.closed = false;
paths = arrify(paths);
if (cwd) paths = paths.map(function(path) {
if (isAbsolute(path)) {
return path;
} else if (path[0] === '!') {
return '!' + sysPath.join(cwd, path.substring(1));
} else {
return sysPath.join(cwd, path);
}
});
// set aside negated glob strings
paths = paths.filter(function(path) {
if (path[0] === '!') this._ignoredPaths[path.substring(1)] = true;
else {
// if a path is being added that was previously ignored, stop ignoring it
delete this._ignoredPaths[path];
delete this._ignoredPaths[path + '/**/*'];
// reset the cached userIgnored anymatch fn
// to make ignoredPaths changes effective
this._userIgnored = null;
return true;
}
}, this);
if (this.options.useFsEvents && FsEventsHandler.canUse()) {
if (!this._readyCount) this._readyCount = paths.length;
if (this.options.persistent) this._readyCount *= 2;
paths.forEach(this._addToFsEvents, this);
} else {
if (!this._readyCount) this._readyCount = 0;
this._readyCount += paths.length;
each(paths, function(path, next) {
this._addToNodeFs(path, !_internal, 0, 0, _origAdd, function(err, res) {
if (res) this._emitReady();
next(err, res);
}.bind(this));
}.bind(this), function(error, results) {
results.forEach(function(item) {
if (!item) return;
this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
}, this);
}.bind(this));
}
return this;
};
// Public method: Close watchers or start ignoring events from specified paths.
// * paths - string or array of strings, file/directory paths and/or globs
// Returns instance of FSWatcher for chaining.
FSWatcher.prototype.unwatch = function(paths) {
if (this.closed) return this;
paths = arrify(paths);
paths.forEach(function(path) {
if (this._closers[path]) {
this._closers[path]();
} else {
this._ignoredPaths[path] = true;
if (path in this._watched) this._ignoredPaths[path + '/**/*'] = true;
// reset the cached userIgnored anymatch fn
// to make ignoredPaths changes effective
this._userIgnored = null;
}
}, this);
return this;
};
// Public method: Close watchers and remove all listeners from watched paths.
// Returns instance of FSWatcher for chaining.
FSWatcher.prototype.close = function() {
if (this.closed) return this;
this.closed = true;
Object.keys(this._closers).forEach(function(watchPath) {
this._closers[watchPath]();
delete this._closers[watchPath];
}, this);
this._watched = Object.create(null);
this.removeAllListeners();
return this;
};
// Attach watch handler prototype methods
function importHandler(handler) {
Object.keys(handler.prototype).forEach(function(method) {
FSWatcher.prototype[method] = handler.prototype[method];
});
}
importHandler(NodeFsHandler);
if (FsEventsHandler.canUse()) importHandler(FsEventsHandler);
// Export FSWatcher class
exports.FSWatcher = FSWatcher;
// Public function: Instantiates watcher with paths to be tracked.
// * paths - string or array of strings, file/directory paths and/or globs
// * options - object, chokidar options
// Returns an instance of FSWatcher for chaining.
exports.watch = function(paths, options) {
return new FSWatcher(options).add(paths);
};
| Socratacom/law-enforcement | wp-content/themes/sage/node_modules/browser-sync/node_modules/chokidar/index.js | JavaScript | gpl-2.0 | 16,466 |
/*!
* Chai - message composition utility
* Copyright(c) 2012-2013 Jake Luer <[email protected]>
* MIT Licensed
*/
/*!
* Module dependancies
*/
var flag = require('./flag')
, getActual = require('./getActual')
, inspect = require('./inspect')
, objDisplay = require('./objDisplay');
/**
* ### .getMessage(object, message, negateMessage)
*
* Construct the error message based on flags
* and template tags. Template tags will return
* a stringified inspection of the object referenced.
*
* Messsage template tags:
* - `#{this}` current asserted object
* - `#{act}` actual value
* - `#{exp}` expected value
*
* @param {Object} object (constructed Assertion)
* @param {Arguments} chai.Assertion.prototype.assert arguments
* @name getMessage
* @api public
*/
module.exports = function (obj, args) {
var negate = flag(obj, 'negate')
, val = flag(obj, 'object')
, expected = args[3]
, actual = getActual(obj, args)
, msg = negate ? args[2] : args[1]
, flagMsg = flag(obj, 'message');
msg = msg || '';
msg = msg
.replace(/#{this}/g, objDisplay(val))
.replace(/#{act}/g, objDisplay(actual))
.replace(/#{exp}/g, objDisplay(expected));
return flagMsg ? flagMsg + ': ' + msg : msg;
};
| espena/terminal | test/node_modules/chai/lib/chai/utils/getMessage.js | JavaScript | mit | 1,253 |
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* JDK-8023368: Instance __proto__ property should exist and be writable.
*
* @test
* @run
*/
// check Object.setPrototypeOf extension rather than using __proto__
// function to force same callsites
function check(obj) {
print(obj.func());
print(obj.x);
print(obj.toString());
}
function Func() {
}
Func.prototype.func = function() {
return "Func.prototype.func";
}
Func.prototype.x = "hello";
var obj = new Func();
var obj2 = Object.create(obj);
// check direct and indirect __proto__ change
check(obj);
check(obj2);
Object.setPrototypeOf(obj, {
func: function() {
return "obj.__proto__.func @ " + __LINE__;
},
x: 344
});
check(obj);
check(obj2);
// check indirect (1 and 2 levels) __proto__ function change
Object.setPrototypeOf(Object.getPrototypeOf(obj), {
toString: function() {
return "new object.toString";
}
});
check(obj);
check(obj2);
| hazzik/nashorn | test/script/basic/JDK-8023368_2.js | JavaScript | gpl-2.0 | 1,970 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _pure = require('recompose/pure');
var _pure2 = _interopRequireDefault(_pure);
var _SvgIcon = require('../../SvgIcon');
var _SvgIcon2 = _interopRequireDefault(_SvgIcon);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ImageFilterDrama = function ImageFilterDrama(props) {
return _react2.default.createElement(
_SvgIcon2.default,
props,
_react2.default.createElement('path', { d: 'M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.61 5.64 5.36 8.04 2.35 8.36 0 10.9 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM19 18H6c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4h2c0-2.76-1.86-5.08-4.4-5.78C8.61 6.88 10.2 6 12 6c3.03 0 5.5 2.47 5.5 5.5v.5H19c1.65 0 3 1.35 3 3s-1.35 3-3 3z' })
);
};
ImageFilterDrama = (0, _pure2.default)(ImageFilterDrama);
ImageFilterDrama.displayName = 'ImageFilterDrama';
ImageFilterDrama.muiName = 'SvgIcon';
exports.default = ImageFilterDrama; | Jorginho211/TFG | web/node_modules/material-ui/svg-icons/image/filter-drama.js | JavaScript | gpl-3.0 | 1,123 |
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*
* @category Shopware
* @package Article
* @subpackage Statistic
* @version $Id$
* @author shopware AG
*/
/**
* Shopware Controller - Article backend module
*/
//{namespace name=backend/article/view/main}
//{block name="backend/article/controller/statistic"}
Ext.define('Shopware.apps.Article.controller.Statistic', {
/**
* The parent class that this class extends.
* @string
*/
extend: 'Ext.app.Controller',
/**
* Set component references for easy access
* @array
*/
refs: [
{ ref: 'mainWindow', selector: 'article-detail-window' },
{ ref: 'statisticList', selector: 'article-detail-window article-statistics-list' },
{ ref: 'statisticChart', selector: 'article-detail-window article-statistics-chart' }
],
/**
* A template method that is called when your application boots.
* It is called before the Application's launch function is executed
* so gives a hook point to run any code before your Viewport is created.
*
* @params orderId - The main controller can handle a orderId parameter to open the order detail page directly
* @return void
*/
init: function () {
var me = this;
me.control({
'article-statistics-list': {
dateChange: me.onDateChange
},
'article-detail-window tabpanel[name=main-tab-panel]': {
beforetabchange: me.onMainTabChange
}
});
me.callParent(arguments);
},
/**
* Event listener function of the main tab panel in the detail window.
* Fired when the user changes the tab.
*/
onMainTabChange: function (panel, newTab, oldTab) {
if (newTab.name !== 'statistic-tab') {
return;
}
var me = this,
statisticListStore = me.getStatisticList().getStore(),
statisticChartStore = me.getStatisticChart().getStore();
if(!Ext.isEmpty(me.getMainWindow()) && !Ext.isEmpty(me.getMainWindow().article) && !Ext.isEmpty(me.getMainWindow().article.get('id'))) {
//set the new article id to the extra params
statisticListStore.getProxy().extraParams.articleId = me.getMainWindow().article.get('id');
statisticChartStore.getProxy().extraParams.articleId = me.getMainWindow().article.get('id');
statisticChartStore.getProxy().extraParams.chart = true;
}
//reload the list and the chart store
statisticListStore.load();
statisticChartStore.load();
},
onDateChange: function(fromDate, toDate) {
var me = this;
var store = me.getStatisticList().getStore();
store.load({
params: {
fromDate: fromDate,
toDate: toDate
}
});
}
});
//{/block}
| jenalgit/shopware | themes/Backend/ExtJs/backend/article/controller/statistic.js | JavaScript | agpl-3.0 | 3,795 |
/*
Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang("a11yhelp","es-mx",{title:"Instrucciones de accesibilidad",contents:"Contenidos de ayuda. Para cerrar este cuadro de diálogo presione ESC.",legend:[{name:"General",items:[{name:"Barra de herramientas del editor",legend:"Presione ${toolbarFocus} para navegar a la barra de herramientas. Desplácese al grupo de barras de herramientas siguiente y anterior con SHIFT + TAB. Desplácese al botón siguiente y anterior de la barra de herramientas con FLECHA DERECHA o FLECHA IZQUIERDA. Presione SPACE o ENTER para activar el botón de la barra de herramientas."},
{name:"Editor de diálogo",legend:"Dentro de un cuadro de diálogo, pulse TAB para desplazarse hasta el siguiente elemento de diálogo, pulse MAYÚS + TAB para desplazarse al elemento de diálogo anterior, pulse ENTER para enviar el diálogo, pulse ESC para cancelar el diálogo. Cuando un cuadro de diálogo tiene varias pestañas, se puede acceder a la lista de pestañas con ALT + F10 o con TAB como parte del orden de tabulación del diálogo. Con la lista de tabuladores enfocada, mueva a la pestaña siguiente y anterior con las flechas DERECHA y IZQUIERDA, respectivamente."},
{name:"Menú contextual del editor",legend:"Presione ${contextMenu} o CLAVE DE APLICACIÓN para abrir el menú contextual. A continuación, vaya a la siguiente opción del menú con TAB o DOWN ARROW. Desplácese a la opción anterior con SHIFT + TAB o FLECHA ARRIBA. Presione SPACE o ENTER para seleccionar la opción del menú. Abra el submenú de la opción actual con ESPACIO o ENTER o FLECHA DERECHA. Vuelva al elemento de menú principal con ESC o FLECHA IZQUIERDA. Cerrar el menú contextual con ESC."},{name:"Editor de cuadro de lista",
legend:"Dentro de un cuadro de lista, mueva al siguiente elemento de lista con TAB O FLECHA ABAJO. Mueva al elemento anterior de la lista con MAYÚS + TAB o FLECHA ARRIBA. Presione SPACE o ENTER para seleccionar la opción de lista. Presione ESC para cerrar el cuadro de lista."},{name:"Barra de ruta del elemento del editor",legend:"Presione ${elementsPathFocus} para navegar a la barra de ruta de elementos. Desplácese al siguiente botón de elemento con TAB o FLECHA DERECHA. Desplácese al botón anterior con SHIFT + TAB o FLECHA IZQUIERDA. Presione SPACE o ENTER para seleccionar el elemento en el editor."}]},
{name:"Comandos",items:[{name:"Comando deshacer",legend:"Presiona ${undo}"},{name:"Comando rehacer",legend:"Presiona ${redo}"},{name:"Comando negrita",legend:"Presiona ${bold}"},{name:"Comando cursiva",legend:"Presiona {italic}"},{name:"Comando subrayado",legend:"Presiona ${underline}"},{name:"Comando enlace",legend:"Presiona ${link}"},{name:"Comando colapsar barra de herramientas",legend:"Presiona ${toolbarCollapse}"},{name:"Acceda al comando de espacio de enfoque anterior",legend:"Presione ${accessPreviousSpace} para acceder al espacio de enfoque inaccesible más cercano antes del cursor, por ejemplo: dos elementos HR adyacentes. Repita la combinación de teclas para alcanzar los espacios de enfoque distantes."},
{name:"Acceder al siguiente comando de espacio de enfoque",legend:"Pulse ${accessNextSpace} para acceder al espacio de enfoque más cercano inaccesible después del cursor, por ejemplo: dos elementos HR adyacentes. Repita la combinación de teclas para alcanzar los espacios de enfoque distantes."},{name:"Ayuda de accesibilidad",legend:"Presiona ${a11yHelp}"},{name:" Paste as plain text",legend:"Press ${pastetext}",legendEdge:"Press ${pastetext}, followed by ${paste}"}]}],tab:"Tabulador",pause:"Pausa",
capslock:"Mayúsculas",escape:"Escape",pageUp:"Página arriba",pageDown:"Página abajo",leftArrow:"Flecha izquierda",upArrow:"Flecha arriba",rightArrow:"Flecha derecha",downArrow:"Flecha abajo",insert:"Insertar",leftWindowKey:"Tecla izquierda de Windows",rightWindowKey:"Tecla derecha de Windows",selectKey:"Tecla de selección",numpad0:"Teclado numérico 0",numpad1:"Teclado numérico 1",numpad2:"Teclado numérico 2",numpad3:"Teclado numérico 3",numpad4:"Teclado numérico 4",numpad5:"Teclado numérico 5",numpad6:"Teclado numérico 6",
numpad7:"Teclado numérico 7",numpad8:"Teclado numérico 8",numpad9:"Teclado numérico 9",multiply:"Multiplicar",add:"Sumar",subtract:"Restar",decimalPoint:"Punto decimal",divide:"Dividir",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:"Números",scrollLock:"Bloqueo de desplazamiento",semiColon:"punto y coma",equalSign:"Signo igual",comma:"Coma",dash:"Guión",period:"Espacio",forwardSlash:"Diagonal",graveAccent:"Acento grave",openBracket:"Abrir paréntesis",
backSlash:"Diagonal invertida",closeBracket:"Cerrar paréntesis",singleQuote:"Comillas simple"}); | YAFNET/YAFNET | yafsrc/YetAnotherForum.NET/Scripts/ckeditor/plugins/plugins/a11yhelp/dialogs/lang/es-mx.js | JavaScript | apache-2.0 | 4,895 |
!function(global, $) {
'use strict';
var i18n = ccmi18n_helpGuides['dashboard'];
var steps = [{
content: '<p><span class="h5">' + i18n[0].title + '</span><br/>' + i18n[0].text + '</p>',
highlightTarget: true,
nextButton: false,
closeButton: true,
target: $('[data-guide-toolbar-action=dashboard]'),
my: 'top right',
at: 'bottom center',
setup: function(tour, options) {
$('a[data-launch-panel=dashboard]').on('click', function() {
tour.view.tip.hide();
ConcreteHelpGuideManager.hideOverlay();
});
ConcreteEvent.subscribe('PanelOpen.concreteDashboardTour', function(e, data) {
setTimeout(function() {
var panel = data.panel.getIdentifier();
if (panel == 'dashboard') {
tour.next();
}
}, 500);
});
}
},{
content: '<p><span class="h5">' + i18n[1].title + '</span><br/>' + i18n[1].text + '</p>',
highlightTarget: false,
nextButton: true,
closeButton: true,
my: 'right center',
at: 'left center',
setup: function(tour, options) {
return {target: $('div#ccm-panel-dashboard ul.nav a[href$=sitemap]').eq(0)}
}
}];
var tour = new Tourist.Tour({
steps: steps,
tipClass: 'Bootstrap',
tipOptions:{
showEffect: 'slidein'
}
});
tour.on('start', function() {
ConcreteHelpGuideManager.enterToolbarGuideMode();
});
tour.on('stop', function() {
ConcreteHelpGuideManager.exitToolbarGuideMode();
ConcreteEvent.unsubscribe('PanelOpen.concreteDashboardTour');
});
ConcreteHelpGuideManager.register('dashboard', tour);
}(window, jQuery); | lifejuggler/audrey_site | updates/concrete5.7.5.6/concrete/js/build/core/app/help/guides/dashboard.js | JavaScript | mit | 1,533 |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v8.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var columnController_1 = require("../columnController/columnController");
var gridPanel_1 = require("../gridPanel/gridPanel");
var column_1 = require("../entities/column");
var context_1 = require("../context/context");
var headerContainer_1 = require("./headerContainer");
var eventService_1 = require("../eventService");
var events_1 = require("../events");
var scrollVisibleService_1 = require("../gridPanel/scrollVisibleService");
var HeaderRenderer = (function () {
function HeaderRenderer() {
}
HeaderRenderer.prototype.init = function () {
var _this = this;
this.eHeaderViewport = this.gridPanel.getHeaderViewport();
this.eRoot = this.gridPanel.getRoot();
this.eHeaderOverlay = this.gridPanel.getHeaderOverlay();
this.centerContainer = new headerContainer_1.HeaderContainer(this.gridPanel.getHeaderContainer(), this.gridPanel.getHeaderViewport(), this.eRoot, null);
this.childContainers = [this.centerContainer];
if (!this.gridOptionsWrapper.isForPrint()) {
this.pinnedLeftContainer = new headerContainer_1.HeaderContainer(this.gridPanel.getPinnedLeftHeader(), null, this.eRoot, column_1.Column.PINNED_LEFT);
this.pinnedRightContainer = new headerContainer_1.HeaderContainer(this.gridPanel.getPinnedRightHeader(), null, this.eRoot, column_1.Column.PINNED_RIGHT);
this.childContainers.push(this.pinnedLeftContainer);
this.childContainers.push(this.pinnedRightContainer);
}
this.childContainers.forEach(function (container) { return _this.context.wireBean(container); });
// when grid columns change, it means the number of rows in the header has changed and it's all new columns
this.eventService.addEventListener(events_1.Events.EVENT_GRID_COLUMNS_CHANGED, this.onGridColumnsChanged.bind(this));
// shotgun way to get labels to change, eg from sum(amount) to avg(amount)
this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_VALUE_CHANGED, this.refreshHeader.bind(this));
// for resized, the individual cells take care of this, so don't need to refresh everything
this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_RESIZED, this.setPinnedColContainerWidth.bind(this));
this.eventService.addEventListener(events_1.Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.setPinnedColContainerWidth.bind(this));
this.eventService.addEventListener(events_1.Events.EVENT_SCROLL_VISIBILITY_CHANGED, this.onScrollVisibilityChanged.bind(this));
if (this.columnController.isReady()) {
this.refreshHeader();
}
};
HeaderRenderer.prototype.onScrollVisibilityChanged = function () {
this.setPinnedColContainerWidth();
};
HeaderRenderer.prototype.forEachHeaderElement = function (callback) {
this.childContainers.forEach(function (childContainer) { return childContainer.forEachHeaderElement(callback); });
};
HeaderRenderer.prototype.destroy = function () {
this.childContainers.forEach(function (container) { return container.destroy(); });
};
HeaderRenderer.prototype.onGridColumnsChanged = function () {
this.setHeight();
};
// this is called from the API and refreshes everything, should be broken out
// into refresh everything vs just something changed
HeaderRenderer.prototype.refreshHeader = function () {
this.setHeight();
this.childContainers.forEach(function (container) { return container.refresh(); });
this.setPinnedColContainerWidth();
};
HeaderRenderer.prototype.setHeight = function () {
// if forPrint, overlay is missing
if (this.eHeaderOverlay) {
var rowHeight = this.gridOptionsWrapper.getHeaderHeight();
// we can probably get rid of this when we no longer need the overlay
var dept = this.columnController.getHeaderRowCount();
this.eHeaderOverlay.style.height = rowHeight + 'px';
this.eHeaderOverlay.style.top = ((dept - 1) * rowHeight) + 'px';
}
};
HeaderRenderer.prototype.setPinnedColContainerWidth = function () {
// pinned col doesn't exist when doing forPrint
if (this.gridOptionsWrapper.isForPrint()) {
return;
}
var pinnedLeftWidthWithScroll = this.scrollVisibleService.getPinnedLeftWithScrollWidth();
var pinnedRightWidthWithScroll = this.scrollVisibleService.getPinnedRightWithScrollWidth();
this.eHeaderViewport.style.marginLeft = pinnedLeftWidthWithScroll + 'px';
this.eHeaderViewport.style.marginRight = pinnedRightWidthWithScroll + 'px';
};
return HeaderRenderer;
}());
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
], HeaderRenderer.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_1.Autowired('columnController'),
__metadata("design:type", columnController_1.ColumnController)
], HeaderRenderer.prototype, "columnController", void 0);
__decorate([
context_1.Autowired('gridPanel'),
__metadata("design:type", gridPanel_1.GridPanel)
], HeaderRenderer.prototype, "gridPanel", void 0);
__decorate([
context_1.Autowired('context'),
__metadata("design:type", context_1.Context)
], HeaderRenderer.prototype, "context", void 0);
__decorate([
context_1.Autowired('eventService'),
__metadata("design:type", eventService_1.EventService)
], HeaderRenderer.prototype, "eventService", void 0);
__decorate([
context_1.Autowired('scrollVisibleService'),
__metadata("design:type", scrollVisibleService_1.ScrollVisibleService)
], HeaderRenderer.prototype, "scrollVisibleService", void 0);
__decorate([
context_1.PostConstruct,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], HeaderRenderer.prototype, "init", null);
__decorate([
context_1.PreDestroy,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], HeaderRenderer.prototype, "destroy", null);
HeaderRenderer = __decorate([
context_1.Bean('headerRenderer')
], HeaderRenderer);
exports.HeaderRenderer = HeaderRenderer;
| tholu/cdnjs | ajax/libs/ag-grid/8.1.1/lib/headerRendering/headerRenderer.js | JavaScript | mit | 7,315 |
define("ace/mode/hjson_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var HjsonHighlightRules = function() {
this.$rules = {
start: [{
include: "#comments"
}, {
include: "#rootObject"
}, {
include: "#value"
}],
"#array": [{
token: "paren.lparen",
regex: /\[/,
push: [{
token: "paren.rparen",
regex: /\]/,
next: "pop"
}, {
include: "#value"
}, {
include: "#comments"
}, {
token: "text",
regex: /,|$/
}, {
token: "invalid.illegal",
regex: /[^\s\]]/
}, {
defaultToken: "array"
}]
}],
"#comments": [{
token: [
"comment.punctuation",
"comment.line"
],
regex: /(#)(.*$)/
}, {
token: "comment.punctuation",
regex: /\/\*/,
push: [{
token: "comment.punctuation",
regex: /\*\//,
next: "pop"
}, {
defaultToken: "comment.block"
}]
}, {
token: [
"comment.punctuation",
"comment.line"
],
regex: /(\/\/)(.*$)/
}],
"#constant": [{
token: "constant",
regex: /\b(?:true|false|null)\b/
}],
"#keyname": [{
token: "keyword",
regex: /(?:[^,\{\[\}\]\s]+|"(?:[^"\\]|\\.)*")\s*(?=:)/
}],
"#mstring": [{
token: "string",
regex: /'''/,
push: [{
token: "string",
regex: /'''/,
next: "pop"
}, {
defaultToken: "string"
}]
}],
"#number": [{
token: "constant.numeric",
regex: /-?(?:0|[1-9]\d*)(?:(?:\.\d+)?(?:[eE][+-]?\d+)?)?/,
comment: "handles integer and decimal numbers"
}],
"#object": [{
token: "paren.lparen",
regex: /\{/,
push: [{
token: "paren.rparen",
regex: /\}/,
next: "pop"
}, {
include: "#keyname"
}, {
include: "#value"
}, {
token: "text",
regex: /:/
}, {
token: "text",
regex: /,/
}, {
defaultToken: "paren"
}]
}],
"#rootObject": [{
token: "paren",
regex: /(?=\s*(?:[^,\{\[\}\]\s]+|"(?:[^"\\]|\\.)*")\s*:)/,
push: [{
token: "paren.rparen",
regex: /---none---/,
next: "pop"
}, {
include: "#keyname"
}, {
include: "#value"
}, {
token: "text",
regex: /:/
}, {
token: "text",
regex: /,/
}, {
defaultToken: "paren"
}]
}],
"#string": [{
token: "string",
regex: /"/,
push: [{
token: "string",
regex: /"/,
next: "pop"
}, {
token: "constant.language.escape",
regex: /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/
}, {
token: "invalid.illegal",
regex: /\\./
}, {
defaultToken: "string"
}]
}],
"#ustring": [{
token: "string",
regex: /\b[^:,0-9\-\{\[\}\]\s].*$/
}],
"#value": [{
include: "#constant"
}, {
include: "#number"
}, {
include: "#string"
}, {
include: "#array"
}, {
include: "#object"
}, {
include: "#comments"
}, {
include: "#mstring"
}, {
include: "#ustring"
}]
}
this.normalizeRules();
};
HjsonHighlightRules.metaData = {
fileTypes: ["hjson"],
foldingStartMarker: "(?x: # turn on extended mode\n ^ # a line beginning with\n \\s* # some optional space\n [{\\[] # the start of an object or array\n (?! # but not followed by\n .* # whatever\n [}\\]] # and the close of an object or array\n ,? # an optional comma\n \\s* # some optional space\n $ # at the end of the line\n )\n | # ...or...\n [{\\[] # the start of an object or array\n \\s* # some optional space\n $ # at the end of the line\n )",
foldingStopMarker: "(?x: # turn on extended mode\n ^ # a line beginning with\n \\s* # some optional space\n [}\\]] # and the close of an object or array\n )",
keyEquivalent: "^~J",
name: "Hjson",
scopeName: "source.hjson"
}
oop.inherits(HjsonHighlightRules, TextHighlightRules);
exports.HjsonHighlightRules = HjsonHighlightRules;
});
define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) {
"use strict";
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function(commentRegex) {
if (commentRegex) {
this.foldingStartMarker = new RegExp(
this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
);
this.foldingStopMarker = new RegExp(
this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
);
}
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/;
this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/;
this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/;
this._getFoldWidgetBase = this.getFoldWidget;
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.singleLineBlockCommentRe.test(line)) {
if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line))
return "";
}
var fw = this._getFoldWidgetBase(session, foldStyle, row);
if (!fw && this.startRegionRe.test(line))
return "start"; // lineCommentRegionStart
return fw;
};
this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) {
var line = session.getLine(row);
if (this.startRegionRe.test(line))
return this.getCommentRegionBlock(session, line, row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length, 1);
if (range && !range.isMultiLine()) {
if (forceMultiline) {
range = this.getSectionRange(session, row);
} else if (foldStyle != "all")
range = null;
}
return range;
}
if (foldStyle === "markbegin")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[1])
return this.closingBracketBlock(session, match[1], row, i);
return session.getCommentFoldRange(row, i, -1);
}
};
this.getSectionRange = function(session, row) {
var line = session.getLine(row);
var startIndent = line.search(/\S/);
var startRow = row;
var startColumn = line.length;
row = row + 1;
var endRow = row;
var maxRow = session.getLength();
while (++row < maxRow) {
line = session.getLine(row);
var indent = line.search(/\S/);
if (indent === -1)
continue;
if (startIndent > indent)
break;
var subRange = this.getFoldWidgetRange(session, "all", row);
if (subRange) {
if (subRange.start.row <= startRow) {
break;
} else if (subRange.isMultiLine()) {
row = subRange.end.row;
} else if (startIndent == indent) {
break;
}
}
endRow = row;
}
return new Range(startRow, startColumn, endRow, session.getLine(endRow).length);
};
this.getCommentRegionBlock = function(session, line, row) {
var startColumn = line.search(/\s*$/);
var maxRow = session.getLength();
var startRow = row;
var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/;
var depth = 1;
while (++row < maxRow) {
line = session.getLine(row);
var m = re.exec(line);
if (!m) continue;
if (m[1]) depth--;
else depth++;
if (!depth) break;
}
var endRow = row;
if (endRow > startRow) {
return new Range(startRow, startColumn, endRow, line.length);
}
};
}).call(FoldMode.prototype);
});
define("ace/mode/hjson",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/hjson_highlight_rules","ace/mode/folding/cstyle"], function(require, exports, module) {
"use strict";
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var HjsonHighlightRules = require("./hjson_highlight_rules").HjsonHighlightRules;
var FoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.HighlightRules = HjsonHighlightRules;
this.foldingRules = new FoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.lineCommentStart = "//";
this.blockComment = { start: "/*", end: "*/" };
this.$id = "ace/mode/hjson"
}).call(Mode.prototype);
exports.Mode = Mode;
});
| chickencoder/chickencoder.github.io | yodacode/vendor/ace/mode-hjson.js | JavaScript | mit | 11,012 |
//// [thisInSuperCall3.ts]
class Base {
constructor(a: any) {}
}
class Foo extends Base {
public x: number = 0;
constructor() {
super(this);
}
}
//// [thisInSuperCall3.js]
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 __());
};
var Base = (function () {
function Base(a) {
}
return Base;
})();
var Foo = (function (_super) {
__extends(Foo, _super);
function Foo() {
_super.call(this, this);
this.x = 0;
}
return Foo;
})(Base);
| shanexu/TypeScript | tests/baselines/reference/thisInSuperCall3.js | JavaScript | apache-2.0 | 724 |
/*! rangeslider.js - v2.3.0 | (c) 2016 @andreruffert | MIT license | https://github.com/andreruffert/rangeslider.js */
(function(factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function($) {
'use strict';
// Polyfill Number.isNaN(value)
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
Number.isNaN = Number.isNaN || function(value) {
return typeof value === 'number' && value !== value;
};
/**
* Range feature detection
* @return {Boolean}
*/
function supportsRange() {
var input = document.createElement('input');
input.setAttribute('type', 'range');
return input.type !== 'text';
}
var pluginName = 'rangeslider',
pluginIdentifier = 0,
hasInputRangeSupport = supportsRange(),
defaults = {
polyfill: true,
orientation: 'horizontal',
rangeClass: 'rangeslider',
disabledClass: 'rangeslider--disabled',
activeClass: 'rangeslider--active',
horizontalClass: 'rangeslider--horizontal',
verticalClass: 'rangeslider--vertical',
fillClass: 'rangeslider__fill',
handleClass: 'rangeslider__handle',
startEvent: ['mousedown', 'touchstart', 'pointerdown'],
moveEvent: ['mousemove', 'touchmove', 'pointermove'],
endEvent: ['mouseup', 'touchend', 'pointerup']
},
constants = {
orientation: {
horizontal: {
dimension: 'width',
direction: 'left',
directionStyle: 'left',
coordinate: 'x'
},
vertical: {
dimension: 'height',
direction: 'top',
directionStyle: 'bottom',
coordinate: 'y'
}
}
};
/**
* Delays a function for the given number of milliseconds, and then calls
* it with the arguments supplied.
*
* @param {Function} fn [description]
* @param {Number} wait [description]
* @return {Function}
*/
function delay(fn, wait) {
var args = Array.prototype.slice.call(arguments, 2);
return setTimeout(function(){ return fn.apply(null, args); }, wait);
}
/**
* Returns a debounced function that will make sure the given
* function is not triggered too much.
*
* @param {Function} fn Function to debounce.
* @param {Number} debounceDuration OPTIONAL. The amount of time in milliseconds for which we will debounce the function. (defaults to 100ms)
* @return {Function}
*/
function debounce(fn, debounceDuration) {
debounceDuration = debounceDuration || 100;
return function() {
if (!fn.debouncing) {
var args = Array.prototype.slice.apply(arguments);
fn.lastReturnVal = fn.apply(window, args);
fn.debouncing = true;
}
clearTimeout(fn.debounceTimeout);
fn.debounceTimeout = setTimeout(function(){
fn.debouncing = false;
}, debounceDuration);
return fn.lastReturnVal;
};
}
/**
* Check if a `element` is visible in the DOM
*
* @param {Element} element
* @return {Boolean}
*/
function isHidden(element) {
return (
element && (
element.offsetWidth === 0 ||
element.offsetHeight === 0 ||
// Also Consider native `<details>` elements.
element.open === false
)
);
}
/**
* Get hidden parentNodes of an `element`
*
* @param {Element} element
* @return {[type]}
*/
function getHiddenParentNodes(element) {
var parents = [],
node = element.parentNode;
while (isHidden(node)) {
parents.push(node);
node = node.parentNode;
}
return parents;
}
/**
* Returns dimensions for an element even if it is not visible in the DOM.
*
* @param {Element} element
* @param {String} key (e.g. offsetWidth …)
* @return {Number}
*/
function getDimension(element, key) {
var hiddenParentNodes = getHiddenParentNodes(element),
hiddenParentNodesLength = hiddenParentNodes.length,
inlineStyle = [],
dimension = element[key];
// Used for native `<details>` elements
function toggleOpenProperty(element) {
if (typeof element.open !== 'undefined') {
element.open = (element.open) ? false : true;
}
}
if (hiddenParentNodesLength) {
for (var i = 0; i < hiddenParentNodesLength; i++) {
// Cache style attribute to restore it later.
inlineStyle[i] = hiddenParentNodes[i].style.cssText;
// visually hide
if (hiddenParentNodes[i].style.setProperty) {
hiddenParentNodes[i].style.setProperty('display', 'block', 'important');
} else {
hiddenParentNodes[i].style.cssText += ';display: block !important';
}
hiddenParentNodes[i].style.height = '0';
hiddenParentNodes[i].style.overflow = 'hidden';
hiddenParentNodes[i].style.visibility = 'hidden';
toggleOpenProperty(hiddenParentNodes[i]);
}
// Update dimension
dimension = element[key];
for (var j = 0; j < hiddenParentNodesLength; j++) {
// Restore the style attribute
hiddenParentNodes[j].style.cssText = inlineStyle[j];
toggleOpenProperty(hiddenParentNodes[j]);
}
}
return dimension;
}
/**
* Returns the parsed float or the default if it failed.
*
* @param {String} str
* @param {Number} defaultValue
* @return {Number}
*/
function tryParseFloat(str, defaultValue) {
var value = parseFloat(str);
return Number.isNaN(value) ? defaultValue : value;
}
/**
* Capitalize the first letter of string
*
* @param {String} str
* @return {String}
*/
function ucfirst(str) {
return str.charAt(0).toUpperCase() + str.substr(1);
}
/**
* Plugin
* @param {String} element
* @param {Object} options
*/
function Plugin(element, options) {
this.$window = $(window);
this.$document = $(document);
this.$element = $(element);
this.options = $.extend( {}, defaults, options );
this.polyfill = this.options.polyfill;
this.orientation = this.$element[0].getAttribute('data-orientation') || this.options.orientation;
this.onInit = this.options.onInit;
this.onSlide = this.options.onSlide;
this.onSlideEnd = this.options.onSlideEnd;
this.DIMENSION = constants.orientation[this.orientation].dimension;
this.DIRECTION = constants.orientation[this.orientation].direction;
this.DIRECTION_STYLE = constants.orientation[this.orientation].directionStyle;
this.COORDINATE = constants.orientation[this.orientation].coordinate;
// Plugin should only be used as a polyfill
if (this.polyfill) {
// Input range support?
if (hasInputRangeSupport) { return false; }
}
this.identifier = 'js-' + pluginName + '-' +(pluginIdentifier++);
this.startEvent = this.options.startEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
this.moveEvent = this.options.moveEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
this.endEvent = this.options.endEvent.join('.' + this.identifier + ' ') + '.' + this.identifier;
this.toFixed = (this.step + '').replace('.', '').length - 1;
this.$fill = $('<div class="' + this.options.fillClass + '" />');
this.$handle = $('<div class="' + this.options.handleClass + '" />');
this.$range = $('<div class="' + this.options.rangeClass + ' ' + this.options[this.orientation + 'Class'] + '" id="' + this.identifier + '" />').insertAfter(this.$element).prepend(this.$fill, this.$handle);
// visually hide the input
this.$element.css({
'position': 'absolute',
'width': '1px',
'height': '1px',
'overflow': 'hidden',
'opacity': '0'
});
// Store context
this.handleDown = $.proxy(this.handleDown, this);
this.handleMove = $.proxy(this.handleMove, this);
this.handleEnd = $.proxy(this.handleEnd, this);
this.init();
// Attach Events
var _this = this;
this.$window.on('resize.' + this.identifier, debounce(function() {
// Simulate resizeEnd event.
delay(function() { _this.update(false, false); }, 300);
}, 20));
this.$document.on(this.startEvent, '#' + this.identifier + ':not(.' + this.options.disabledClass + ')', this.handleDown);
// Listen to programmatic value changes
this.$element.on('change.' + this.identifier, function(e, data) {
if (data && data.origin === _this.identifier) {
return;
}
var value = e.target.value,
pos = _this.getPositionFromValue(value);
_this.setPosition(pos);
});
}
Plugin.prototype.init = function() {
this.update(true, false);
if (this.onInit && typeof this.onInit === 'function') {
this.onInit();
}
};
Plugin.prototype.update = function(updateAttributes, triggerSlide) {
updateAttributes = updateAttributes || false;
if (updateAttributes) {
this.min = tryParseFloat(this.$element[0].getAttribute('min'), 0);
this.max = tryParseFloat(this.$element[0].getAttribute('max'), 100);
this.value = tryParseFloat(this.$element[0].value, Math.round(this.min + (this.max-this.min)/2));
this.step = tryParseFloat(this.$element[0].getAttribute('step'), 1);
}
this.handleDimension = getDimension(this.$handle[0], 'offset' + ucfirst(this.DIMENSION));
this.rangeDimension = getDimension(this.$range[0], 'offset' + ucfirst(this.DIMENSION));
this.maxHandlePos = this.rangeDimension - this.handleDimension;
this.grabPos = this.handleDimension / 2;
this.position = this.getPositionFromValue(this.value);
// Consider disabled state
if (this.$element[0].disabled) {
this.$range.addClass(this.options.disabledClass);
} else {
this.$range.removeClass(this.options.disabledClass);
}
this.setPosition(this.position, triggerSlide);
};
Plugin.prototype.handleDown = function(e) {
e.preventDefault();
this.$document.on(this.moveEvent, this.handleMove);
this.$document.on(this.endEvent, this.handleEnd);
// add active class because Firefox is ignoring
// the handle:active pseudo selector because of `e.preventDefault();`
this.$range.addClass(this.options.activeClass);
// If we click on the handle don't set the new position
if ((' ' + e.target.className + ' ').replace(/[\n\t]/g, ' ').indexOf(this.options.handleClass) > -1) {
return;
}
var pos = this.getRelativePosition(e),
rangePos = this.$range[0].getBoundingClientRect()[this.DIRECTION],
handlePos = this.getPositionFromNode(this.$handle[0]) - rangePos,
setPos = (this.orientation === 'vertical') ? (this.maxHandlePos - (pos - this.grabPos)) : (pos - this.grabPos);
this.setPosition(setPos);
if (pos >= handlePos && pos < handlePos + this.handleDimension) {
this.grabPos = pos - handlePos;
}
};
Plugin.prototype.handleMove = function(e) {
e.preventDefault();
var pos = this.getRelativePosition(e);
var setPos = (this.orientation === 'vertical') ? (this.maxHandlePos - (pos - this.grabPos)) : (pos - this.grabPos);
this.setPosition(setPos);
};
Plugin.prototype.handleEnd = function(e) {
e.preventDefault();
this.$document.off(this.moveEvent, this.handleMove);
this.$document.off(this.endEvent, this.handleEnd);
this.$range.removeClass(this.options.activeClass);
// Ok we're done fire the change event
this.$element.trigger('change', { origin: this.identifier });
if (this.onSlideEnd && typeof this.onSlideEnd === 'function') {
this.onSlideEnd(this.position, this.value);
}
};
Plugin.prototype.cap = function(pos, min, max) {
if (pos < min) { return min; }
if (pos > max) { return max; }
return pos;
};
Plugin.prototype.setPosition = function(pos, triggerSlide) {
var value, newPos;
if (triggerSlide === undefined) {
triggerSlide = true;
}
// Snapping steps
value = this.getValueFromPosition(this.cap(pos, 0, this.maxHandlePos));
newPos = this.getPositionFromValue(value);
// Update ui
this.$fill[0].style[this.DIMENSION] = (newPos + this.grabPos) + 'px';
this.$handle[0].style[this.DIRECTION_STYLE] = newPos + 'px';
this.setValue(value);
// Update globals
this.position = newPos;
this.value = value;
if (triggerSlide && this.onSlide && typeof this.onSlide === 'function') {
this.onSlide(newPos, value);
}
};
// Returns element position relative to the parent
Plugin.prototype.getPositionFromNode = function(node) {
var i = 0;
while (node !== null) {
i += node.offsetLeft;
node = node.offsetParent;
}
return i;
};
Plugin.prototype.getRelativePosition = function(e) {
// Get the offset DIRECTION relative to the viewport
var ucCoordinate = ucfirst(this.COORDINATE),
rangePos = this.$range[0].getBoundingClientRect()[this.DIRECTION],
pageCoordinate = 0;
if (typeof e.originalEvent['client' + ucCoordinate] !== 'undefined') {
pageCoordinate = e.originalEvent['client' + ucCoordinate];
}
else if (
e.originalEvent.touches &&
e.originalEvent.touches[0] &&
typeof e.originalEvent.touches[0]['client' + ucCoordinate] !== 'undefined'
) {
pageCoordinate = e.originalEvent.touches[0]['client' + ucCoordinate];
}
else if(e.currentPoint && typeof e.currentPoint[this.COORDINATE] !== 'undefined') {
pageCoordinate = e.currentPoint[this.COORDINATE];
}
return pageCoordinate - rangePos;
};
Plugin.prototype.getPositionFromValue = function(value) {
var percentage, pos;
percentage = (value - this.min)/(this.max - this.min);
pos = (!Number.isNaN(percentage)) ? percentage * this.maxHandlePos : 0;
return pos;
};
Plugin.prototype.getValueFromPosition = function(pos) {
var percentage, value;
percentage = ((pos) / (this.maxHandlePos || 1));
value = this.step * Math.round(percentage * (this.max - this.min) / this.step) + this.min;
return Number((value).toFixed(this.toFixed));
};
Plugin.prototype.setValue = function(value) {
if (value === this.value && this.$element[0].value !== '') {
return;
}
// Set the new value and fire the `input` event
this.$element
.val(value)
.trigger('input', { origin: this.identifier });
};
Plugin.prototype.destroy = function() {
this.$document.off('.' + this.identifier);
this.$window.off('.' + this.identifier);
this.$element
.off('.' + this.identifier)
.removeAttr('style')
.removeData('plugin_' + pluginName);
// Remove the generated markup
if (this.$range && this.$range.length) {
this.$range[0].parentNode.removeChild(this.$range[0]);
}
};
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[pluginName] = function(options) {
var args = Array.prototype.slice.call(arguments, 1);
return this.each(function() {
var $this = $(this),
data = $this.data('plugin_' + pluginName);
// Create a new instance.
if (!data) {
$this.data('plugin_' + pluginName, (data = new Plugin(this, options)));
}
// Make it possible to access methods from public.
// e.g `$element.rangeslider('method');`
if (typeof options === 'string') {
data[options].apply(data, args);
}
});
};
return 'rangeslider.js is available in jQuery context e.g $(selector).rangeslider(options);';
}));
| guillecro/utn-abierta | web/js/rangeslider.js | JavaScript | mit | 17,853 |
/**
* Localization file for Chinese - China (zh-CN)
*/
(function(factory) {
// Module systems magic dance.
/*global require,ko.validation,define*/
if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
// CommonJS or Node: hard-coded dependency on 'knockout-validation'
factory(require('knockout.validation'));
} else if (typeof define === "function" && define['amd']) {
// AMD anonymous module with hard-coded dependency on 'knockout-validation'
define(['knockout.validation'], factory);
} else {
// <script> tag: use the global `ko.validation` object
factory(ko.validation);
}
}(function(kv) {
if (!kv || typeof kv.defineLocale !== 'function') {
throw new Error('Knockout-Validation is required, please ensure it is loaded before this localization file');
}
return kv.defineLocale('zh-CN', {
required: '必填字段',
min: '输入值必须大于等于 {0}',
max: '输入值必须小于等于 {0}',
minLength: '至少输入 {0} 个字符',
maxLength: '输入的字符数不能超过 {0} 个',
pattern: '请检查此值',
step: '每次步进值是 {0}',
email: 'email地址格式不正确',
date: '日期格式不正确',
dateISO: '日期格式不正确',
number: '请输入一个数字',
digit: '请输入一个数字',
phoneUS: '请输入一个合法的手机号(US)',
equal: '输入值不一样',
notEqual: '请选择另一个值',
unique: '此值应该是唯一的'
});
}));
| Dervisevic/cdnjs | ajax/libs/knockout-validation/2.0.1/localization/zh-CN.js | JavaScript | mit | 1,480 |
'use strict';var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);var _createClass2 = require('babel-runtime/helpers/createClass');var _createClass3 = _interopRequireDefault(_createClass2);var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);var _inherits2 = require('babel-runtime/helpers/inherits');var _inherits3 = _interopRequireDefault(_inherits2);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };} /**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
var Console = require('./Console');var
NullConsole = function (_Console) {(0, _inherits3.default)(NullConsole, _Console);function NullConsole() {(0, _classCallCheck3.default)(this, NullConsole);return (0, _possibleConstructorReturn3.default)(this, (NullConsole.__proto__ || (0, _getPrototypeOf2.default)(NullConsole)).apply(this, arguments));}(0, _createClass3.default)(NullConsole, [{ key: 'assert', value: function assert()
{} }, { key: 'dir', value: function dir()
{} }, { key: 'error', value: function error()
{} }, { key: 'info', value: function info()
{} }, { key: 'log', value: function log()
{} }, { key: 'time', value: function time()
{} }, { key: 'timeEnd', value: function timeEnd()
{} }, { key: 'trace', value: function trace()
{} }, { key: 'warn', value: function warn()
{} }]);return NullConsole;}(Console);
module.exports = NullConsole; | rootulp/exercism | typescript/space-age/node_modules/jest-util/build-es5/NullConsole.js | JavaScript | mit | 8,377 |
//
/*
// The module of the SocialCalc package for the optional popup menus in socialcalcspreadsheetcontrol.js
//
// (c) Copyright 2009 Socialtext, Inc.
// All Rights Reserved.
//
// The contents of this file are subject to the Artistic License 2.0; you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at http://socialcalc.org/licenses/al-20/.
//
// Some of the other files in the SocialCalc package are licensed under
// different licenses. Please note the licenses of the modules you use.
//
// Code History:
//
// Initially coded by Dan Bricklin of Software Garden, Inc., for Socialtext, Inc.
//
*/
var SocialCalc; // All values are stored in the master SocialCalc object
if (!SocialCalc) {
SocialCalc = {};
}
// The main Popup data -- there is only one set
SocialCalc.Popup = {};
// Routines and values for each type of control, indexed by type name
// The value for each is an object constructed as follows:
//
// Create = function(type, id, attribs)
// Initialize = function(type, id, data)
// SetValue = function(type, id, value)
// GetValue = function(type, id) returns value
// SetDisabled = function(type, id, t/f)
// Show = function(type, id)
// Hide = function(type, id)
// Cancel = function(type, id)
// Reset = function(type)
//
// data = object to hold type-specific data
//
SocialCalc.Popup.Types = {};
// Definitions for each individual control, indexed by id
// The value for each is an object constructed as follows:
//
// type: type name of the control
// value: current value of the control (usually a string, but can depend on type)
// data: object with type-specific items
//
SocialCalc.Popup.Controls = {};
// System-wide values of currently active control
//
// id: id of current control or null
//
SocialCalc.Popup.Current = {};
// Override this for localization
SocialCalc.Popup.LocalizeString = function(str) {return str;};
// * * * * * * * * * * * * * * * *
//
// GENERAL ROUTINES
//
// * * * * * * * * * * * * * * * *
//
// SocialCalc.Popup.Create(type, id, attribs)
//
// Creates a control of type "type" as the children of document element "id" using "attribs"
//
SocialCalc.Popup.Create = function(type, id, attribs) {
var pt = SocialCalc.Popup.Types[type];
if (pt && pt.Create) {
pt.Create(type, id, attribs);
}
SocialCalc.Popup.imagePrefix = SocialCalc.Constants.defaultImagePrefix; // image prefix
}
//
// SocialCalc.Popup.SetValue(id, value)
//
// Sets the value of control.
//
SocialCalc.Popup.SetValue = function(id, value) {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
if (!spc[id]) {alert("Unknown control "+id);return;}
var type = spc[id].type;
var pt = spt[type];
var spcdata = spc[id].data;
if (pt && pt.Create) {
pt.SetValue(type, id, value);
if (spcdata.attribs && spcdata.attribs.changedcallback) {
spcdata.attribs.changedcallback(spcdata.attribs, id, value);
}
}
}
//
// SocialCalc.Popup.SetDisabled(id, disabled)
//
// Sets whether the control is disabled (true) or not (false).
//
SocialCalc.Popup.SetDisabled = function(id, disabled) {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
if (!spc[id]) {alert("Unknown control "+id);return;}
var type = spc[id].type;
var pt = spt[type];
if (pt && pt.Create) {
if (sp.Current.id && id == sp.Current.id) {
pt.Hide(type, sp.Current.id);
sp.Current.id = null;
}
pt.SetDisabled(type, id, disabled);
}
}
//
// SocialCalc.Popup.GetValue(id)
//
// Returns the value of control.
//
SocialCalc.Popup.GetValue = function(id) {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
if (!spc[id]) {alert("Unknown control "+id);return;}
var type = spc[id].type;
var pt = spt[type];
if (pt && pt.Create) {
return pt.GetValue(type, id);
}
return null;
}
//
// SocialCalc.Popup.Initialize(id, data)
//
// Gives "data" to the appropriate initialization code.
//
SocialCalc.Popup.Initialize = function(id, data) {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
if (!spc[id]) {alert("Unknown control "+id);return;}
var type = spc[id].type;
var pt = spt[type];
if (pt && pt.Initialize) {
pt.Initialize(type, id, data);
}
}
//
// SocialCalc.Popup.Reset(type)
//
// Resets Popup, such as when turning to page.
//
SocialCalc.Popup.Reset = function(type) {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
if (spt[type].Reset) spt[type].Reset(type);
}
//
// SocialCalc.Popup.CClick(id)
//
// Should be called when the user clicks on a control to do the popup
//
SocialCalc.Popup.CClick = function(id) {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
if (!spc[id]) {alert("Unknown control "+id);return;}
if (spc[id].data && spc[id].data.disabled) return;
var type = spc[id].type;
var pt = spt[type];
if (sp.Current.id) {
spt[spc[sp.Current.id].type].Hide(type, sp.Current.id);
if (id == sp.Current.id) { // same one - done
sp.Current.id = null;
return;
}
}
if (pt && pt.Show) {
pt.Show(type, id);
}
sp.Current.id = id;
}
//
// SocialCalc.Popup.Close()
//
// Used to close any open popup.
//
SocialCalc.Popup.Close = function() {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
if (!sp.Current.id) return;
sp.CClick(sp.Current.id);
}
//
// SocialCalc.Popup.Cancel()
//
// Closes Popup and restores old value
//
SocialCalc.Popup.Cancel = function() {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
if (!sp.Current.id) return;
var type = spc[sp.Current.id].type;
var pt = spt[type];
pt.Cancel(type, sp.Current.id);
sp.Current.id = null;
}
//
// ele = SocialCalc.Popup.CreatePopupDiv(id, attribs)
//
// Utility function to create the main popup div of width attribs.width.
// If attribs.title, create one with that text, and optionally attribs.moveable.
//
SocialCalc.Popup.CreatePopupDiv = function(id, attribs) {
var pos, ele;
var sp = SocialCalc.Popup;
var spc = sp.Controls;
var spcdata = spc[id].data;
var main = document.createElement("div");
main.style.position = "absolute";
pos = SocialCalc.GetElementPosition(spcdata.mainele);
main.style.top = (pos.top+spcdata.mainele.offsetHeight)+"px";
main.style.left = pos.left+"px";
main.style.zIndex = 100;
main.style.backgroundColor = "#FFF";
main.style.border = "1px solid black";
if (attribs.width) {
main.style.width = attribs.width;
}
spcdata.mainele.appendChild(main);
if (attribs.title) {
main.innerHTML = '<table cellspacing="0" cellpadding="0" style="border-bottom:1px solid black;"><tr>'+
'<td style="font-size:10px;cursor:default;width:100%;background-color:#999;color:#FFF;">'+attribs.title+'</td>'+
'<td style="font-size:10px;cursor:default;color:#666;" onclick="SocialCalc.Popup.Cancel();"> X </td></tr></table>';
if (attribs.moveable) {
spcdata.dragregistered = main.firstChild.firstChild.firstChild.firstChild;
SocialCalc.DragRegister(spcdata.dragregistered, true, true,
{MouseDown: SocialCalc.DragFunctionStart,
MouseMove: SocialCalc.DragFunctionPosition,
MouseUp: SocialCalc.DragFunctionPosition,
Disabled: null, positionobj: main},
spcdata.mainele);
}
}
return main;
}
//
// SocialCalc.Popup.EnsurePosition(id, container)
//
// Utility function to make sure popup is positioned completely within container (both element objects)
// and appropriate with respect to the main element controlling the popup.
//
SocialCalc.Popup.EnsurePosition = function(id, container) {
var sp = SocialCalc.Popup;
var spc = sp.Controls;
var spcdata = spc[id].data;
var main = spcdata.mainele.firstChild;
if (!main) {alert("No main popup element firstChild.");return};
var popup = spcdata.popupele;
function GetLayoutValues(ele) {
var r = SocialCalc.GetElementPosition(ele);
r.height = ele.offsetHeight;
r.width = ele.offsetWidth;
r.bottom = r.top+r.height;
r.right = r.left+r.width;
return r;
}
var p = GetLayoutValues(popup);
var c = GetLayoutValues(container);
var m = GetLayoutValues(main);
var t = 0; // type of placement
//addmsg("popup t/r/b/l/h/w= "+p.top+"/"+p.right+"/"+p.bottom+"/"+p.left+"/"+p.height+"/"+p.width);
//addmsg("container t/r/b/l/h/w= "+c.top+"/"+c.right+"/"+c.bottom+"/"+c.left+"/"+c.height+"/"+c.width);
//addmsg("main t/r/b/l/h/w= "+m.top+"/"+m.right+"/"+m.bottom+"/"+m.left+"/"+m.height+"/"+m.width);
// Check various layout cases in priority order
if (m.bottom+p.height < c.bottom && m.left+p.width < c.right) { // normal case: room on bottom and right
popup.style.top = m.bottom + "px";
popup.style.left = m.left + "px";
t = 1;
}
else if (m.top-p.height > c.top && m.left+p.width < c.right) { // room on top and right
popup.style.top = (m.top-p.height) + "px";
popup.style.left = m.left + "px";
t = 2;
}
else if (m.bottom+p.height < c.bottom && m.right-p.width > c.left) { // room on bottom and left
popup.style.top = m.bottom + "px";
popup.style.left = (m.right-p.width) + "px";
t = 3;
}
else if (m.top-p.height > c.top && m.right-p.width > c.left) { // room on top and left
popup.style.top = (m.top-p.height) + "px";
popup.style.left = (m.right-p.width) + "px";
t = 4;
}
else if (m.bottom+p.height < c.bottom && p.width < c.width) { // room on bottom and middle
popup.style.top = m.bottom + "px";
popup.style.left = (c.left+Math.floor((c.width-p.width)/2)) + "px";
t = 5;
}
else if (m.top-p.height > c.top && p.width < c.width) { // room on top and middle
popup.style.top = (m.top-p.height) + "px";
popup.style.left = (c.left+Math.floor((c.width-p.width)/2)) + "px";
t = 6;
}
else if (p.height < c.height && m.right+p.width < c.right) { // room on middle and right
popup.style.top = (c.top+Math.floor((c.height-p.height)/2)) + "px";
popup.style.left = m.right + "px";
t = 7;
}
else if (p.height < c.height && m.left-p.width > c.left) { // room on middle and left
popup.style.top = (c.top+Math.floor((c.height-p.height)/2)) + "px";
popup.style.left = (m.left-p.width) + "px";
t = 8;
}
else { // nothing works, so leave as it is
}
//addmsg("Popup layout "+t);
}
//
// ele = SocialCalc.Popup.DestroyPopupDiv(ele, dragregistered)
//
// Utility function to get rid of the main popup div.
//
SocialCalc.Popup.DestroyPopupDiv = function(ele, dragregistered) {
if (!ele) return;
ele.innerHTML = "";
SocialCalc.DragUnregister(dragregistered); // OK to do this even if not registered
if (ele.parentNode) {
ele.parentNode.removeChild(ele);
}
}
//
// Color Utility Functions
//
SocialCalc.Popup.RGBToHex = function(val) {
var sp = SocialCalc.Popup;
if (val=="") {
return "000000";
}
var rgbvals = val.match(/(\d+)\D+(\d+)\D+(\d+)/);
if (rgbvals) {
return sp.ToHex(rgbvals[1])+sp.ToHex(rgbvals[2])+sp.ToHex(rgbvals[3]);
}
else {
return "000000";
}
}
SocialCalc.Popup.HexDigits="0123456789ABCDEF";
SocialCalc.Popup.ToHex = function(num) {
var sp = SocialCalc.Popup;
var first=Math.floor(num / 16);
var second=num % 16;
return sp.HexDigits.charAt(first)+sp.HexDigits.charAt(second);
}
SocialCalc.Popup.FromHex = function(str) {
var sp = SocialCalc.Popup;
var first = sp.HexDigits.indexOf(str.charAt(0).toUpperCase());
var second = sp.HexDigits.indexOf(str.charAt(1).toUpperCase());
return ((first>=0)?first:0)*16+((second>=0)?second:0);
}
SocialCalc.Popup.HexToRGB = function(val) {
var sp = SocialCalc.Popup;
return "rgb("+sp.FromHex(val.substring(1,3))+","+sp.FromHex(val.substring(3,5))+","+sp.FromHex(val.substring(5,7))+")";
}
SocialCalc.Popup.makeRGB = function(r, g, b) {
return "rgb("+(r>0?r:0)+","+(g>0?g:0)+","+(b>0?b:0)+")";
}
SocialCalc.Popup.splitRGB = function(rgb) {
var parts = rgb.match(/(\d+)\D+(\d+)\D+(\d+)\D/);
if (!parts) {
return {r:0, g:0, b:0};
}
else {
return {r: parts[1]-0, g: parts[2]-0, b: parts[3]-0};
}
}
// * * * * * * * * * * * * * * * *
//
// ROUTINES FOR EACH TYPE
//
// * * * * * * * * * * * * * * * *
//
// List
//
// type: List
// value: value of control,
// display: "value to display",
// custom: true if custom value,
// disabled: t/f,
// attribs: {
// title: "popup title string",
// moveable: t/f,
// width: optional width, e.g., "100px",
// ensureWithin: optional element object to ensure popup fits within if possible
// changedcallback: optional function(attribs, id, newvalue),
// ...
// }
// data: {
// ncols: calculated number of columns
// options: [
// {o: option-name, v: value-to-return,
// a: {option attribs} // optional: {skip: true, custom: true, cancel: true, newcol: true}
// },
// ...]
// }
//
// popupele: gets popup element object when created
// contentele: gets element created with all the content
// listdiv: gets div with list of items
// customele: gets input element with custom value
// dragregistered: gets element, if any, registered as draggable
//
SocialCalc.Popup.Types.List = {};
SocialCalc.Popup.Types.List.Create = function(type, id, attribs) {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcid = {type: type, value: "", display: "", data: {}};
//if (spc[id]) {alert("Already created "+id); return;}
spc[id] = spcid;
var spcdata = spcid.data;
spcdata.attribs = attribs || {};
var ele = document.getElementById(id);
if (!ele) {alert("Missing element "+id); return;}
spcdata.mainele = ele;
ele.innerHTML = '<input style="cursor:pointer;width:100px;font-size:smaller;" onfocus="this.blur();" onclick="SocialCalc.Popup.CClick(\''+id+'\');" value="">';
spcdata.options = []; // set to nothing - use Initialize to fill
}
SocialCalc.Popup.Types.List.SetValue = function(type, id, value) {
var i;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
spcdata.value = value;
spcdata.custom = false;
for (i=0; i<spcdata.options.length; i++) {
o = spcdata.options[i];
if (o.a) {
if (o.a.skip || o.a.custom || o.a.cancel) {
continue;
}
}
if (o.v == spcdata.value) { // matches value
spcdata.display = o.o;
break;
}
}
if (i==spcdata.options.length) { // none found
spcdata.display = "Custom";
spcdata.custom = true;
}
if (spcdata.mainele && spcdata.mainele.firstChild) {
spcdata.mainele.firstChild.value = spcdata.display;
}
}
SocialCalc.Popup.Types.List.SetDisabled = function(type, id, disabled) {
var i;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
spcdata.disabled = disabled;
if (spcdata.mainele && spcdata.mainele.firstChild) {
spcdata.mainele.firstChild.disabled = disabled;
}
}
SocialCalc.Popup.Types.List.GetValue = function(type, id) {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
return spcdata.value;
}
// data is: {value: initial value, attribs: {attribs stuff}, options: [{o: option-name, v: value-to-return, a: optional-attribs}, ...]}
SocialCalc.Popup.Types.List.Initialize = function(type, id, data) {
var a;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
for (a in data.attribs) {
spcdata.attribs[a] = data.attribs[a];
}
spcdata.options = data ? data.options : [];
if (data.value) { // if has a value, set to it
sp.SetValue(id, data.value);
}
}
SocialCalc.Popup.Types.List.Reset = function(type) {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
if (sp.Current.id && spc[sp.Current.id].type == type) { // we have a popup
spt[type].Hide(type, sp.Current.id);
sp.Current.id = null;
}
}
SocialCalc.Popup.Types.List.Show = function(type, id) {
var i, ele, o, bg;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data
var str = "";
spcdata.popupele = sp.CreatePopupDiv(id, spcdata.attribs);
if (spcdata.custom) {
str = SocialCalc.Popup.Types.List.MakeCustom(type, id);
ele = document.createElement("div");
ele.innerHTML = '<div style="cursor:default;padding:4px;background-color:#CCC;">'+str+'</div>';
spcdata.customele = ele.firstChild.firstChild.childNodes[1];
spcdata.listdiv = null;
spcdata.contentele = ele;
}
else {
str = SocialCalc.Popup.Types.List.MakeList(type, id);
ele = document.createElement("div");
ele.innerHTML = '<div style="cursor:default;padding:4px;">'+str+'</div>';
spcdata.customele = null;
spcdata.listdiv = ele.firstChild;
spcdata.contentele = ele;
}
if (spcdata.mainele && spcdata.mainele.firstChild) {
spcdata.mainele.firstChild.disabled = true;
}
spcdata.popupele.appendChild(ele);
if (spcdata.attribs.ensureWithin) {
SocialCalc.Popup.EnsurePosition(id, spcdata.attribs.ensureWithin);
}
}
SocialCalc.Popup.Types.List.MakeList = function(type, id) {
var i, ele, o, bg;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data
var str = '<table cellspacing="0" cellpadding="0"><tr>';
var td = '<td style="vertical-align:top;">';
str += td;
spcdata.ncols = 1;
for (i=0; i<spcdata.options.length; i++) {
o = spcdata.options[i];
if (o.a) {
if ( o.a.newcol) {
str += '</td>'+td+" "+'</td>'+td;
spcdata.ncols += 1;
continue;
}
if (o.a.skip) {
str += '<div style="font-size:x-small;white-space:nowrap;">'+o.o+'</div>';
continue;
}
}
if (o.v == spcdata.value && !(o.a && (o.a.custom || o.a.cancel))) { // matches value
bg = "background-color:#DDF;";
}
else {
bg = "";
}
str += '<div style="font-size:x-small;white-space:nowrap;'+bg+'" onclick="SocialCalc.Popup.Types.List.ItemClicked(\''+id+'\',\''+i+'\');" onmousemove="SocialCalc.Popup.Types.List.MouseMove(\''+id+'\',this);">'+o.o+'</div>';
}
str += "</td></tr></table>";
return str;
}
SocialCalc.Popup.Types.List.MakeCustom = function(type, id) {
var SPLoc = SocialCalc.Popup.LocalizeString;
var i, ele, o, bg;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
var style = 'style="font-size:smaller;"';
var str = "";
var val = spcdata.value;
val = SocialCalc.special_chars(val);
str = '<div style="white-space:nowrap;"><br>'+
'<input id="customvalue" value="'+val+'"><br><br>'+
'<input '+style+' type="button" value="'+SPLoc("OK")+'" onclick="SocialCalc.Popup.Types.List.CustomOK(\''+id+'\');return false;">'+
'<input '+style+' type="button" value="'+SPLoc("List")+'" onclick="SocialCalc.Popup.Types.List.CustomToList(\''+id+'\');">'+
'<input '+style+' type="button" value="'+SPLoc("Cancel")+'" onclick="SocialCalc.Popup.Close();">'+
'<br></div>';
return str;
}
SocialCalc.Popup.Types.List.ItemClicked = function(id, num) {
var oele, str, nele;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
var a = spcdata.options[num].a;
if (a && a.custom) {
oele = spcdata.contentele;
str = SocialCalc.Popup.Types.List.MakeCustom("List", id);
nele = document.createElement("div");
nele.innerHTML = '<div style="cursor:default;padding:4px;background-color:#CCC;">'+str+'</div>';
spcdata.customele = nele.firstChild.firstChild.childNodes[1];
spcdata.listdiv = null;
spcdata.contentele = nele;
spcdata.popupele.replaceChild(nele, oele);
if (spcdata.attribs.ensureWithin) {
SocialCalc.Popup.EnsurePosition(id, spcdata.attribs.ensureWithin);
}
return;
}
if (a && a.cancel) {
SocialCalc.Popup.Close();
return;
}
SocialCalc.Popup.SetValue(id, spcdata.options[num].v);
SocialCalc.Popup.Close();
}
SocialCalc.Popup.Types.List.CustomToList = function(id) {
var oele, str, nele;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
oele = spcdata.contentele;
str = SocialCalc.Popup.Types.List.MakeList("List", id);
nele = document.createElement("div");
nele.innerHTML = '<div style="cursor:default;padding:4px;">'+str+'</div>';
spcdata.customele = null;
spcdata.listdiv = nele.firstChild;
spcdata.contentele = nele;
spcdata.popupele.replaceChild(nele, oele);
if (spcdata.attribs.ensureWithin) {
SocialCalc.Popup.EnsurePosition(id, spcdata.attribs.ensureWithin);
}
}
SocialCalc.Popup.Types.List.CustomOK = function(id) {
var i, c;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
SocialCalc.Popup.SetValue(id, spcdata.customele.value);
SocialCalc.Popup.Close();
}
SocialCalc.Popup.Types.List.MouseMove = function(id, ele) {
var col, i, c;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
var list = spcdata.listdiv;
if (!list) return;
var rowele = list.firstChild.firstChild.firstChild; // div.table.tbody.tr
for (col=0; col<spcdata.ncols; col++) {
for (i=0; i<rowele.childNodes[col*2].childNodes.length; i++) {
rowele.childNodes[col*2].childNodes[i].style.backgroundColor = "#FFF";
}
}
ele.style.backgroundColor = "#DDF";
}
SocialCalc.Popup.Types.List.Hide = function(type, id) {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
sp.DestroyPopupDiv(spcdata.popupele, spcdata.dragregistered);
spcdata.popupele = null;
if (spcdata.mainele && spcdata.mainele.firstChild) {
spcdata.mainele.firstChild.disabled = false;
}
}
SocialCalc.Popup.Types.List.Cancel = function(type, id) {
SocialCalc.Popup.Types.List.Hide(type, id);
}
//
// ColorChooser
//
// type: ColorChooser
// value: value of control as "rgb(r,g,b)" or "" if default,
// oldvalue: starting value to reset to on close,
// display: "value to display" as hex color value,
// custom: true if custom value,
// disabled: t/f,
// attribs: {
// title: "popup title string",
// moveable: t/f,
// width: optional width, e.g., "100px", of popup chooser
// ensureWithin: optional element object to ensure popup fits within if possible
// sampleWidth: optional width, e.g., "20px",
// sampleHeight: optional height, e.g., "20px",
// backgroundImage: optional background image for sample (transparent where want to show current color), e.g., "colorbg.gif"
// backgroundImageDefault: optional background image for sample when default (transparent shows white)
// backgroundImageDisabled: optional background image for sample when disabled (transparent shows gray)
// changedcallback: optional function(attribs, id, newvalue),
// ...
// }
// data: {
// }
//
// popupele: gets popup element object when created
// contentele: gets element created with all the content
// customele: gets input element with custom value
//
SocialCalc.Popup.Types.ColorChooser = {};
SocialCalc.Popup.Types.ColorChooser.Create = function(type, id, attribs) {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcid = {type: type, value: "", display: "", data: {}};
//if (spc[id]) {alert("Already created "+id); return;}
spc[id] = spcid;
var spcdata = spcid.data;
spcdata.attribs = attribs || {};
var spca = spcdata.attribs;
spcdata.value = "";
var ele = document.getElementById(id);
if (!ele) {alert("Missing element "+id); return;}
spcdata.mainele = ele;
ele.innerHTML = '<div style="cursor:pointer;border:1px solid black;vertical-align:top;width:'+
(spca.sampleWidth || '15px')+';height:'+(spca.sampleHeight || '15px')+
';" onclick="SocialCalc.Popup.Types.ColorChooser.ControlClicked(\''+id+'\');"> </div>';
}
SocialCalc.Popup.Types.ColorChooser.SetValue = function(type, id, value) {
var i, img, pos;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
var spca = spcdata.attribs;
spcdata.value = value;
spcdata.custom = false;
if (spcdata.mainele && spcdata.mainele.firstChild) {
if (spcdata.value) {
spcdata.mainele.firstChild.style.backgroundColor = spcdata.value;
if (spca.backgroundImage) {
img = "url("+sp.imagePrefix+spca.backgroundImage+")";
}
else {
img = "";
}
pos = "center center";
}
else {
spcdata.mainele.firstChild.style.backgroundColor = "#FFF";
if (spca.backgroundImageDefault) {
img = "url("+sp.imagePrefix+spca.backgroundImageDefault+")";
pos = "center center";
}
else {
img = "url("+sp.imagePrefix+"defaultcolor.gif)";
pos = "left top";
}
}
spcdata.mainele.firstChild.style.backgroundPosition = pos;
spcdata.mainele.firstChild.style.backgroundImage = img;
}
}
SocialCalc.Popup.Types.ColorChooser.SetDisabled = function(type, id, disabled) {
var i;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
var spca = spcdata.attribs;
spcdata.disabled = disabled;
if (spcdata.mainele && spcdata.mainele.firstChild) {
if (disabled) {
spcdata.mainele.firstChild.style.backgroundColor = "#DDD";
if (spca.backgroundImageDisabled) {
img = "url("+sp.imagePrefix+spca.backgroundImageDisabled+")";
pos = "center center";
}
else {
img = "url("+sp.imagePrefix+"defaultcolor.gif)";
pos = "left top";
}
spcdata.mainele.firstChild.style.backgroundPosition = pos;
spcdata.mainele.firstChild.style.backgroundImage = img;
}
else {
sp.SetValue(id, spcdata.value);
}
}
}
SocialCalc.Popup.Types.ColorChooser.GetValue = function(type, id) {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
return spcdata.value;
}
SocialCalc.Popup.Types.ColorChooser.Initialize = function(type, id, data) {
var a;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
for (a in data.attribs) {
spcdata.attribs[a] = data.attribs[a];
}
if (data.value) { // if has a value, set to it
sp.SetValue(id, data.value);
}
}
SocialCalc.Popup.Types.ColorChooser.Reset = function(type) {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
if (sp.Current.id && spc[sp.Current.id].type == type) { // we have a popup
spt[type].Hide(type, sp.Current.id);
sp.Current.id = null;
}
}
SocialCalc.Popup.Types.ColorChooser.Show = function(type, id) {
var i, ele, mainele;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data
var str = "";
spcdata.oldvalue = spcdata.value; // remember starting value
spcdata.popupele = sp.CreatePopupDiv(id, spcdata.attribs);
if (spcdata.custom) {
str = SocialCalc.Popup.Types.ColorChooser.MakeCustom(type, id);
ele = document.createElement("div");
ele.innerHTML = '<div style="cursor:default;padding:4px;background-color:#CCC;">'+str+'</div>';
spcdata.customele = ele.firstChild.firstChild.childNodes[2];
spcdata.contentele = ele;
}
else {
mainele = SocialCalc.Popup.Types.ColorChooser.CreateGrid(type, id);
ele = document.createElement("div");
ele.style.padding = "3px";
ele.style.backgroundColor = "#CCC";
ele.appendChild(mainele);
spcdata.customele = null;
spcdata.contentele = ele;
}
spcdata.popupele.appendChild(ele);
if (spcdata.attribs.ensureWithin) {
SocialCalc.Popup.EnsurePosition(id, spcdata.attribs.ensureWithin);
}
}
SocialCalc.Popup.Types.ColorChooser.MakeCustom = function(type, id) {
var i, ele, o, bg;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
var SPLoc = sp.LocalizeString;
var style = 'style="font-size:smaller;"';
var str = "";
str = '<div style="white-space:nowrap;"><br>'+
'#<input id="customvalue" style="width:75px;" value="'+spcdata.value+'"><br><br>'+
'<input '+style+' type="button" value="'+SPLoc("OK")+'" onclick="SocialCalc.Popup.Types.ColorChooser.CustomOK(\''+id+'\');return false;">'+
'<input '+style+' type="button" value="'+SPLoc("Grid")+'" onclick="SocialCalc.Popup.Types.ColorChooser.CustomToGrid(\''+id+'\');">'+
'<br></div>';
return str;
}
SocialCalc.Popup.Types.ColorChooser.ItemClicked = function(id, num) {
var oele, str, nele;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
SocialCalc.Popup.Close();
}
SocialCalc.Popup.Types.ColorChooser.CustomToList = function(id) {
var oele, str, nele;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
}
SocialCalc.Popup.Types.ColorChooser.CustomOK = function(id) {
var i, c;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
sp.SetValue(id, spcdata.customele.value);
sp.Close();
}
SocialCalc.Popup.Types.ColorChooser.Hide = function(type, id) {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
sp.DestroyPopupDiv(spcdata.popupele, spcdata.dragregistered);
spcdata.popupele = null;
}
SocialCalc.Popup.Types.ColorChooser.Cancel = function(type, id) {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
sp.SetValue(id, spcdata.oldvalue); // reset to old value
SocialCalc.Popup.Types.ColorChooser.Hide(type, id);
}
SocialCalc.Popup.Types.ColorChooser.CreateGrid = function (type, id) {
var ele, pos, row, rowele, col, g;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var SPLoc = sp.LocalizeString;
var spcdata = spc[id].data;
spcdata.grid = {};
var grid = spcdata.grid;
var mainele = document.createElement("div");
ele = document.createElement("table");
ele.cellSpacing = 0;
ele.cellPadding = 0;
ele.style.width = "100px";
grid.table = ele;
ele = document.createElement("tbody");
grid.table.appendChild(ele);
grid.tbody = ele;
for (row=0; row<16; row++) {
rowele = document.createElement("tr");
for (col=0; col<5; col++) {
g = {};
grid[row+","+col] = g;
ele = document.createElement("td");
ele.style.fontSize = "1px";
ele.innerHTML = " ";
ele.style.height = "10px";
if (col<=1) {
ele.style.width = "17px";
ele.style.borderRight = "3px solid white";
}
else {
ele.style.width = "20px";
ele.style.backgroundRepeat = "no-repeat";
}
rowele.appendChild(ele);
g.ele = ele;
}
grid.tbody.appendChild(rowele);
}
mainele.appendChild(grid.table);
ele = document.createElement("div");
ele.style.marginTop = "3px";
ele.innerHTML = '<table cellspacing="0" cellpadding="0"><tr>'+
'<td style="width:17px;background-color:#FFF;background-image:url('+sp.imagePrefix+'defaultcolor.gif);height:16px;font-size:10px;cursor:pointer;" title="'+SPLoc("Default")+'"> </td>'+
'<td style="width:23px;height:16px;font-size:10px;text-align:center;cursor:pointer;" title="'+SPLoc("Custom")+'">#</td>'+
'<td style="width:60px;height:16px;font-size:10px;text-align:center;cursor:pointer;">'+SPLoc("OK")+'</td>'+
'</tr></table>';
grid.defaultbox = ele.firstChild.firstChild.firstChild.childNodes[0];
grid.defaultbox.onclick = spt.ColorChooser.DefaultClicked;
grid.custom = ele.firstChild.firstChild.firstChild.childNodes[1];
grid.custom.onclick = spt.ColorChooser.CustomClicked;
grid.msg = ele.firstChild.firstChild.firstChild.childNodes[2];
grid.msg.onclick = spt.ColorChooser.CloseOK;
mainele.appendChild(ele);
grid.table.onmousedown = spt.ColorChooser.GridMouseDown;
spt.ColorChooser.DetermineColors(id);
spt.ColorChooser.SetColors(id);
return mainele;
}
SocialCalc.Popup.Types.ColorChooser.gridToG = function(grid, row, col) {
return grid[row+","+col];
}
SocialCalc.Popup.Types.ColorChooser.DetermineColors = function(id) {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var sptc = spt.ColorChooser;
var spc = sp.Controls;
var spcdata = spc[id].data;
var grid = spcdata.grid;
var col, row;
var rgb = sp.splitRGB(spcdata.value);
var color;
col = 2;
row = 16-Math.floor((rgb.r+16)/16);
grid["selectedrow"+col] = row;
for (row=0; row<16; row++) {
sptc.gridToG(grid,row,col).rgb = sp.makeRGB(17*(15-row),0,0);
}
col = 3;
row = 16-Math.floor((rgb.g+16)/16);
grid["selectedrow"+col] = row;
for (row=0; row<16; row++) {
sptc.gridToG(grid,row,col).rgb = sp.makeRGB(0,17*(15-row),0);
}
col = 4;
row = 16-Math.floor((rgb.b+16)/16);
grid["selectedrow"+col] = row;
for (row=0; row<16; row++) {
sptc.gridToG(grid,row,col).rgb = sp.makeRGB(0,0,17*(15-row));
}
col = 1;
for (row=0; row<16; row++) {
sptc.gridToG(grid,row,col).rgb = sp.makeRGB(17*(15-row),17*(15-row),17*(15-row));
}
col = 0;
var steps = [0, 68, 153, 204, 255];
var commonrgb = ["400", "310", "420", "440", "442", "340", "040", "042", "032", "044", "024", "004", "204", "314", "402", "414"];
var x;
for (row=0; row<16; row++) {
x = commonrgb[row];
sptc.gridToG(grid,row,col).rgb = "rgb("+steps[x.charAt(0)-0]+","+steps[x.charAt(1)-0]+","+steps[x.charAt(2)-0]+")";
}
}
SocialCalc.Popup.Types.ColorChooser.SetColors = function(id) {
var row, col, g, ele, rgb;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var sptc = spt.ColorChooser;
var spc = sp.Controls;
var spcdata = spc[id].data;
var grid = spcdata.grid;
for (row=0; row<16; row++) {
for (col=0; col<5; col++) {
g = sptc.gridToG(grid,row, col);
g.ele.style.backgroundColor = g.rgb;
g.ele.title = sp.RGBToHex(g.rgb);
if (grid["selectedrow"+col]==row) {
g.ele.style.backgroundImage = "url("+sp.imagePrefix+"chooserarrow.gif)";
}
else {
g.ele.style.backgroundImage = "";
}
}
}
sp.SetValue(id, spcdata.value);
grid.msg.style.backgroundColor = spcdata.value;
rgb = sp.splitRGB(spcdata.value || "rgb(255,255,255)");
if (rgb.r+rgb.g+rgb.b < 220) {
grid.msg.style.color = "#FFF";
}
else {
grid.msg.style.color = "#000";
}
if (!spcdata.value) { // default
grid.msg.style.backgroundColor = "#FFF";
grid.msg.style.backgroundImage = "url("+sp.imagePrefix+"defaultcolor.gif)";
grid.msg.title = "Default";
}
else {
grid.msg.style.backgroundImage = "";
grid.msg.title = sp.RGBToHex(spcdata.value);
}
}
SocialCalc.Popup.Types.ColorChooser.GridMouseDown = function(e) {
var event = e || window.event;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var sptc = spt.ColorChooser;
var spc = sp.Controls;
var id = sp.Current.id;
if (!id) return;
var spcdata = spc[id].data;
var grid = spcdata.grid;
switch (event.type) {
case "mousedown":
grid.mousedown = true;
break;
case "mouseup":
grid.mousedown = false;
break;
case "mousemove":
if (!grid.mousedown) {
return;
}
break;
}
var pos = SocialCalc.GetElementPositionWithScroll(spcdata.mainele);
var clientX = event.clientX - pos.left;
var clientY = event.clientY - pos.top;
var gpos = SocialCalc.GetElementPositionWithScroll(grid.table);
gpos.left -= pos.left;
gpos.top -= pos.top
var row = Math.floor((clientY-gpos.top-2)/10); // -2 is to split the diff btw IE & FF
row = row < 0 ? 0 : row;
var col = Math.floor((clientX-gpos.left)/20);
row = row < 0 ? 0 : (row > 15 ? 15 : row);
col = col < 0 ? 0 : (col > 4 ? 4 : col);
var color = sptc.gridToG(grid,row,col).ele.style.backgroundColor;
var newrgb = sp.splitRGB(color);
var oldrgb = sp.splitRGB(spcdata.value);
switch (col) {
case 2:
spcdata.value = sp.makeRGB(newrgb.r, oldrgb.g, oldrgb.b);
break;
case 3:
spcdata.value = sp.makeRGB(oldrgb.r, newrgb.g, oldrgb.b);
break;
case 4:
spcdata.value = sp.makeRGB(oldrgb.r, oldrgb.g, newrgb.b);
break;
case 0:
case 1:
spcdata.value = color;
}
sptc.DetermineColors(id);
sptc.SetColors(id);
}
SocialCalc.Popup.Types.ColorChooser.ControlClicked = function(id) {
var sp = SocialCalc.Popup;
var spt = sp.Types;
var sptc = spt.ColorChooser;
var spc = sp.Controls;
var cid = sp.Current.id;
if (!cid || id != cid) {
sp.CClick(id);
return;
}
sptc.CloseOK();
}
SocialCalc.Popup.Types.ColorChooser.DefaultClicked = function(e) {
var event = e || window.event;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var sptc = spt.ColorChooser;
var spc = sp.Controls;
var id = sp.Current.id;
if (!id) return;
var spcdata = spc[id].data;
spcdata.value = "";
SocialCalc.Popup.SetValue(id, spcdata.value);
SocialCalc.Popup.Close();
}
SocialCalc.Popup.Types.ColorChooser.CustomClicked = function(e) {
var event = e || window.event;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var sptc = spt.ColorChooser;
var spc = sp.Controls;
var id = sp.Current.id;
if (!id) return;
var spcdata = spc[id].data;
var oele, str, nele;
oele = spcdata.contentele;
str = SocialCalc.Popup.Types.ColorChooser.MakeCustom("ColorChooser", id);
nele = document.createElement("div");
nele.innerHTML = '<div style="cursor:default;padding:4px;background-color:#CCC;">'+str+'</div>';
spcdata.customele = nele.firstChild.firstChild.childNodes[2];
spcdata.contentele = nele;
spcdata.popupele.replaceChild(nele, oele);
spcdata.customele.value = sp.RGBToHex(spcdata.value);
if (spcdata.attribs.ensureWithin) {
SocialCalc.Popup.EnsurePosition(id, spcdata.attribs.ensureWithin);
}
}
SocialCalc.Popup.Types.ColorChooser.CustomToGrid = function(id) {
var oele, str, nele;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
SocialCalc.Popup.SetValue(id, sp.HexToRGB("#"+spcdata.customele.value));
var oele, mainele, nele;
oele = spcdata.contentele;
mainele = SocialCalc.Popup.Types.ColorChooser.CreateGrid("ColorChooser", id);
nele = document.createElement("div");
nele.style.padding = "3px";
nele.style.backgroundColor = "#CCC";
nele.appendChild(mainele);
spcdata.customele = null;
spcdata.contentele = nele;
spcdata.popupele.replaceChild(nele, oele);
if (spcdata.attribs.ensureWithin) {
SocialCalc.Popup.EnsurePosition(id, spcdata.attribs.ensureWithin);
}
}
SocialCalc.Popup.Types.ColorChooser.CustomOK = function(id) {
var i, c;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var spc = sp.Controls;
var spcdata = spc[id].data;
SocialCalc.Popup.SetValue(id, sp.HexToRGB("#"+spcdata.customele.value));
SocialCalc.Popup.Close();
}
SocialCalc.Popup.Types.ColorChooser.CloseOK = function(e) {
var event = e || window.event;
var sp = SocialCalc.Popup;
var spt = sp.Types;
var sptc = spt.ColorChooser;
var spc = sp.Controls;
var id = sp.Current.id;
if (!id) return;
var spcdata = spc[id].data;
SocialCalc.Popup.SetValue(id, spcdata.value);
SocialCalc.Popup.Close();
}
| 2014c2g12/c2g12 | wsgi/wsgi/static/socialcalc/socialcalcpopup.js | JavaScript | gpl-2.0 | 41,803 |
/*!
* froala_editor v2.1.0 (https://www.froala.com/wysiwyg-editor)
* License https://froala.com/wysiwyg-editor/terms
* Copyright 2014-2016 Froala Labs
*/
/**
* German
*/
$.FroalaEditor.LANGUAGE['de'] = {
translation: {
// Place holder
"Type something": "Schreiben Sie etwas",
// Basic formatting
"Bold": "Fett",
"Italic": "Kursiv",
"Underline": "Unterstrichen",
"Strikethrough": "Durchgestrichen",
// Main buttons
"Insert": "Einf\u00fcgen",
"Delete": "L\u00f6schen",
"Cancel": "Abbrechen",
"OK": "Ok",
"Back": "Zur\u00fcck",
"Remove": "Entfernen",
"More": "Mehr",
"Update": "Aktualisierung",
"Style": "Stil",
// Font
"Font Family": "Schriftart",
"Font Size": "Schriftgr\u00f6\u00dfe",
// Colors
"Colors": "Farben",
"Background": "Hintergrund",
"Text": "Text",
// Paragraphs
"Paragraph Format": "Formate",
"Normal": "Normal",
"Code": "Quelltext",
"Heading 1": "\u00dcberschrift 1",
"Heading 2": "\u00dcberschrift 2",
"Heading 3": "\u00dcberschrift 3",
"Heading 4": "\u00dcberschrift 4",
// Style
"Paragraph Style": "Absatz-Stil",
"Inline Style": "Inline-Stil",
// Alignment
"Align": "Ausrichtung",
"Align Left": "Linksb\u00fcndig ausrichten",
"Align Center": "Zentriert ausrichten",
"Align Right": "Rechtsb\u00fcndig ausrichten",
"Align Justify": "Blocksatz",
"None": "Keine",
// Lists
"Ordered List": "Geordnete Liste",
"Unordered List": "Ungeordnete Liste",
// Indent
"Decrease Indent": "Einzug Verkleinern",
"Increase Indent": "Einzug Vergr\u00f6\u00dfern",
// Links
"Insert Link": "Link einf\u00fcgen",
"Open in new tab": "In neuem Tab \u00f6ffnen",
"Open Link": "Link \u00d6ffnen",
"Edit Link": "Link Bearbeiten",
"Unlink": "Link entfernen",
"Choose Link": "Einen Link ausw\u00e4hlen",
// Images
"Insert Image": "Bild Einf\u00fcgen",
"Upload Image": "Bild Hochladen",
"By URL": "Von URL",
"Browse": "Ordner",
"Drop image": "Ziehen Sie ein Bild hierhin",
"or click": "oder klicken Sie hier",
"Manage Images": "Bilder Verwalten",
"Loading": "Laden",
"Deleting": "L\u00f6schen",
"Tags": "Tags",
"Are you sure? Image will be deleted.": "Sind Sie sicher? Das Bild wird gel\u00f6scht.",
"Replace": "Ersetzen",
"Uploading": "Hochladen",
"Loading image": "Das Bild wird geladen",
"Display": "Textausrichtung",
"Inline": "Mit Text in einer Zeile",
"Break Text": "Text umbrechen",
"Alternate Text": "Alternativtext",
"Change Size": "Gr\u00f6\u00dfe \u00e4ndern",
"Width": "Breite",
"Height": "H\u00f6he",
"Something went wrong. Please try again.": "Etwas ist schief gelaufen. Bitte versuchen Sie es erneut.",
// Video
"Insert Video": "Video einf\u00fcgen",
"Embedded Code": "Eingebetteter Code",
// Tables
"Insert Table": "Tabelle einf\u00fcgen",
"Header": "Kopfzeile",
"Row": "Zeile",
"Insert row above": "Neue Zeile davor einf\u00fcgen",
"Insert row below": "Neue Zeile danach einf\u00fcgen",
"Delete row": "Zeile l\u00f6schen",
"Column": "Spalte",
"Insert column before": "Neue Spalte davor einf\u00fcgen",
"Insert column after": "Neue Spalte danach einf\u00fcgen",
"Delete column": "Spalte l\u00f6schen",
"Cell": "Zelle",
"Merge cells": "Zelle verschmelzen",
"Horizontal split": "Horizontal teilen",
"Vertical split": "Vertikal teilen",
"Cell Background": "Zellenhintergrund",
"Vertical Align": "Vertikale Ausrichtung",
"Top": "Oben",
"Middle": "Zentriert",
"Bottom": "Unten",
"Align Top": "Oben ausrichten",
"Align Middle": "Zentriert ausrichten",
"Align Bottom": "Unten ausrichten",
"Cell Style": "Zellen-Stil",
// Files
"Upload File": "Datei Hochladen",
"Drop file": "Ziehen Sie eine Datei hierhin",
// Emoticons
"Emoticons": "Emoticons",
"Grinning face": "Grinsendes Gesicht",
"Grinning face with smiling eyes": "Grinsend Gesicht mit l\u00e4chelnden Augen",
"Face with tears of joy": "Gesicht mit Tr\u00e4nen der Freude",
"Smiling face with open mouth": "L\u00e4chelndes Gesicht mit offenem Mund",
"Smiling face with open mouth and smiling eyes": "L\u00e4chelndes Gesicht mit offenem Mund und l\u00e4chelnden Augen",
"Smiling face with open mouth and cold sweat": "L\u00e4chelndes Gesicht mit offenem Mund und kaltem Schwei\u00df",
"Smiling face with open mouth and tightly-closed eyes": "L\u00e4chelndes Gesicht mit offenem Mund und fest geschlossenen Augen",
"Smiling face with halo": "L\u00e4cheln Gesicht mit Heiligenschein",
"Smiling face with horns": "L\u00e4cheln Gesicht mit H\u00f6rnern",
"Winking face": "Zwinkerndes Gesicht",
"Smiling face with smiling eyes": "L\u00e4chelndes Gesicht mit l\u00e4chelnden Augen",
"Face savoring delicious food": "Gesicht leckeres Essen genie\u00dfend",
"Relieved face": "Erleichtertes Gesicht",
"Smiling face with heart-shaped eyes": "L\u00e4chelndes Gesicht mit herzf\u00f6rmigen Augen",
"Smiling face with sunglasses": "L\u00e4chelndes Gesicht mit Sonnenbrille",
"Smirking face": "Grinsendes Gesicht",
"Neutral face": "Neutrales Gesicht",
"Expressionless face": "Ausdrucksloses Gesicht",
"Unamused face": "Genervtes Gesicht",
"Face with cold sweat": "Gesicht mit kaltem Schwei\u00df",
"Pensive face": "Nachdenkliches Gesicht",
"Confused face": "Verwirrtes Gesicht",
"Confounded face": "Elendes Gesicht",
"Kissing face": "K\u00fcssendes Gesicht",
"Face throwing a kiss": "Gesicht wirft einen Kuss",
"Kissing face with smiling eyes": "K\u00fcssendes Gesicht mit l\u00e4chelnden Augen",
"Kissing face with closed eyes": "K\u00fcssendes Gesicht mit geschlossenen Augen",
"Face with stuck out tongue": "Gesicht mit herausgestreckter Zunge",
"Face with stuck out tongue and winking eye": "Gesicht mit herausgestreckter Zunge und zwinkerndem Auge",
"Face with stuck out tongue and tightly-closed eyes": "Gesicht mit herausgestreckter Zunge und fest geschlossenen Augen",
"Disappointed face": "Entt\u00e4uschtes Gesicht",
"Worried face": "Besorgtes Gesicht",
"Angry face": "Ver\u00e4rgertes Gesicht",
"Pouting face": "Schmollendes Gesicht",
"Crying face": "Weinendes Gesicht",
"Persevering face": "Ausharrendes Gesicht",
"Face with look of triumph": "Gesicht mit triumphierenden Blick",
"Disappointed but relieved face": "Entt\u00e4uschtes, aber erleichtertes Gesicht",
"Frowning face with open mouth": "Entsetztes Gesicht mit offenem Mund",
"Anguished face": "Gequ\u00e4ltes Gesicht",
"Fearful face": "Angstvolles Gesicht",
"Weary face": "M\u00fcdes Gesicht",
"Sleepy face": "Schl\u00e4friges Gesicht",
"Tired face": "G\u00e4hnendes Gesicht",
"Grimacing face": "Grimassenschneidendes Gesicht",
"Loudly crying face": "Laut weinendes Gesicht",
"Face with open mouth": "Gesicht mit offenem Mund",
"Hushed face": "Besorgtes Gesicht mit offenem Mund",
"Face with open mouth and cold sweat": "Gesicht mit offenem Mund und kaltem Schwei\u00df",
"Face screaming in fear": "Vor Angst schreiendes Gesicht",
"Astonished face": "Erstauntes Gesicht",
"Flushed face": "Ger\u00f6tetes Gesicht",
"Sleeping face": "Schlafendes Gesicht",
"Dizzy face": "Schwindliges Gesicht",
"Face without mouth": "Gesicht ohne Mund",
"Face with medical mask": "Gesicht mit Mundschutz",
// Line breaker
"Break": "Zeilenumbruch",
// Math
"Subscript": "Tiefgestellt",
"Superscript": "Hochgestellt",
// Full screen
"Fullscreen": "Vollbild",
// Horizontal line
"Insert Horizontal Line": "Horizontale Linie Einf\u00fcgen",
// Clear formatting
"Clear Formatting": "Formatierung L\u00f6schen",
// Undo, redo
"Undo": "R\u00fcckg\u00e4ngig",
"Redo": "Wiederholen",
// Select all
"Select All": "Alles ausw\u00e4hlen",
// Code view
"Code View": "Code-Ansicht",
// Quote
"Quote": "Zitieren",
"Increase": "Vergr\u00f6\u00dfern",
"Decrease": "Verkleinern"
},
direction: "ltr"
}; | ThomasZh/legend-club-wxpub | static/froala_editor_2/js/languages/de.js | JavaScript | apache-2.0 | 8,261 |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @providesModule react-native-interface
*/
'use strict';
// see also react-native.js
declare var __DEV__: boolean;
declare var __REACT_DEVTOOLS_GLOBAL_HOOK__: any; /*?{
inject: ?((stuff: Object) => void)
};*/
declare var fetch: any;
declare var Headers: any;
declare var Request: any;
declare var Response: any;
declare module requestAnimationFrame {
declare var exports: (callback: any) => any;
}
| gunaangs/Feedonymous | node_modules/react-native/Libraries/react-native/react-native-interface.js | JavaScript | mit | 726 |
// enyo.js
(function() {
var e = "enyo.js";
enyo = window.enyo || {}, enyo.locateScript = function(e) {
var t = document.getElementsByTagName("script");
for (var n = t.length - 1, r, i, s = e.length; n >= 0 && (r = t[n]); n--) if (!r.located) {
i = r.getAttribute("src") || "";
if (i.slice(-s) == e) return r.located = !0, {
path: i.slice(0, Math.max(0, i.lastIndexOf("/"))),
node: r
};
}
}, enyo.args = enyo.args || {};
var t = enyo.locateScript(e);
if (t) {
enyo.args.root = (enyo.args.root || t.path).replace("/source", "");
for (var n = 0, r = t.node.attributes.length, i; n < r && (i = t.node.attributes.item(n)); n++) enyo.args[i.nodeName] = i.value;
}
})();
// ../../loader.js
(function() {
enyo = window.enyo || {}, enyo.pathResolverFactory = function() {
this.paths = {};
}, enyo.pathResolverFactory.prototype = {
addPath: function(e, t) {
return this.paths[e] = t;
},
addPaths: function(e) {
if (e) for (var t in e) this.addPath(t, e[t]);
},
includeTrailingSlash: function(e) {
return e && e.slice(-1) !== "/" ? e + "/" : e;
},
rewritePattern: /\$([^\/\\]*)(\/)?/g,
rewrite: function(e) {
var t, n = this.includeTrailingSlash, r = this.paths, i = function(e, i) {
return t = !0, n(r[i]) || "";
}, s = e;
do t = !1, s = s.replace(this.rewritePattern, i); while (t);
return s;
}
}, enyo.path = new enyo.pathResolverFactory, enyo.loaderFactory = function(e, t) {
this.machine = e, this.packages = [], this.modules = [], this.sheets = [], this.stack = [], this.pathResolver = t || enyo.path, this.packageName = "", this.packageFolder = "", this.finishCallbacks = {};
}, enyo.loaderFactory.prototype = {
verbose: !1,
loadScript: function(e) {
this.machine.script(e);
},
loadSheet: function(e) {
this.machine.sheet(e);
},
loadPackage: function(e) {
this.machine.script(e);
},
report: function() {},
load: function() {
this.more({
index: 0,
depends: arguments || []
});
},
more: function(e) {
if (e && this.continueBlock(e)) return;
var t = this.stack.pop();
t ? (this.verbose && console.groupEnd("* finish package (" + (t.packageName || "anon") + ")"), this.packageFolder = t.folder, this.packageName = "", this.more(t)) : this.finish();
},
finish: function() {
this.packageFolder = "", this.verbose && console.log("-------------- fini");
for (var e in this.finishCallbacks) this.finishCallbacks[e] && (this.finishCallbacks[e](), this.finishCallbacks[e] = null);
},
continueBlock: function(e) {
while (e.index < e.depends.length) {
var t = e.depends[e.index++];
if (t) if (typeof t == "string") {
if (this.require(t, e)) return !0;
} else this.pathResolver.addPaths(t);
}
},
require: function(e, t) {
var n = this.pathResolver.rewrite(e), r = this.getPathPrefix(e);
n = r + n;
if (n.slice(-4) == ".css" || n.slice(-5) == ".less") this.verbose && console.log("+ stylesheet: [" + r + "][" + e + "]"), this.requireStylesheet(n); else {
if (n.slice(-3) != ".js" || n.slice(-10) == "package.js") return this.requirePackage(n, t), !0;
this.verbose && console.log("+ module: [" + r + "][" + e + "]"), this.requireScript(e, n);
}
},
getPathPrefix: function(e) {
var t = e.slice(0, 1);
return t != "/" && t != "\\" && t != "$" && !/^https?:/i.test(e) ? this.packageFolder : "";
},
requireStylesheet: function(e) {
this.sheets.push(e), this.loadSheet(e);
},
requireScript: function(e, t) {
this.modules.push({
packageName: this.packageName,
rawPath: e,
path: t
}), this.loadScript(t);
},
decodePackagePath: function(e) {
var t = "", n = "", r = "", i = "package.js", s = e.replace(/\\/g, "/").replace(/\/\//g, "/").replace(/:\//, "://").split("/"), o, u;
if (s.length) {
var a = s.pop() || s.pop() || "";
a.slice(-i.length) !== i ? s.push(a) : i = a, r = s.join("/"), r = r ? r + "/" : "", i = r + i;
for (o = s.length - 1; o >= 0; o--) if (s[o] == "source") {
s.splice(o, 1);
break;
}
n = s.join("/");
for (o = s.length - 1; u = s[o]; o--) if (u == "lib" || u == "enyo") {
s = s.slice(o + 1);
break;
}
for (o = s.length - 1; u = s[o]; o--) (u == ".." || u == ".") && s.splice(o, 1);
t = s.join("-");
}
return {
alias: t,
target: n,
folder: r,
manifest: i
};
},
aliasPackage: function(e) {
var t = this.decodePackagePath(e);
this.manifest = t.manifest, t.alias && (this.pathResolver.addPath(t.alias, t.target), this.packageName = t.alias, this.packages.push({
name: t.alias,
folder: t.folder
})), this.packageFolder = t.folder;
},
requirePackage: function(e, t) {
t.folder = this.packageFolder, this.aliasPackage(e), t.packageName = this.packageName, this.stack.push(t), this.report("loading package", this.packageName), this.verbose && console.group("* start package [" + this.packageName + "]"), this.loadPackage(this.manifest);
}
};
})();
// boot.js
enyo.execUnsafeLocalFunction = function(e) {
typeof MSApp == "undefined" ? e() : MSApp.execUnsafeLocalFunction(e);
}, enyo.machine = {
sheet: function(e) {
var t = "text/css", n = "stylesheet", r = e.slice(-5) == ".less";
r && (window.less ? (t = "text/less", n = "stylesheet/less") : e = e.slice(0, e.length - 4) + "css");
var i;
enyo.runtimeLoading || r ? (i = document.createElement("link"), i.href = e, i.media = "screen", i.rel = n, i.type = t, document.getElementsByTagName("head")[0].appendChild(i)) : (i = function() {
document.write('<link href="' + e + '" media="screen" rel="' + n + '" type="' + t + '" />');
}, enyo.execUnsafeLocalFunction(i)), r && window.less && (less.sheets.push(i), enyo.loader.finishCallbacks.lessRefresh || (enyo.loader.finishCallbacks.lessRefresh = function() {
less.refresh(!0);
}));
},
script: function(e, t, n) {
if (!enyo.runtimeLoading) document.write('<script src="' + e + '"' + (t ? ' onload="' + t + '"' : "") + (n ? ' onerror="' + n + '"' : "") + "></scri" + "pt>"); else {
var r = document.createElement("script");
r.src = e, r.onload = t, r.onerror = n, document.getElementsByTagName("head")[0].appendChild(r);
}
},
inject: function(e) {
document.write('<script type="text/javascript">' + e + "</scri" + "pt>");
}
}, enyo.loader = new enyo.loaderFactory(enyo.machine), enyo.depends = function() {
var e = enyo.loader;
if (!e.packageFolder) {
var t = enyo.locateScript("package.js");
t && t.path && (e.aliasPackage(t.path), e.packageFolder = t.path + "/");
}
e.load.apply(e, arguments);
}, function() {
function n(r) {
r && r();
if (t.length) {
var i = t.shift(), s = i[0], o = e.isArray(s) ? s : [ s ], u = i[1];
e.loader.finishCallbacks.runtimeLoader = function() {
n(function() {
u && u(s);
});
}, e.loader.packageFolder = "./", e.depends.apply(this, o);
} else e.runtimeLoading = !1, e.loader.packageFolder = "";
}
var e = window.enyo, t = [];
e.load = function(r, i) {
t.push(arguments), e.runtimeLoading || (e.runtimeLoading = !0, n());
};
}(), enyo.path.addPaths({
enyo: enyo.args.root,
lib: "$enyo/../lib"
});
// log.js
enyo.logging = {
level: 99,
levels: {
log: 20,
warn: 10,
error: 0
},
shouldLog: function(e) {
var t = parseInt(this.levels[e], 0);
return t <= this.level;
},
_log: function(e, t) {
if (typeof console == "undefined") return;
var n = enyo.isArray(t) ? t : enyo.cloneArray(t);
enyo.dumbConsole && (n = [ n.join(" ") ]);
var r = console[e];
r && r.apply ? r.apply(console, n) : console.log.apply ? console.log.apply(console, n) : console.log(n.join(" "));
},
log: function(e, t) {
typeof console != "undefined" && this.shouldLog(e) && this._log(e, t);
}
}, enyo.setLogLevel = function(e) {
var t = parseInt(e, 0);
isFinite(t) && (enyo.logging.level = t);
}, enyo.log = function() {
enyo.logging.log("log", arguments);
}, enyo.warn = function() {
enyo.logging.log("warn", arguments);
}, enyo.error = function() {
enyo.logging.log("error", arguments);
};
// lang.js
(function() {
enyo.global = this, enyo._getProp = function(e, t, n) {
var r = n || enyo.global;
for (var i = 0, s; r && (s = e[i]); i++) r = s in r ? r[s] : t ? r[s] = {} : undefined;
return r;
}, enyo.setObject = function(e, t, n) {
var r = e.split("."), i = r.pop(), s = enyo._getProp(r, !0, n);
return s && i ? s[i] = t : undefined;
}, enyo.getObject = function(e, t, n) {
return enyo._getProp(e.split("."), t, n);
}, enyo.irand = function(e) {
return Math.floor(Math.random() * e);
}, enyo.cap = function(e) {
return e.slice(0, 1).toUpperCase() + e.slice(1);
}, enyo.uncap = function(e) {
return e.slice(0, 1).toLowerCase() + e.slice(1);
}, enyo.format = function(e) {
var t = /\%./g, n = 0, r = e, i = arguments, s = function(e) {
return i[++n];
};
return r.replace(t, s);
};
var e = Object.prototype.toString;
enyo.isString = function(t) {
return e.call(t) === "[object String]";
}, enyo.isFunction = function(t) {
return e.call(t) === "[object Function]";
}, enyo.isArray = Array.isArray || function(t) {
return e.call(t) === "[object Array]";
}, enyo.isTrue = function(e) {
return e !== "false" && e !== !1 && e !== 0 && e !== null && e !== undefined;
}, enyo.indexOf = function(e, t, n) {
if (t.indexOf) return t.indexOf(e, n);
if (n) {
n < 0 && (n = 0);
if (n > t.length) return -1;
}
for (var r = n || 0, i = t.length, s; (s = t[r]) || r < i; r++) if (s == e) return r;
return -1;
}, enyo.remove = function(e, t) {
var n = enyo.indexOf(e, t);
n >= 0 && t.splice(n, 1);
}, enyo.forEach = function(e, t, n) {
if (e) {
var r = n || this;
if (enyo.isArray(e) && e.forEach) e.forEach(t, r); else {
var i = Object(e), s = i.length >>> 0;
for (var o = 0; o < s; o++) o in i && t.call(r, i[o], o, i);
}
}
}, enyo.map = function(e, t, n) {
var r = n || this;
if (enyo.isArray(e) && e.map) return e.map(t, r);
var i = [], s = function(e, n, s) {
i.push(t.call(r, e, n, s));
};
return enyo.forEach(e, s, r), i;
}, enyo.filter = function(e, t, n) {
var r = n || this;
if (enyo.isArray(e) && e.filter) return e.filter(t, r);
var i = [], s = function(e, n, s) {
var o = e;
t.call(r, e, n, s) && i.push(o);
};
return enyo.forEach(e, s, r), i;
}, enyo.keys = Object.keys || function(e) {
var t = [], n = Object.prototype.hasOwnProperty;
for (var r in e) n.call(e, r) && t.push(r);
if (!{
toString: null
}.propertyIsEnumerable("toString")) {
var i = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ];
for (var s = 0, o; o = i[s]; s++) n.call(e, o) && t.push(o);
}
return t;
}, enyo.cloneArray = function(e, t, n) {
var r = n || [];
for (var i = t || 0, s = e.length; i < s; i++) r.push(e[i]);
return r;
}, enyo.toArray = enyo.cloneArray, enyo.clone = function(e) {
return enyo.isArray(e) ? enyo.cloneArray(e) : enyo.mixin({}, e);
};
var t = {};
enyo.mixin = function(e, n) {
e = e || {};
if (n) {
var r, i, s;
for (r in n) i = n[r], t[r] !== i && (e[r] = i);
}
return e;
}, enyo.bind = function(e, t) {
t || (t = e, e = null), e = e || enyo.global;
if (enyo.isString(t)) {
if (!e[t]) throw [ 'enyo.bind: scope["', t, '"] is null (scope="', e, '")' ].join("");
t = e[t];
}
if (enyo.isFunction(t)) {
var n = enyo.cloneArray(arguments, 2);
return t.bind ? t.bind.apply(t, [ e ].concat(n)) : function() {
var r = enyo.cloneArray(arguments);
return t.apply(e, n.concat(r));
};
}
throw [ 'enyo.bind: scope["', t, '"] is not a function (scope="', e, '")' ].join("");
}, enyo.asyncMethod = function(e, t) {
return setTimeout(enyo.bind.apply(enyo, arguments), 1);
}, enyo.call = function(e, t, n) {
var r = e || this;
if (t) {
var i = r[t] || t;
if (i && i.apply) return i.apply(r, n || []);
}
}, enyo.now = Date.now || function() {
return (new Date).getTime();
}, enyo.nop = function() {}, enyo.nob = {}, enyo.nar = [], enyo.instance = function() {}, enyo.setPrototype || (enyo.setPrototype = function(e, t) {
e.prototype = t;
}), enyo.delegate = function(e) {
return enyo.setPrototype(enyo.instance, e), new enyo.instance;
}, $L = function(e) {
return e;
};
})();
// job.js
enyo.job = function(e, t, n) {
enyo.job.stop(e), enyo.job._jobs[e] = setTimeout(function() {
enyo.job.stop(e), t();
}, n);
}, enyo.job.stop = function(e) {
enyo.job._jobs[e] && (clearTimeout(enyo.job._jobs[e]), delete enyo.job._jobs[e]);
}, enyo.job._jobs = {};
// macroize.js
enyo.macroize = function(e, t, n) {
var r, i, s = e, o = n || enyo.macroize.pattern, u = function(e, n) {
return r = enyo.getObject(n, !1, t), r === undefined || r === null ? "{$" + n + "}" : (i = !0, r);
}, a = 0;
do {
i = !1, s = s.replace(o, u);
if (++a >= 20) throw "enyo.macroize: recursion too deep";
} while (i);
return s;
}, enyo.quickMacroize = function(e, t, n) {
var r, i, s = e, o = n || enyo.macroize.pattern, u = function(e, n) {
return n in t ? r = t[n] : r = enyo.getObject(n, !1, t), r === undefined || r === null ? "{$" + n + "}" : r;
};
return s = s.replace(o, u), s;
}, enyo.macroize.pattern = /\{\$([^{}]*)\}/g;
// Oop.js
enyo.kind = function(e) {
enyo._kindCtors = {};
var t = e.name || "";
delete e.name;
var n = "kind" in e, r = e.kind;
delete e.kind;
var i = enyo.constructorForKind(r), s = i && i.prototype || null;
if (n && r === undefined || i === undefined) {
var o = r === undefined ? "undefined kind" : "unknown kind (" + r + ")";
throw "enyo.kind: Attempt to subclass an " + o + ". Check dependencies for [" + (t || "<unnamed>") + "].";
}
var u = enyo.kind.makeCtor();
return e.hasOwnProperty("constructor") && (e._constructor = e.constructor, delete e.constructor), enyo.setPrototype(u, s ? enyo.delegate(s) : {}), enyo.mixin(u.prototype, e), u.prototype.kindName = t, u.prototype.base = i, u.prototype.ctor = u, enyo.forEach(enyo.kind.features, function(t) {
t(u, e);
}), enyo.setObject(t, u), u;
}, enyo.singleton = function(e, t) {
var n = e.name;
delete e.name;
var r = enyo.kind(e);
enyo.setObject(n, new r, t);
}, enyo.kind.makeCtor = function() {
return function() {
if (!(this instanceof arguments.callee)) throw "enyo.kind: constructor called directly, not using 'new'";
var e;
this._constructor && (e = this._constructor.apply(this, arguments)), this.constructed && this.constructed.apply(this, arguments);
if (e) return e;
};
}, enyo.kind.defaultNamespace = "enyo", enyo.kind.features = [], enyo.kind.features.push(function(e, t) {
var n = e.prototype;
n.inherited || (n.inherited = enyo.kind.inherited);
if (n.base) for (var r in t) {
var i = t[r];
enyo.isFunction(i) && (i._inherited = n.base.prototype[r] || enyo.nop, i.nom = n.kindName + "." + r + "()");
}
}), enyo.kind.inherited = function(e, t) {
return e.callee._inherited.apply(this, t || e);
}, enyo.kind.features.push(function(e, t) {
enyo.mixin(e, enyo.kind.statics), t.statics && (enyo.mixin(e, t.statics), delete e.prototype.statics);
var n = e.prototype.base;
while (n) n.subclass(e, t), n = n.prototype.base;
}), enyo.kind.statics = {
subclass: function(e, t) {},
extend: function(e) {
enyo.mixin(this.prototype, e);
var t = this;
enyo.forEach(enyo.kind.features, function(n) {
n(t, e);
});
}
}, enyo._kindCtors = {}, enyo.constructorForKind = function(e) {
if (e === null || enyo.isFunction(e)) return e;
if (e) {
var t = enyo._kindCtors[e];
return t ? t : enyo._kindCtors[e] = enyo.Theme[e] || enyo[e] || enyo.getObject(e, !1, enyo) || window[e] || enyo.getObject(e);
}
return enyo.defaultCtor;
}, enyo.Theme = {}, enyo.registerTheme = function(e) {
enyo.mixin(enyo.Theme, e);
};
// Object.js
enyo.kind({
name: "enyo.Object",
kind: null,
constructor: function() {
enyo._objectCount++;
},
setPropertyValue: function(e, t, n) {
if (this[n]) {
var r = this[e];
this[e] = t, this[n](r);
} else this[e] = t;
},
_setProperty: function(e, t, n) {
this.setPropertyValue(e, t, this.getProperty(e) !== t && n);
},
destroyObject: function(e) {
this[e] && this[e].destroy && this[e].destroy(), this[e] = null;
},
getProperty: function(e) {
var t = "get" + enyo.cap(e);
return this[t] ? this[t]() : this[e];
},
setProperty: function(e, t) {
var n = "set" + enyo.cap(e);
this[n] ? this[n](t) : this._setProperty(e, t, e + "Changed");
},
log: function() {
var e = arguments.callee.caller, t = ((e ? e.nom : "") || "(instance method)") + ":";
enyo.logging.log("log", [ t ].concat(enyo.cloneArray(arguments)));
},
warn: function() {
this._log("warn", arguments);
},
error: function() {
this._log("error", arguments);
},
_log: function(e, t) {
if (enyo.logging.shouldLog(e)) try {
throw new Error;
} catch (n) {
enyo.logging._log(e, [ t.callee.caller.nom + ": " ].concat(enyo.cloneArray(t))), enyo.log(n.stack);
}
}
}), enyo._objectCount = 0, enyo.Object.subclass = function(e, t) {
this.publish(e, t);
}, enyo.Object.publish = function(e, t) {
var n = t.published;
if (n) {
var r = e.prototype;
for (var i in n) enyo.Object.addGetterSetter(i, n[i], r);
}
}, enyo.Object.addGetterSetter = function(e, t, n) {
var r = e;
n[r] = t;
var i = enyo.cap(r), s = "get" + i;
n[s] || (n[s] = function() {
return this[r];
});
var o = "set" + i, u = r + "Changed";
n[o] || (n[o] = function(e) {
this._setProperty(r, e, u);
});
};
// Component.js
enyo.kind({
name: "enyo.Component",
kind: enyo.Object,
published: {
name: "",
id: "",
owner: null
},
statics: {
_kindPrefixi: {},
_unnamedKindNumber: 0
},
defaultKind: "Component",
handlers: {},
toString: function() {
return this.kindName;
},
constructor: function() {
this._componentNameMap = {}, this.$ = {}, this.inherited(arguments);
},
constructed: function(e) {
this.importProps(e), this.create();
},
importProps: function(e) {
if (e) for (var t in e) this[t] = e[t];
this.handlers = enyo.mixin(enyo.clone(this.kindHandlers), this.handlers);
},
create: function() {
this.ownerChanged(), this.initComponents();
},
initComponents: function() {
this.createChrome(this.kindComponents), this.createClientComponents(this.components);
},
createChrome: function(e) {
this.createComponents(e, {
isChrome: !0
});
},
createClientComponents: function(e) {
this.createComponents(e, {
owner: this.getInstanceOwner()
});
},
getInstanceOwner: function() {
return !this.owner || this.owner.notInstanceOwner ? this : this.owner;
},
destroy: function() {
this.destroyComponents(), this.setOwner(null), this.destroyed = !0;
},
destroyComponents: function() {
enyo.forEach(this.getComponents(), function(e) {
e.destroyed || e.destroy();
});
},
makeId: function() {
var e = "_", t = this.owner && this.owner.getId(), n = this.name || "@@" + ++enyo.Component._unnamedKindNumber;
return (t ? t + e : "") + n;
},
ownerChanged: function(e) {
e && e.removeComponent(this), this.owner && this.owner.addComponent(this), this.id || (this.id = this.makeId());
},
nameComponent: function(e) {
var t = enyo.Component.prefixFromKindName(e.kindName), n, r = this._componentNameMap[t] || 0;
do n = t + (++r > 1 ? String(r) : ""); while (this.$[n]);
return this._componentNameMap[t] = Number(r), e.name = n;
},
addComponent: function(e) {
var t = e.getName();
t || (t = this.nameComponent(e)), this.$[t] && this.warn('Duplicate component name "' + t + '" in owner "' + this.id + '" violates ' + "unique-name-under-owner rule, replacing existing component in the hash and continuing, " + "but this is an error condition and should be fixed."), this.$[t] = e;
},
removeComponent: function(e) {
delete this.$[e.getName()];
},
getComponents: function() {
var e = [];
for (var t in this.$) e.push(this.$[t]);
return e;
},
adjustComponentProps: function(e) {
this.defaultProps && enyo.mixin(e, this.defaultProps), e.kind = e.kind || e.isa || this.defaultKind, e.owner = e.owner || this;
},
_createComponent: function(e, t) {
if (!e.kind && "kind" in e) throw "enyo.create: Attempt to create a null kind. Check dependencies for [" + e.name + "].";
var n = enyo.mixin(enyo.clone(t), e);
return this.adjustComponentProps(n), enyo.Component.create(n);
},
createComponent: function(e, t) {
return this._createComponent(e, t);
},
createComponents: function(e, t) {
if (e) {
var n = [];
for (var r = 0, i; i = e[r]; r++) n.push(this._createComponent(i, t));
return n;
}
},
getBubbleTarget: function() {
return this.owner;
},
bubble: function(e, t, n) {
var r = t || {};
return "originator" in r || (r.originator = n || this), this.dispatchBubble(e, r, n);
},
bubbleUp: function(e, t, n) {
var r = this.getBubbleTarget();
return r ? r.dispatchBubble(e, t, this) : !1;
},
dispatchEvent: function(e, t, n) {
this.decorateEvent(e, t, n);
if (this.handlers[e] && this.dispatch(this.handlers[e], t, n)) return !0;
if (this[e]) return this.bubbleDelegation(this.owner, this[e], e, t, this);
},
dispatchBubble: function(e, t, n) {
return this.dispatchEvent(e, t, n) ? !0 : this.bubbleUp(e, t, n);
},
decorateEvent: function(e, t, n) {},
bubbleDelegation: function(e, t, n, r, i) {
var s = this.getBubbleTarget();
if (s) return s.delegateEvent(e, t, n, r, i);
},
delegateEvent: function(e, t, n, r, i) {
return this.decorateEvent(n, r, i), e == this ? this.dispatch(t, r, i) : this.bubbleDelegation(e, t, n, r, i);
},
dispatch: function(e, t, n) {
var r = e && this[e];
if (r) return r.call(this, n || this, t);
},
waterfall: function(e, t, n) {
if (this.dispatchEvent(e, t, n)) return !0;
this.waterfallDown(e, t, n || this);
},
waterfallDown: function(e, t, n) {
for (var r in this.$) this.$[r].waterfall(e, t, n);
}
}), enyo.defaultCtor = enyo.Component, enyo.create = enyo.Component.create = function(e) {
if (!e.kind && "kind" in e) throw "enyo.create: Attempt to create a null kind. Check dependencies for [" + (e.name || "") + "].";
var t = e.kind || e.isa || enyo.defaultCtor, n = enyo.constructorForKind(t);
return n || (enyo.error('no constructor found for kind "' + t + '"'), n = enyo.Component), new n(e);
}, enyo.Component.subclass = function(e, t) {
var n = e.prototype;
t.components && (n.kindComponents = t.components, delete n.components);
if (t.handlers) {
var r = n.kindHandlers;
n.kindHandlers = enyo.mixin(enyo.clone(r), n.handlers), n.handlers = null;
}
t.events && this.publishEvents(e, t);
}, enyo.Component.publishEvents = function(e, t) {
var n = t.events;
if (n) {
var r = e.prototype;
for (var i in n) this.addEvent(i, n[i], r);
}
}, enyo.Component.addEvent = function(e, t, n) {
var r, i;
enyo.isString(t) ? (e.slice(0, 2) != "on" && (enyo.warn("enyo.Component.addEvent: event names must start with 'on'. " + n.kindName + " event '" + e + "' was auto-corrected to 'on" + e + "'."), e = "on" + e), r = t, i = "do" + enyo.cap(e.slice(2))) : (r = t.value, i = t.caller), n[e] = r, n[i] || (n[i] = function(t) {
return this.bubble(e, t);
});
}, enyo.Component.prefixFromKindName = function(e) {
var t = enyo.Component._kindPrefixi[e];
if (!t) {
var n = e.lastIndexOf(".");
t = n >= 0 ? e.slice(n + 1) : e, t = t.charAt(0).toLowerCase() + t.slice(1), enyo.Component._kindPrefixi[e] = t;
}
return t;
};
// UiComponent.js
enyo.kind({
name: "enyo.UiComponent",
kind: enyo.Component,
published: {
container: null,
parent: null,
controlParentName: "client",
layoutKind: ""
},
handlers: {
onresize: "resizeHandler"
},
addBefore: undefined,
statics: {
_resizeFlags: {
showingOnly: !0
}
},
create: function() {
this.controls = [], this.children = [], this.containerChanged(), this.inherited(arguments), this.layoutKindChanged();
},
destroy: function() {
this.destroyClientControls(), this.setContainer(null), this.inherited(arguments);
},
importProps: function(e) {
this.inherited(arguments), this.owner || (this.owner = enyo.master);
},
createComponents: function() {
var e = this.inherited(arguments);
return this.discoverControlParent(), e;
},
discoverControlParent: function() {
this.controlParent = this.$[this.controlParentName] || this.controlParent;
},
adjustComponentProps: function(e) {
e.container = e.container || this, this.inherited(arguments);
},
containerChanged: function(e) {
e && e.removeControl(this), this.container && this.container.addControl(this, this.addBefore);
},
parentChanged: function(e) {
e && e != this.parent && e.removeChild(this);
},
isDescendantOf: function(e) {
var t = this;
while (t && t != e) t = t.parent;
return e && t == e;
},
getControls: function() {
return this.controls;
},
getClientControls: function() {
var e = [];
for (var t = 0, n = this.controls, r; r = n[t]; t++) r.isChrome || e.push(r);
return e;
},
destroyClientControls: function() {
var e = this.getClientControls();
for (var t = 0, n; n = e[t]; t++) n.destroy();
},
addControl: function(e, t) {
this.controls.push(e), this.addChild(e, t);
},
removeControl: function(e) {
return e.setParent(null), enyo.remove(e, this.controls);
},
indexOfControl: function(e) {
return enyo.indexOf(e, this.controls);
},
indexOfClientControl: function(e) {
return enyo.indexOf(e, this.getClientControls());
},
indexInContainer: function() {
return this.container.indexOfControl(this);
},
clientIndexInContainer: function() {
return this.container.indexOfClientControl(this);
},
controlAtIndex: function(e) {
return this.controls[e];
},
addChild: function(e, t) {
if (this.controlParent) this.controlParent.addChild(e); else {
e.setParent(this);
if (t !== undefined) {
var n = t === null ? 0 : this.indexOfChild(t);
this.children.splice(n, 0, e);
} else this.children.push(e);
}
},
removeChild: function(e) {
return enyo.remove(e, this.children);
},
indexOfChild: function(e) {
return enyo.indexOf(e, this.children);
},
layoutKindChanged: function() {
this.layout && this.layout.destroy(), this.layout = enyo.createFromKind(this.layoutKind, this), this.generated && this.render();
},
flow: function() {
this.layout && this.layout.flow();
},
reflow: function() {
this.layout && this.layout.reflow();
},
resized: function() {
this.waterfall("onresize", enyo.UiComponent._resizeFlags), this.waterfall("onpostresize", enyo.UiComponent._resizeFlags);
},
resizeHandler: function() {
this.reflow();
},
waterfallDown: function(e, t, n) {
for (var r in this.$) this.$[r] instanceof enyo.UiComponent || this.$[r].waterfall(e, t, n);
for (var i = 0, s = this.children, o; o = s[i]; i++) (o.showing || !t || !t.showingOnly) && o.waterfall(e, t, n);
},
getBubbleTarget: function() {
return this.parent;
}
}), enyo.createFromKind = function(e, t) {
var n = e && enyo.constructorForKind(e);
if (n) return new n(t);
}, enyo.master = new enyo.Component({
name: "master",
notInstanceOwner: !0,
eventFlags: {
showingOnly: !0
},
getId: function() {
return "";
},
isDescendantOf: enyo.nop,
bubble: function(e, t, n) {
e == "onresize" ? (enyo.master.waterfallDown("onresize", this.eventFlags), enyo.master.waterfallDown("onpostresize", this.eventFlags)) : enyo.Signals.send(e, t);
}
});
// Layout.js
enyo.kind({
name: "enyo.Layout",
kind: null,
layoutClass: "",
constructor: function(e) {
this.container = e, e && e.addClass(this.layoutClass);
},
destroy: function() {
this.container && this.container.removeClass(this.layoutClass);
},
flow: function() {},
reflow: function() {}
});
// Signals.js
enyo.kind({
name: "enyo.Signals",
kind: enyo.Component,
create: function() {
this.inherited(arguments), enyo.Signals.addListener(this);
},
destroy: function() {
enyo.Signals.removeListener(this), this.inherited(arguments);
},
notify: function(e, t) {
this.dispatchEvent(e, t);
},
statics: {
listeners: [],
addListener: function(e) {
this.listeners.push(e);
},
removeListener: function(e) {
enyo.remove(e, this.listeners);
},
send: function(e, t) {
enyo.forEach(this.listeners, function(n) {
n.notify(e, t);
});
}
}
});
// Async.js
enyo.kind({
name: "enyo.Async",
kind: enyo.Object,
published: {
timeout: 0
},
failed: !1,
context: null,
constructor: function() {
this.responders = [], this.errorHandlers = [];
},
accumulate: function(e, t) {
var n = t.length < 2 ? t[0] : enyo.bind(t[0], t[1]);
e.push(n);
},
response: function() {
return this.accumulate(this.responders, arguments), this;
},
error: function() {
return this.accumulate(this.errorHandlers, arguments), this;
},
route: function(e, t) {
var n = enyo.bind(this, "respond");
e.response(function(e, t) {
n(t);
});
var r = enyo.bind(this, "fail");
e.error(function(e, t) {
r(t);
}), e.go(t);
},
handle: function(e, t) {
var n = t.shift();
if (n) if (n instanceof enyo.Async) this.route(n, e); else {
var r = enyo.call(this.context || this, n, [ this, e ]);
r = r !== undefined ? r : e, (this.failed ? this.fail : this.respond).call(this, r);
}
},
startTimer: function() {
this.startTime = enyo.now(), this.timeout && (this.timeoutJob = setTimeout(enyo.bind(this, "timeoutComplete"), this.timeout));
},
endTimer: function() {
this.timeoutJob && (this.endTime = enyo.now(), clearTimeout(this.timeoutJob), this.timeoutJob = null, this.latency = this.endTime - this.startTime);
},
timeoutComplete: function() {
this.timedout = !0, this.fail("timeout");
},
respond: function(e) {
this.failed = !1, this.endTimer(), this.handle(e, this.responders);
},
fail: function(e) {
this.failed = !0, this.endTimer(), this.handle(e, this.errorHandlers);
},
recover: function() {
this.failed = !1;
},
go: function(e) {
return enyo.asyncMethod(this, function() {
this.respond(e);
}), this;
}
});
// json.js
enyo.json = {
stringify: function(e, t, n) {
return JSON.stringify(e, t, n);
},
parse: function(e, t) {
return e ? JSON.parse(e, t) : null;
}
};
// cookie.js
enyo.getCookie = function(e) {
var t = document.cookie.match(new RegExp("(?:^|; )" + e + "=([^;]*)"));
return t ? decodeURIComponent(t[1]) : undefined;
}, enyo.setCookie = function(e, t, n) {
var r = e + "=" + encodeURIComponent(t), i = n || {}, s = i.expires;
if (typeof s == "number") {
var o = new Date;
o.setTime(o.getTime() + s * 24 * 60 * 60 * 1e3), s = o;
}
s && s.toUTCString && (i.expires = s.toUTCString());
var u, a;
for (u in i) r += "; " + u, a = i[u], a !== !0 && (r += "=" + a);
document.cookie = r;
};
// xhr.js
enyo.xhr = {
request: function(e) {
var t = this.getXMLHttpRequest(e), n = enyo.path.rewrite(this.simplifyFileURL(e.url)), r = e.method || "GET", i = !e.sync;
e.username ? t.open(r, n, i, e.username, e.password) : t.open(r, n, i), enyo.mixin(t, e.xhrFields), e.callback && this.makeReadyStateHandler(t, e.callback), e.headers = e.headers || {}, r !== "GET" && enyo.platform.ios && enyo.platform.ios >= 6 && e.headers["cache-control"] !== null && (e.headers["cache-control"] = e.headers["cache-control"] || "no-cache");
if (t.setRequestHeader) for (var s in e.headers) e.headers[s] && t.setRequestHeader(s, e.headers[s]);
return typeof t.overrideMimeType == "function" && e.mimeType && t.overrideMimeType(e.mimeType), t.send(e.body || null), !i && e.callback && t.onreadystatechange(t), t;
},
cancel: function(e) {
e.onload && (e.onload = null), e.onreadystatechange && (e.onreadystatechange = null), e.abort && e.abort();
},
makeReadyStateHandler: function(e, t) {
window.XDomainRequest && e instanceof XDomainRequest && (e.onload = function() {
var n;
typeof e.responseText == "string" && (n = e.responseText), t.apply(null, [ n, e ]);
}), e.onreadystatechange = function() {
if (e.readyState == 4) {
var n;
typeof e.responseText == "string" && (n = e.responseText), t.apply(null, [ n, e ]);
}
};
},
inOrigin: function(e) {
var t = document.createElement("a"), n = !1;
t.href = e;
if (t.protocol === ":" || t.protocol === window.location.protocol && t.hostname === window.location.hostname && t.port === (window.location.port || (window.location.protocol === "https:" ? "443" : "80"))) n = !0;
return n;
},
simplifyFileURL: function(e) {
var t = document.createElement("a"), n = !1;
return t.href = e, t.protocol === "file:" || t.protocol === ":" && window.location.protocol === "file:" ? t.protocol + "//" + t.host + t.pathname : t.protocol === ":" && window.location.protocol === "x-wmapp0:" ? window.location.protocol + "//" + window.location.pathname.split("/")[0] + "/" + t.host + t.pathname : e;
},
getXMLHttpRequest: function(e) {
try {
if (enyo.platform.ie < 10 && window.XDomainRequest && !e.headers && !this.inOrigin(e.url) && !/^file:\/\//.test(window.location.href)) return new XDomainRequest;
} catch (t) {}
try {
return new XMLHttpRequest;
} catch (t) {}
return null;
}
};
// formdata.js
(function(e) {
function i() {
this.fake = !0, this._fields = [], this.boundary = "--------------------------";
for (var e = 0; e < 24; e++) this.boundary += Math.floor(Math.random() * 10).toString(16);
}
function s(e, t) {
this.name = t.name, this.type = t.type || "application/octet-stream";
if (!enyo.isArray(e)) throw new Error("enyo.Blob only handles Arrays of Strings");
if (e.length > 0 && typeof e[0] != "string") throw new Error("enyo.Blob only handles Arrays of Strings");
this._bufs = e;
}
if (e.FormData) try {
var t = new e.FormData, n = new e.Blob;
enyo.FormData = e.FormData, enyo.Blob = e.Blob;
return;
} catch (r) {}
i.prototype.getContentType = function() {
return "multipart/form-data; boundary=" + this.boundary;
}, i.prototype.append = function(e, t, n) {
this._fields.push([ e, t, n ]);
}, i.prototype.toString = function() {
var e = this.boundary, t = "";
return enyo.forEach(this._fields, function(n) {
t += "--" + e + "\r\n";
if (n[2] || n[1].name) {
var r = n[1], i = n[2] || r.name;
t += 'Content-Disposition: form-data; name="' + n[0] + '"; filename="' + i + '"\r\n', t += "Content-Type: " + r.type + "\r\n\r\n", t += r.getAsBinary() + "\r\n";
} else t += 'Content-Disposition: form-data; name="' + n[0] + '";\r\n\r\n', t += n[1] + "\r\n";
}), t += "--" + e + "--", t;
}, enyo.FormData = i, s.prototype.getAsBinary = function() {
var e = "", t = e.concat.apply(e, this._bufs);
return t;
}, enyo.Blob = s;
})(window);
// AjaxProperties.js
enyo.AjaxProperties = {
cacheBust: !0,
url: "",
method: "GET",
handleAs: "json",
contentType: "application/x-www-form-urlencoded",
sync: !1,
headers: null,
postBody: "",
username: "",
password: "",
xhrFields: null,
mimeType: null
};
// Ajax.js
enyo.kind({
name: "enyo.Ajax",
kind: enyo.Async,
published: enyo.AjaxProperties,
constructor: function(e) {
enyo.mixin(this, e), this.inherited(arguments);
},
go: function(e) {
return this.startTimer(), this.request(e), this;
},
request: function(e) {
var t = this.url.split("?"), n = t.shift() || "", r = t.length ? t.join("?").split("&") : [], i = null;
enyo.isString(e) ? i = e : e && (i = enyo.Ajax.objectToQuery(e)), i && (r.push(i), i = null), this.cacheBust && r.push(Math.random());
var s = r.length ? [ n, r.join("&") ].join("?") : n, o = {}, u;
this.method != "GET" && (u = this.postBody, this.method === "POST" && u instanceof enyo.FormData ? u.fake && (o["Content-Type"] = u.getContentType(), u = u.toString()) : (o["Content-Type"] = this.contentType, u instanceof Object && (this.contentType === "application/json" ? u = JSON.stringify(u) : this.contentType === "application/x-www-form-urlencoded" ? u = enyo.Ajax.objectToQuery(u) : u = u.toString()))), enyo.mixin(o, this.headers), enyo.keys(o).length === 0 && (o = undefined);
try {
this.xhr = enyo.xhr.request({
url: s,
method: this.method,
callback: enyo.bind(this, "receive"),
body: u,
headers: o,
sync: window.PalmSystem ? !1 : this.sync,
username: this.username,
password: this.password,
xhrFields: this.xhrFields,
mimeType: this.mimeType
});
} catch (a) {
this.fail(a);
}
},
receive: function(e, t) {
if (!this.failed && !this.destroyed) {
var n;
typeof t.responseText == "string" ? n = t.responseText : n = t.responseBody, this.xhrResponse = {
status: t.status,
headers: enyo.Ajax.parseResponseHeaders(t),
body: n
}, this.isFailure(t) ? this.fail(t.status) : this.respond(this.xhrToResponse(t));
}
},
fail: function(e) {
this.xhr && (enyo.xhr.cancel(this.xhr), this.xhr = null), this.inherited(arguments);
},
xhrToResponse: function(e) {
if (e) return this[(this.handleAs || "text") + "Handler"](e);
},
isFailure: function(e) {
try {
var t = "";
return typeof e.responseText == "string" && (t = e.responseText), e.status === 0 && t === "" ? !0 : e.status !== 0 && (e.status < 200 || e.status >= 300);
} catch (n) {
return !0;
}
},
xmlHandler: function(e) {
return e.responseXML;
},
textHandler: function(e) {
return e.responseText;
},
jsonHandler: function(e) {
var t = e.responseText;
try {
return t && enyo.json.parse(t);
} catch (n) {
return enyo.warn("Ajax request set to handleAs JSON but data was not in JSON format"), t;
}
},
statics: {
objectToQuery: function(e) {
var t = encodeURIComponent, n = [], r = {};
for (var i in e) {
var s = e[i];
if (s != r[i]) {
var o = t(i) + "=";
if (enyo.isArray(s)) for (var u = 0; u < s.length; u++) n.push(o + t(s[u])); else n.push(o + t(s));
}
}
return n.join("&");
},
parseResponseHeaders: function(e) {
var t = {}, n = [];
e.getAllResponseHeaders && (n = e.getAllResponseHeaders().split(/\r?\n/));
for (var r = 0; r < n.length; r++) {
var i = n[r], s = i.indexOf(": ");
if (s > 0) {
var o = i.substring(0, s).toLowerCase(), u = i.substring(s + 2);
t[o] = u;
}
}
return t;
}
}
});
// Jsonp.js
enyo.kind({
name: "enyo.JsonpRequest",
kind: enyo.Async,
published: {
url: "",
charset: null,
callbackName: "callback",
cacheBust: !0
},
statics: {
nextCallbackID: 0
},
addScriptElement: function() {
var e = document.createElement("script");
e.src = this.src, e.async = "async", this.charset && (e.charset = this.charset), e.onerror = enyo.bind(this, function() {
this.fail(400);
});
var t = document.getElementsByTagName("script")[0];
t.parentNode.insertBefore(e, t), this.scriptTag = e;
},
removeScriptElement: function() {
var e = this.scriptTag;
this.scriptTag = null, e.onerror = null, e.parentNode && e.parentNode.removeChild(e);
},
constructor: function(e) {
enyo.mixin(this, e), this.inherited(arguments);
},
go: function(e) {
return this.startTimer(), this.jsonp(e), this;
},
jsonp: function(e) {
var t = "enyo_jsonp_callback_" + enyo.JsonpRequest.nextCallbackID++;
this.src = this.buildUrl(e, t), this.addScriptElement(), window[t] = enyo.bind(this, this.respond);
var n = enyo.bind(this, function() {
this.removeScriptElement(), window[t] = null;
});
this.response(n), this.error(n);
},
buildUrl: function(e, t) {
var n = this.url.split("?"), r = n.shift() || "", i = n.join("?").split("&"), s = this.bodyArgsFromParams(e, t);
return i.push(s), this.cacheBust && i.push(Math.random()), [ r, i.join("&") ].join("?");
},
bodyArgsFromParams: function(e, t) {
if (enyo.isString(e)) return e.replace("=?", "=" + t);
var n = enyo.mixin({}, e);
return n[this.callbackName] = t, enyo.Ajax.objectToQuery(n);
}
});
// WebService.js
enyo.kind({
name: "enyo._AjaxComponent",
kind: enyo.Component,
published: enyo.AjaxProperties
}), enyo.kind({
name: "enyo.WebService",
kind: enyo._AjaxComponent,
published: {
jsonp: !1,
callbackName: "callback",
charset: null,
timeout: 0
},
events: {
onResponse: "",
onError: ""
},
constructor: function(e) {
this.inherited(arguments);
},
send: function(e, t) {
return this.jsonp ? this.sendJsonp(e, t) : this.sendAjax(e, t);
},
sendJsonp: function(e, t) {
var n = new enyo.JsonpRequest;
for (var r in {
url: 1,
callbackName: 1,
charset: 1,
timeout: 1
}) n[r] = this[r];
return enyo.mixin(n, t), this.sendAsync(n, e);
},
sendAjax: function(e, t) {
var n = new enyo.Ajax(t);
for (var r in enyo.AjaxProperties) n[r] = this[r];
return n.timeout = this.timeout, enyo.mixin(n, t), this.sendAsync(n, e);
},
sendAsync: function(e, t) {
return e.go(t).response(this, "response").error(this, "error");
},
response: function(e, t) {
this.doResponse({
ajax: e,
data: t
});
},
error: function(e, t) {
this.doError({
ajax: e,
data: t
});
}
});
// dom.js
enyo.requiresWindow = function(e) {
e();
}, enyo.dom = {
byId: function(e, t) {
return typeof e == "string" ? (t || document).getElementById(e) : e;
},
escape: function(e) {
return e !== null ? String(e).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") : "";
},
getBounds: function(e) {
return e ? {
left: e.offsetLeft,
top: e.offsetTop,
width: e.offsetWidth,
height: e.offsetHeight
} : null;
},
getComputedStyle: function(e) {
return window.getComputedStyle && e && window.getComputedStyle(e, null);
},
getComputedStyleValue: function(e, t, n) {
var r = n || this.getComputedStyle(e);
return r ? r.getPropertyValue(t) : null;
},
getFirstElementByTagName: function(e) {
var t = document.getElementsByTagName(e);
return t && t[0];
},
applyBodyFit: function() {
var e = this.getFirstElementByTagName("html");
e && (e.className += " enyo-document-fit");
var t = this.getFirstElementByTagName("body");
t && (t.className += " enyo-body-fit"), enyo.bodyIsFitting = !0;
},
getWindowWidth: function() {
return window.innerWidth ? window.innerWidth : document.body && document.body.offsetWidth ? document.body.offsetWidth : document.compatMode == "CSS1Compat" && document.documentElement && document.documentElement.offsetWidth ? document.documentElement.offsetWidth : 320;
},
getWindowHeight: function() {
return window.innerHeight ? window.innerHeight : document.body && document.body.offsetHeight ? document.body.offsetHeight : document.compatMode == "CSS1Compat" && document.documentElement && document.documentElement.offsetHeight ? document.documentElement.offsetHeight : 480;
},
_ieCssToPixelValue: function(e, t) {
var n = t, r = e.style, i = r.left, s = e.runtimeStyle && e.runtimeStyle.left;
return s && (e.runtimeStyle.left = e.currentStyle.left), r.left = n, n = r.pixelLeft, r.left = i, s && (r.runtimeStyle.left = s), n;
},
_pxMatch: /px/i,
getComputedBoxValue: function(e, t, n, r) {
var i = r || this.getComputedStyle(e);
if (i) return parseInt(i.getPropertyValue(t + "-" + n), 0);
if (e && e.currentStyle) {
var s = e.currentStyle[t + enyo.cap(n)];
return s.match(this._pxMatch) || (s = this._ieCssToPixelValue(e, s)), parseInt(s, 0);
}
return 0;
},
calcBoxExtents: function(e, t) {
var n = this.getComputedStyle(e);
return {
top: this.getComputedBoxValue(e, t, "top", n),
right: this.getComputedBoxValue(e, t, "right", n),
bottom: this.getComputedBoxValue(e, t, "bottom", n),
left: this.getComputedBoxValue(e, t, "left", n)
};
},
calcPaddingExtents: function(e) {
return this.calcBoxExtents(e, "padding");
},
calcMarginExtents: function(e) {
return this.calcBoxExtents(e, "margin");
},
calcNodePosition: function(e, t) {
var n = 0, r = 0, i = e, s = i.offsetWidth, o = i.offsetHeight, u = enyo.dom.getStyleTransformProp(), a = /translateX\((-?\d+)px\)/i, f = /translateY\((-?\d+)px\)/i, l = 0, c = 0, h = 0, p = 0;
t ? (h = t.offsetHeight, p = t.offsetWidth) : (h = document.body.parentNode.offsetHeight > this.getWindowHeight() ? this.getWindowHeight() - document.body.parentNode.scrollTop : document.body.parentNode.offsetHeight, p = document.body.parentNode.offsetWidth > this.getWindowWidth() ? this.getWindowWidth() - document.body.parentNode.scrollLeft : document.body.parentNode.offsetWidth);
if (i.offsetParent) do r += i.offsetLeft - (i.offsetParent ? i.offsetParent.scrollLeft : 0), u && a.test(i.style[u]) && (r += parseInt(i.style[u].replace(a, "$1"), 10)), n += i.offsetTop - (i.offsetParent ? i.offsetParent.scrollTop : 0), u && f.test(i.style[u]) && (n += parseInt(i.style[u].replace(f, "$1"), 10)), i !== e && (i.currentStyle ? (l = parseInt(i.currentStyle.borderLeftWidth, 10), c = parseInt(i.currentStyle.borderTopWidth, 10)) : window.getComputedStyle ? (l = parseInt(window.getComputedStyle(i, "").getPropertyValue("border-left-width"), 10), c = parseInt(window.getComputedStyle(i, "").getPropertyValue("border-top-width"), 10)) : (l = parseInt(i.style.borderLeftWidth, 10), c = parseInt(i.style.borderTopWidth, 10)), l && (r += l), c && (n += c)); while ((i = i.offsetParent) && i !== t);
return {
top: n,
left: r,
bottom: h - n - o,
right: p - r - s,
height: o,
width: s
};
},
setInnerHtml: function(e, t) {
enyo.execUnsafeLocalFunction(function() {
e.innerHTML = t;
});
}
};
// transform.js
(function() {
enyo.dom.calcCanAccelerate = function() {
if (enyo.platform.android <= 2) return !1;
var e = [ "perspective", "WebkitPerspective", "MozPerspective", "msPerspective", "OPerspective" ];
for (var t = 0, n; n = e[t]; t++) if (typeof document.body.style[n] != "undefined") return !0;
return !1;
};
var e = [ "transform", "-webkit-transform", "-moz-transform", "-ms-transform", "-o-transform" ], t = [ "transform", "webkitTransform", "MozTransform", "msTransform", "OTransform" ];
enyo.dom.getCssTransformProp = function() {
if (this._cssTransformProp) return this._cssTransformProp;
var n = enyo.indexOf(this.getStyleTransformProp(), t);
return this._cssTransformProp = e[n];
}, enyo.dom.getStyleTransformProp = function() {
if (this._styleTransformProp || !document.body) return this._styleTransformProp;
for (var e = 0, n; n = t[e]; e++) if (typeof document.body.style[n] != "undefined") return this._styleTransformProp = n;
}, enyo.dom.domTransformsToCss = function(e) {
var t, n, r = "";
for (t in e) n = e[t], n !== null && n !== undefined && n !== "" && (r += t + "(" + n + ") ");
return r;
}, enyo.dom.transformsToDom = function(e) {
var t = this.domTransformsToCss(e.domTransforms), n = e.hasNode() ? e.node.style : null, r = e.domStyles, i = this.getStyleTransformProp(), s = this.getCssTransformProp();
i && s && (r[s] = t, n ? n[i] = t : e.domStylesChanged());
}, enyo.dom.canTransform = function() {
return Boolean(this.getStyleTransformProp());
}, enyo.dom.canAccelerate = function() {
return this.accelerando !== undefined ? this.accelerando : document.body && (this.accelerando = this.calcCanAccelerate());
}, enyo.dom.transform = function(e, t) {
var n = e.domTransforms = e.domTransforms || {};
enyo.mixin(n, t), this.transformsToDom(e);
}, enyo.dom.transformValue = function(e, t, n) {
var r = e.domTransforms = e.domTransforms || {};
r[t] = n, this.transformsToDom(e);
}, enyo.dom.accelerate = function(e, t) {
var n = t == "auto" ? this.canAccelerate() : t;
this.transformValue(e, "translateZ", n ? 0 : null);
};
})();
// Control.js
enyo.kind({
name: "enyo.Control",
kind: enyo.UiComponent,
published: {
tag: "div",
attributes: null,
classes: "",
style: "",
content: "",
showing: !0,
allowHtml: !1,
src: "",
canGenerate: !0,
fit: !1,
isContainer: !1
},
handlers: {
ontap: "tap"
},
defaultKind: "Control",
controlClasses: "",
node: null,
generated: !1,
create: function() {
this.initStyles(), this.inherited(arguments), this.showingChanged(), this.addClass(this.kindClasses), this.addClass(this.classes), this.initProps([ "id", "content", "src" ]);
},
destroy: function() {
this.removeNodeFromDom(), enyo.Control.unregisterDomEvents(this.id), this.inherited(arguments);
},
importProps: function(e) {
this.inherited(arguments), this.attributes = enyo.mixin(enyo.clone(this.kindAttributes), this.attributes);
},
initProps: function(e) {
for (var t = 0, n, r; n = e[t]; t++) this[n] && (r = n + "Changed", this[r] && this[r]());
},
classesChanged: function(e) {
this.removeClass(e), this.addClass(this.classes);
},
addChild: function(e) {
e.addClass(this.controlClasses), this.inherited(arguments);
},
removeChild: function(e) {
this.inherited(arguments), e.removeClass(this.controlClasses);
},
strictlyInternalEvents: {
onenter: 1,
onleave: 1
},
dispatchEvent: function(e, t, n) {
return this.strictlyInternalEvents[e] && this.isInternalEvent(t) ? !0 : this.inherited(arguments);
},
isInternalEvent: function(e) {
var t = enyo.dispatcher.findDispatchTarget(e.relatedTarget);
return t && t.isDescendantOf(this);
},
hasNode: function() {
return this.generated && (this.node || this.findNodeById());
},
addContent: function(e) {
this.setContent(this.content + e);
},
getAttribute: function(e) {
return this.hasNode() ? this.node.getAttribute(e) : this.attributes[e];
},
setAttribute: function(e, t) {
this.attributes[e] = t, this.hasNode() && this.attributeToNode(e, t), this.invalidateTags();
},
getNodeProperty: function(e, t) {
return this.hasNode() ? this.node[e] : t;
},
setNodeProperty: function(e, t) {
this.hasNode() && (this.node[e] = t);
},
setClassAttribute: function(e) {
this.setAttribute("class", e);
},
getClassAttribute: function() {
return this.attributes["class"] || "";
},
hasClass: function(e) {
return e && (" " + this.getClassAttribute() + " ").indexOf(" " + e + " ") >= 0;
},
addClass: function(e) {
if (e && !this.hasClass(e)) {
var t = this.getClassAttribute();
this.setClassAttribute(t + (t ? " " : "") + e);
}
},
removeClass: function(e) {
if (e && this.hasClass(e)) {
var t = this.getClassAttribute();
t = (" " + t + " ").replace(" " + e + " ", " ").slice(1, -1), this.setClassAttribute(t);
}
},
addRemoveClass: function(e, t) {
this[t ? "addClass" : "removeClass"](e);
},
initStyles: function() {
this.domStyles = this.domStyles || {}, enyo.Control.cssTextToDomStyles(this.kindStyle, this.domStyles), this.domCssText = enyo.Control.domStylesToCssText(this.domStyles);
},
styleChanged: function() {
this.invalidateTags(), this.renderStyles();
},
applyStyle: function(e, t) {
this.domStyles[e] = t, this.domStylesChanged();
},
addStyles: function(e) {
enyo.Control.cssTextToDomStyles(e, this.domStyles), this.domStylesChanged();
},
getComputedStyleValue: function(e, t) {
return this.hasNode() ? enyo.dom.getComputedStyleValue(this.node, e) : t;
},
domStylesChanged: function() {
this.domCssText = enyo.Control.domStylesToCssText(this.domStyles), this.invalidateTags(), this.renderStyles();
},
stylesToNode: function() {
this.node.style.cssText = this.style + (this.style[this.style.length - 1] == ";" ? " " : "; ") + this.domCssText;
},
setupBodyFitting: function() {
enyo.dom.applyBodyFit(), this.addClass("enyo-fit enyo-clip");
},
setupOverflowScrolling: function() {
if (enyo.platform.android || enyo.platform.androidChrome || enyo.platform.blackberry) return;
document.getElementsByTagName("body")[0].className += " webkitOverflowScrolling";
},
render: function() {
if (this.parent) {
this.parent.beforeChildRender(this);
if (!this.parent.generated) return this;
}
return this.hasNode() || this.renderNode(), this.hasNode() && (this.renderDom(), this.generated && this.rendered()), this;
},
renderInto: function(e) {
this.teardownRender();
var t = enyo.dom.byId(e);
return t == document.body ? this.setupBodyFitting() : this.fit && this.addClass("enyo-fit enyo-clip"), this.addClass("enyo-no-touch-action"), this.setupOverflowScrolling(), enyo.dom.setInnerHtml(t, this.generateHtml()), this.generated && this.rendered(), this;
},
write: function() {
return this.fit && this.setupBodyFitting(), this.addClass("enyo-no-touch-action"), this.setupOverflowScrolling(), document.write(this.generateHtml()), this.generated && this.rendered(), this;
},
rendered: function() {
this.reflow();
for (var e = 0, t; t = this.children[e]; e++) t.generated && t.rendered();
},
show: function() {
this.setShowing(!0);
},
hide: function() {
this.setShowing(!1);
},
getBounds: function() {
var e = this.node || this.hasNode(), t = enyo.dom.getBounds(e);
return t || {
left: undefined,
top: undefined,
width: undefined,
height: undefined
};
},
setBounds: function(e, t) {
var n = this.domStyles, r = t || "px", i = [ "width", "height", "left", "top", "right", "bottom" ];
for (var s = 0, o, u; u = i[s]; s++) {
o = e[u];
if (o || o === 0) n[u] = o + (enyo.isString(o) ? "" : r);
}
this.domStylesChanged();
},
findNodeById: function() {
return this.id && (this.node = enyo.dom.byId(this.id));
},
idChanged: function(e) {
e && enyo.Control.unregisterDomEvents(e), this.setAttribute("id", this.id), this.id && enyo.Control.registerDomEvents(this.id, this);
},
contentChanged: function() {
this.hasNode() && this.renderContent();
},
getSrc: function() {
return this.getAttribute("src");
},
srcChanged: function() {
this.setAttribute("src", enyo.path.rewrite(this.src));
},
attributesChanged: function() {
this.invalidateTags(), this.renderAttributes();
},
generateHtml: function() {
if (this.canGenerate === !1) return "";
var e = this.generateInnerHtml(), t = this.generateOuterHtml(e);
return this.generated = !0, t;
},
generateInnerHtml: function() {
return this.flow(), this.children.length ? this.generateChildHtml() : this.allowHtml ? this.content : enyo.Control.escapeHtml(this.content);
},
generateChildHtml: function() {
var e = "";
for (var t = 0, n; n = this.children[t]; t++) {
var r = n.generateHtml();
e += r;
}
return e;
},
generateOuterHtml: function(e) {
return this.tag ? (this.tagsValid || this.prepareTags(), this._openTag + e + this._closeTag) : e;
},
invalidateTags: function() {
this.tagsValid = !1;
},
prepareTags: function() {
var e = this.domCssText + this.style;
this._openTag = "<" + this.tag + (e ? ' style="' + e + '"' : "") + enyo.Control.attributesToHtml(this.attributes), enyo.Control.selfClosing[this.tag] ? (this._openTag += "/>", this._closeTag = "") : (this._openTag += ">", this._closeTag = "</" + this.tag + ">"), this.tagsValid = !0;
},
attributeToNode: function(e, t) {
t === null || t === !1 || t === "" ? this.node.removeAttribute(e) : this.node.setAttribute(e, t);
},
attributesToNode: function() {
for (var e in this.attributes) this.attributeToNode(e, this.attributes[e]);
},
getParentNode: function() {
return this.parentNode || this.parent && (this.parent.hasNode() || this.parent.getParentNode());
},
addNodeToParent: function() {
if (this.node) {
var e = this.getParentNode();
e && (this.addBefore !== undefined ? this.insertNodeInParent(e, this.addBefore && this.addBefore.hasNode()) : this.appendNodeToParent(e));
}
},
appendNodeToParent: function(e) {
e.appendChild(this.node);
},
insertNodeInParent: function(e, t) {
e.insertBefore(this.node, t || e.firstChild);
},
removeNodeFromDom: function() {
this.hasNode() && this.node.parentNode && this.node.parentNode.removeChild(this.node);
},
teardownRender: function() {
this.generated && this.teardownChildren(), this.node = null, this.generated = !1;
},
teardownChildren: function() {
for (var e = 0, t; t = this.children[e]; e++) t.teardownRender();
},
renderNode: function() {
this.teardownRender(), this.node = document.createElement(this.tag), this.addNodeToParent(), this.generated = !0;
},
renderDom: function() {
this.renderAttributes(), this.renderStyles(), this.renderContent();
},
renderContent: function() {
this.generated && this.teardownChildren(), enyo.dom.setInnerHtml(this.node, this.generateInnerHtml());
},
renderStyles: function() {
this.hasNode() && this.stylesToNode();
},
renderAttributes: function() {
this.hasNode() && this.attributesToNode();
},
beforeChildRender: function() {
this.generated && this.flow();
},
syncDisplayToShowing: function() {
var e = this.domStyles;
this.showing ? e.display == "none" && this.applyStyle("display", this._displayStyle || "") : (this._displayStyle = e.display == "none" ? "" : e.display, this.applyStyle("display", "none"));
},
showingChanged: function() {
this.syncDisplayToShowing();
},
getShowing: function() {
return this.showing = this.domStyles.display != "none";
},
fitChanged: function(e) {
this.parent.reflow();
},
statics: {
escapeHtml: function(e) {
return e != null ? String(e).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">") : "";
},
registerDomEvents: function(e, t) {
enyo.$[e] = t;
},
unregisterDomEvents: function(e) {
enyo.$[e] = null;
},
selfClosing: {
img: 1,
hr: 1,
br: 1,
area: 1,
base: 1,
basefont: 1,
input: 1,
link: 1,
meta: 1,
command: 1,
embed: 1,
keygen: 1,
wbr: 1,
param: 1,
source: 1,
track: 1,
col: 1
},
cssTextToDomStyles: function(e, t) {
if (e) {
var n = e.replace(/; /g, ";").split(";");
for (var r = 0, i, s, o, u; u = n[r]; r++) i = u.split(":"), s = i.shift(), o = i.join(":"), t[s] = o;
}
},
domStylesToCssText: function(e) {
var t, n, r = "";
for (t in e) n = e[t], n !== null && n !== undefined && n !== "" && (r += t + ":" + n + ";");
return r;
},
stylesToHtml: function(e) {
var t = enyo.Control.domStylesToCssText(e);
return t ? ' style="' + t + '"' : "";
},
escapeAttribute: function(e) {
return enyo.isString(e) ? String(e).replace(/&/g, "&").replace(/\"/g, """) : e;
},
attributesToHtml: function(e) {
var t, n, r = "";
for (t in e) n = e[t], n !== null && n !== !1 && n !== "" && (r += " " + t + '="' + enyo.Control.escapeAttribute(n) + '"');
return r;
}
}
}), enyo.defaultCtor = enyo.Control, enyo.Control.subclass = function(e, t) {
var n = e.prototype;
if (n.classes) {
var r = n.kindClasses;
n.kindClasses = (r ? r + " " : "") + n.classes, n.classes = "";
}
if (n.style) {
var i = n.kindStyle;
n.kindStyle = (i ? i + ";" : "") + n.style, n.style = "";
}
if (t.attributes) {
var s = n.kindAttributes;
n.kindAttributes = enyo.mixin(enyo.clone(s), n.attributes), n.attributes = null;
}
};
// platform.js
enyo.platform = {
touch: Boolean("ontouchstart" in window || window.navigator.msMaxTouchPoints),
gesture: Boolean("ongesturestart" in window || window.navigator.msMaxTouchPoints)
}, function() {
var e = navigator.userAgent, t = enyo.platform, n = [ {
platform: "androidChrome",
regex: /Android .* Chrome\/(\d+)[.\d]+/
}, {
platform: "android",
regex: /Android (\d+)/
}, {
platform: "android",
regex: /Silk\/1./,
forceVersion: 2,
extra: {
silk: 1
}
}, {
platform: "android",
regex: /Silk\/2./,
forceVersion: 4,
extra: {
silk: 2
}
}, {
platform: "windowsPhone",
regex: /Windows Phone (?:OS )?(\d+)[.\d]+/
}, {
platform: "ie",
regex: /MSIE (\d+)/
}, {
platform: "ios",
regex: /iP(?:hone|ad;(?: U;)? CPU) OS (\d+)/
}, {
platform: "webos",
regex: /(?:web|hpw)OS\/(\d+)/
}, {
platform: "safari",
regex: /Version\/(\d+)[.\d]+\s+Safari/
}, {
platform: "chrome",
regex: /Chrome\/(\d+)[.\d]+/
}, {
platform: "androidFirefox",
regex: /Android;.*Firefox\/(\d+)/
}, {
platform: "firefoxOS",
regex: /Mobile;.*Firefox\/(\d+)/
}, {
platform: "firefox",
regex: /Firefox\/(\d+)/
}, {
platform: "blackberry",
regex: /BB1\d;.*Version\/(\d+\.\d+)/
} ];
for (var r = 0, i, s, o; i = n[r]; r++) {
s = i.regex.exec(e);
if (s) {
i.forceVersion ? o = i.forceVersion : o = Number(s[1]), t[i.platform] = o, i.extra && enyo.mixin(t, i.extra);
break;
}
}
enyo.dumbConsole = Boolean(t.android || t.ios || t.webos);
}();
// animation.js
(function() {
var e = Math.round(1e3 / 60), t = [ "webkit", "moz", "ms", "o", "" ], n = "requestAnimationFrame", r = "cancel" + enyo.cap(n), i = function(t) {
return window.setTimeout(t, e);
}, s = function(e) {
return window.clearTimeout(e);
};
for (var o = 0, u = t.length, a, f, l; (a = t[o]) || o < u; o++) {
if (enyo.platform.ios >= 6) break;
f = a ? a + enyo.cap(r) : r, l = a ? a + enyo.cap(n) : n;
if (window[f]) {
s = window[f], i = window[l], a == "webkit" && s(i(enyo.nop));
break;
}
}
enyo.requestAnimationFrame = function(e, t) {
return i(e, t);
}, enyo.cancelRequestAnimationFrame = function(e) {
return s(e);
};
})(), enyo.easing = {
cubicIn: function(e) {
return Math.pow(e, 3);
},
cubicOut: function(e) {
return Math.pow(e - 1, 3) + 1;
},
expoOut: function(e) {
return e == 1 ? 1 : -1 * Math.pow(2, -10 * e) + 1;
},
quadInOut: function(e) {
return e *= 2, e < 1 ? Math.pow(e, 2) / 2 : -1 * (--e * (e - 2) - 1) / 2;
},
linear: function(e) {
return e;
}
}, enyo.easedLerp = function(e, t, n, r) {
var i = (enyo.now() - e) / t;
return r ? i >= 1 ? 0 : 1 - n(1 - i) : i >= 1 ? 1 : n(i);
};
// phonegap.js
(function() {
if (window.cordova || window.PhoneGap) {
var e = [ "deviceready", "pause", "resume", "online", "offline", "backbutton", "batterycritical", "batterylow", "batterystatus", "menubutton", "searchbutton", "startcallbutton", "endcallbutton", "volumedownbutton", "volumeupbutton" ];
for (var t = 0, n; n = e[t]; t++) document.addEventListener(n, enyo.bind(enyo.Signals, "send", "on" + n), !1);
}
})();
// dispatcher.js
enyo.$ = {}, enyo.dispatcher = {
events: [ "mousedown", "mouseup", "mouseover", "mouseout", "mousemove", "mousewheel", "click", "dblclick", "change", "keydown", "keyup", "keypress", "input" ],
windowEvents: [ "resize", "load", "unload", "message" ],
cssEvents: [ "webkitTransitionEnd", "transitionend" ],
features: [],
connect: function() {
var e = enyo.dispatcher, t, n;
for (t = 0; n = e.events[t]; t++) e.listen(document, n);
for (t = 0; n = e.cssEvents[t]; t++) e.listen(document, n);
for (t = 0; n = e.windowEvents[t]; t++) {
if (n === "unload" && typeof window.chrome == "object" && window.chrome.app) continue;
e.listen(window, n);
}
for (t = 0; n = e.cssEvents[t]; t++) e.listen(document, n);
},
listen: function(e, t, n) {
var r = enyo.dispatch;
e.addEventListener ? this.listen = function(e, t, n) {
e.addEventListener(t, n || r, !1);
} : this.listen = function(e, t, n) {
e.attachEvent("on" + t, function(e) {
return e.target = e.srcElement, e.preventDefault || (e.preventDefault = enyo.iePreventDefault), (n || r)(e);
});
}, this.listen(e, t, n);
},
dispatch: function(e) {
var t = this.findDispatchTarget(e.target) || this.findDefaultTarget(e);
e.dispatchTarget = t;
for (var n = 0, r; r = this.features[n]; n++) if (r.call(this, e) === !0) return;
t && !e.preventDispatch && this.dispatchBubble(e, t);
},
findDispatchTarget: function(e) {
var t, n = e;
try {
while (n) {
if (t = enyo.$[n.id]) {
t.eventNode = n;
break;
}
n = n.parentNode;
}
} catch (r) {
enyo.log(r, n);
}
return t;
},
findDefaultTarget: function(e) {
return enyo.master;
},
dispatchBubble: function(e, t) {
return t.bubble("on" + e.type, e, t);
}
}, enyo.iePreventDefault = function() {
try {
this.returnValue = !1;
} catch (e) {}
}, enyo.dispatch = function(e) {
return enyo.dispatcher.dispatch(e);
}, enyo.bubble = function(e) {
var t = e || window.event;
t && (t.target || (t.target = t.srcElement), enyo.dispatch(t));
}, enyo.bubbler = "enyo.bubble(arguments[0])", function() {
var e = function() {
enyo.bubble(arguments[0]);
};
enyo.makeBubble = function() {
var t = Array.prototype.slice.call(arguments, 0), n = t.shift();
typeof n == "object" && typeof n.hasNode == "function" && enyo.forEach(t, function(t) {
this.hasNode() && enyo.dispatcher.listen(this.node, t, e);
}, n);
};
}(), enyo.requiresWindow(enyo.dispatcher.connect), enyo.dispatcher.features.push(function(e) {
if ("click" === e.type && e.clientX === 0 && e.clientY === 0) {
var t = enyo.clone(e);
t.type = "tap", enyo.dispatch(t);
}
});
// preview.js
(function() {
var e = "previewDomEvent", t = {
feature: function(e) {
t.dispatch(e, e.dispatchTarget);
},
dispatch: function(t, n) {
var r = this.buildLineage(n);
for (var i = 0, s; s = r[i]; i++) if (s[e] && s[e](t) === !0) {
t.preventDispatch = !0;
return;
}
},
buildLineage: function(e) {
var t = [], n = e;
while (n) t.unshift(n), n = n.parent;
return t;
}
};
enyo.dispatcher.features.push(t.feature);
})();
// modal.js
enyo.dispatcher.features.push(function(e) {
var t = e.dispatchTarget, n = this.captureTarget && !this.noCaptureEvents[e.type], r = n && !(t && t.isDescendantOf && t.isDescendantOf(this.captureTarget));
if (r) {
var i = e.captureTarget = this.captureTarget, s = this.autoForwardEvents[e.type] || this.forwardEvents;
this.dispatchBubble(e, i), s || (e.preventDispatch = !0);
}
}), enyo.mixin(enyo.dispatcher, {
noCaptureEvents: {
load: 1,
unload: 1,
error: 1
},
autoForwardEvents: {
leave: 1,
resize: 1
},
captures: [],
capture: function(e, t) {
var n = {
target: e,
forward: t
};
this.captures.push(n), this.setCaptureInfo(n);
},
release: function() {
this.captures.pop(), this.setCaptureInfo(this.captures[this.captures.length - 1]);
},
setCaptureInfo: function(e) {
this.captureTarget = e && e.target, this.forwardEvents = e && e.forward;
}
});
// gesture.js
enyo.gesture = {
eventProps: [ "target", "relatedTarget", "clientX", "clientY", "pageX", "pageY", "screenX", "screenY", "altKey", "ctrlKey", "metaKey", "shiftKey", "detail", "identifier", "dispatchTarget", "which", "srcEvent" ],
makeEvent: function(e, t) {
var n = {
type: e
};
for (var r = 0, i; i = this.eventProps[r]; r++) n[i] = t[i];
n.srcEvent = n.srcEvent || t, n.preventDefault = this.preventDefault, n.disablePrevention = this.disablePrevention;
if (enyo.platform.ie < 10) {
enyo.platform.ie == 8 && n.target && (n.pageX = n.clientX + n.target.scrollLeft, n.pageY = n.clientY + n.target.scrollTop);
var s = window.event && window.event.button;
n.which = s & 1 ? 1 : s & 2 ? 2 : s & 4 ? 3 : 0;
} else (enyo.platform.webos || window.PalmSystem) && n.which === 0 && (n.which = 1);
return n;
},
down: function(e) {
var t = this.makeEvent("down", e);
enyo.dispatch(t), this.downEvent = t;
},
move: function(e) {
var t = this.makeEvent("move", e);
t.dx = t.dy = t.horizontal = t.vertical = 0, t.which && this.downEvent && (t.dx = e.clientX - this.downEvent.clientX, t.dy = e.clientY - this.downEvent.clientY, t.horizontal = Math.abs(t.dx) > Math.abs(t.dy), t.vertical = !t.horizontal), enyo.dispatch(t);
},
up: function(e) {
var t = this.makeEvent("up", e), n = !1;
t.preventTap = function() {
n = !0;
}, enyo.dispatch(t), !n && this.downEvent && this.downEvent.which == 1 && this.sendTap(t), this.downEvent = null;
},
over: function(e) {
enyo.dispatch(this.makeEvent("enter", e));
},
out: function(e) {
enyo.dispatch(this.makeEvent("leave", e));
},
sendTap: function(e) {
var t = this.findCommonAncestor(this.downEvent.target, e.target);
if (t) {
var n = this.makeEvent("tap", e);
n.target = t, enyo.dispatch(n);
}
},
findCommonAncestor: function(e, t) {
var n = t;
while (n) {
if (this.isTargetDescendantOf(e, n)) return n;
n = n.parentNode;
}
},
isTargetDescendantOf: function(e, t) {
var n = e;
while (n) {
if (n == t) return !0;
n = n.parentNode;
}
}
}, enyo.gesture.preventDefault = function() {
this.srcEvent && this.srcEvent.preventDefault();
}, enyo.gesture.disablePrevention = function() {
this.preventDefault = enyo.nop, this.srcEvent && (this.srcEvent.preventDefault = enyo.nop);
}, enyo.dispatcher.features.push(function(e) {
if (enyo.gesture.events[e.type]) return enyo.gesture.events[e.type](e);
}), enyo.gesture.events = {
mousedown: function(e) {
enyo.gesture.down(e);
},
mouseup: function(e) {
enyo.gesture.up(e);
},
mousemove: function(e) {
enyo.gesture.move(e);
},
mouseover: function(e) {
enyo.gesture.over(e);
},
mouseout: function(e) {
enyo.gesture.out(e);
}
}, enyo.requiresWindow(function() {
document.addEventListener && document.addEventListener("DOMMouseScroll", function(e) {
var t = enyo.clone(e);
t.preventDefault = function() {
e.preventDefault();
}, t.type = "mousewheel";
var n = t.VERTICAL_AXIS == t.axis ? "wheelDeltaY" : "wheelDeltaX";
t[n] = t.detail * -40, enyo.dispatch(t);
}, !1);
});
// drag.js
enyo.dispatcher.features.push(function(e) {
if (enyo.gesture.drag[e.type]) return enyo.gesture.drag[e.type](e);
}), enyo.gesture.drag = {
hysteresisSquared: 16,
holdPulseDelay: 200,
trackCount: 5,
minFlick: .1,
minTrack: 8,
down: function(e) {
this.stopDragging(e), this.cancelHold(), this.target = e.target, this.startTracking(e), this.beginHold(e);
},
move: function(e) {
if (this.tracking) {
this.track(e);
if (!e.which) {
this.stopDragging(e), this.cancelHold(), this.tracking = !1;
return;
}
this.dragEvent ? this.sendDrag(e) : this.dy * this.dy + this.dx * this.dx >= this.hysteresisSquared && (this.sendDragStart(e), this.cancelHold());
}
},
up: function(e) {
this.endTracking(e), this.stopDragging(e), this.cancelHold();
},
leave: function(e) {
this.dragEvent && this.sendDragOut(e);
},
stopDragging: function(e) {
if (this.dragEvent) {
this.sendDrop(e);
var t = this.sendDragFinish(e);
return this.dragEvent = null, t;
}
},
makeDragEvent: function(e, t, n, r) {
var i = Math.abs(this.dx), s = Math.abs(this.dy), o = i > s, u = (o ? s / i : i / s) < .414, a = {
type: e,
dx: this.dx,
dy: this.dy,
ddx: this.dx - this.lastDx,
ddy: this.dy - this.lastDy,
xDirection: this.xDirection,
yDirection: this.yDirection,
pageX: n.pageX,
pageY: n.pageY,
clientX: n.clientX,
clientY: n.clientY,
horizontal: o,
vertical: !o,
lockable: u,
target: t,
dragInfo: r,
ctrlKey: n.ctrlKey,
altKey: n.altKey,
metaKey: n.metaKey,
shiftKey: n.shiftKey,
srcEvent: n.srcEvent
};
return enyo.platform.ie == 8 && a.target && (a.pageX = a.clientX + a.target.scrollLeft, a.pageY = a.clientY + a.target.scrollTop), a.preventDefault = enyo.gesture.preventDefault, a.disablePrevention = enyo.gesture.disablePrevention, a;
},
sendDragStart: function(e) {
this.dragEvent = this.makeDragEvent("dragstart", this.target, e), enyo.dispatch(this.dragEvent);
},
sendDrag: function(e) {
var t = this.makeDragEvent("dragover", e.target, e, this.dragEvent.dragInfo);
enyo.dispatch(t), t.type = "drag", t.target = this.dragEvent.target, enyo.dispatch(t);
},
sendDragFinish: function(e) {
var t = this.makeDragEvent("dragfinish", this.dragEvent.target, e, this.dragEvent.dragInfo);
t.preventTap = function() {
e.preventTap && e.preventTap();
}, enyo.dispatch(t);
},
sendDragOut: function(e) {
var t = this.makeDragEvent("dragout", e.target, e, this.dragEvent.dragInfo);
enyo.dispatch(t);
},
sendDrop: function(e) {
var t = this.makeDragEvent("drop", e.target, e, this.dragEvent.dragInfo);
t.preventTap = function() {
e.preventTap && e.preventTap();
}, enyo.dispatch(t);
},
startTracking: function(e) {
this.tracking = !0, this.px0 = e.clientX, this.py0 = e.clientY, this.flickInfo = {
startEvent: e,
moves: []
}, this.track(e);
},
track: function(e) {
this.lastDx = this.dx, this.lastDy = this.dy, this.dx = e.clientX - this.px0, this.dy = e.clientY - this.py0, this.xDirection = this.calcDirection(this.dx - this.lastDx, 0), this.yDirection = this.calcDirection(this.dy - this.lastDy, 0);
var t = this.flickInfo;
t.moves.push({
x: e.clientX,
y: e.clientY,
t: enyo.now()
}), t.moves.length > this.trackCount && t.moves.shift();
},
endTracking: function(e) {
this.tracking = !1;
var t = this.flickInfo, n = t && t.moves;
if (n && n.length > 1) {
var r = n[n.length - 1], i = enyo.now();
for (var s = n.length - 2, o = 0, u = 0, a = 0, f = 0, l = 0, c = 0, h = 0, p; p = n[s]; s--) {
o = i - p.t, u = (r.x - p.x) / o, a = (r.y - p.y) / o, c = c || (u < 0 ? -1 : u > 0 ? 1 : 0), h = h || (a < 0 ? -1 : a > 0 ? 1 : 0);
if (u * c > f * c || a * h > l * h) f = u, l = a;
}
var d = Math.sqrt(f * f + l * l);
d > this.minFlick && this.sendFlick(t.startEvent, f, l, d);
}
this.flickInfo = null;
},
calcDirection: function(e, t) {
return e > 0 ? 1 : e < 0 ? -1 : t;
},
beginHold: function(e) {
this.holdStart = enyo.now(), this.holdJob = setInterval(enyo.bind(this, "sendHoldPulse", e), this.holdPulseDelay);
},
cancelHold: function() {
clearInterval(this.holdJob), this.holdJob = null, this.sentHold && (this.sentHold = !1, this.sendRelease(this.holdEvent));
},
sendHoldPulse: function(e) {
this.sentHold || (this.sentHold = !0, this.sendHold(e));
var t = enyo.gesture.makeEvent("holdpulse", e);
t.holdTime = enyo.now() - this.holdStart, enyo.dispatch(t);
},
sendHold: function(e) {
this.holdEvent = e;
var t = enyo.gesture.makeEvent("hold", e);
enyo.dispatch(t);
},
sendRelease: function(e) {
var t = enyo.gesture.makeEvent("release", e);
enyo.dispatch(t);
},
sendFlick: function(e, t, n, r) {
var i = enyo.gesture.makeEvent("flick", e);
i.xVelocity = t, i.yVelocity = n, i.velocity = r, enyo.dispatch(i);
}
};
// transition.js
enyo.dom.transition = enyo.platform.ios || enyo.platform.android || enyo.platform.chrome || enyo.platform.androidChrome || enyo.platform.safari ? "-webkit-transition" : enyo.platform.firefox || enyo.platform.firefoxOS || enyo.platform.androidFirefox ? "-moz-transition" : "transition";
// touch.js
enyo.requiresWindow(function() {
var e = enyo.gesture, t = e.events;
e.events.touchstart = function(t) {
e.events = n, e.events.touchstart(t);
};
var n = {
_touchCount: 0,
touchstart: function(t) {
this._touchCount += t.changedTouches.length, this.excludedTarget = null;
var n = this.makeEvent(t);
e.down(n), n = this.makeEvent(t), this.overEvent = n, e.over(n);
},
touchmove: function(t) {
enyo.job.stop("resetGestureEvents");
var n = e.drag.dragEvent;
this.excludedTarget = n && n.dragInfo && n.dragInfo.node;
var r = this.makeEvent(t);
e.move(r), enyo.bodyIsFitting && t.preventDefault(), this.overEvent && this.overEvent.target != r.target && (this.overEvent.relatedTarget = r.target, r.relatedTarget = this.overEvent.target, e.out(this.overEvent), e.over(r)), this.overEvent = r;
},
touchend: function(t) {
e.up(this.makeEvent(t)), e.out(this.overEvent), this._touchCount -= t.changedTouches.length;
},
mouseup: function(n) {
this._touchCount === 0 && (this.sawMousedown = !1, e.events = t);
},
makeEvent: function(e) {
var t = enyo.clone(e.changedTouches[0]);
return t.srcEvent = e, t.target = this.findTarget(t), t.which = 1, t;
},
calcNodeOffset: function(e) {
if (e.getBoundingClientRect) {
var t = e.getBoundingClientRect();
return {
left: t.left,
top: t.top,
width: t.width,
height: t.height
};
}
},
findTarget: function(e) {
return document.elementFromPoint(e.clientX, e.clientY);
},
findTargetTraverse: function(e, t, n) {
var r = e || document.body, i = this.calcNodeOffset(r);
if (i && r != this.excludedTarget) {
var s = t - i.left, o = n - i.top;
if (s > 0 && o > 0 && s <= i.width && o <= i.height) {
var u;
for (var a = r.childNodes, f = a.length - 1, l; l = a[f]; f--) {
u = this.findTargetTraverse(l, t, n);
if (u) return u;
}
return r;
}
}
},
connect: function() {
enyo.forEach([ "ontouchstart", "ontouchmove", "ontouchend", "ongesturestart", "ongesturechange", "ongestureend" ], function(e) {
document[e] = enyo.dispatch;
}), enyo.platform.androidChrome <= 18 || enyo.platform.silk === 2 ? this.findTarget = function(e) {
return document.elementFromPoint(e.screenX, e.screenY);
} : document.elementFromPoint || (this.findTarget = function(e) {
return this.findTargetTraverse(null, e.clientX, e.clientY);
});
}
};
n.connect();
});
// msevents.js
(function() {
var e = enyo.gesture;
if (window.navigator.msPointerEnabled) {
var t = [ "MSPointerDown", "MSPointerUp", "MSPointerMove", "MSPointerOver", "MSPointerOut", "MSPointerCancel", "MSGestureTap", "MSGestureDoubleTap", "MSGestureHold", "MSGestureStart", "MSGestureChange", "MSGestureEnd" ];
enyo.forEach(t, function(e) {
enyo.dispatcher.listen(document, e);
}), enyo.dispatcher.features.push(function(e) {
i[e.type] && e.isPrimary && i[e.type](e);
}), enyo.gesture.events = {};
}
var n = function(t, n) {
var r = enyo.clone(n);
return enyo.mixin(r, {
pageX: n.translationX || 0,
pageY: n.translationY || 0,
rotation: n.rotation * (180 / Math.PI) || 0,
type: t,
srcEvent: n,
preventDefault: e.preventDefault,
disablePrevention: e.disablePrevention
});
}, r = function(e) {
var t = enyo.clone(e);
return t.srcEvent = e, t.which = 1, t;
}, i = {
MSPointerDown: function(t) {
var n = r(t);
e.down(n);
},
MSPointerUp: function(t) {
var n = r(t);
e.up(n);
},
MSPointerMove: function(t) {
var n = r(t);
e.move(n);
},
MSPointerCancel: function(t) {
var n = r(t);
e.up(n);
},
MSPointerOver: function(t) {
var n = r(t);
e.over(n);
},
MSPointerOut: function(t) {
var n = r(t);
e.out(n);
}
};
})();
// gesture.js
(function() {
!enyo.platform.gesture && enyo.platform.touch && enyo.dispatcher.features.push(function(n) {
e[n.type] && t[n.type](n);
});
var e = {
touchstart: !0,
touchmove: !0,
touchend: !0
}, t = {
orderedTouches: [],
gesture: null,
touchstart: function(e) {
enyo.forEach(e.changedTouches, function(e) {
var t = e.identifier;
enyo.indexOf(t, this.orderedTouches) < 0 && this.orderedTouches.push(t);
}, this);
if (e.touches.length >= 2 && !this.gesture) {
var t = this.gesturePositions(e);
this.gesture = this.gestureVector(t), this.gesture.angle = this.gestureAngle(t), this.gesture.scale = 1, this.gesture.rotation = 0;
var n = this.makeGesture("gesturestart", e, {
vector: this.gesture,
scale: 1,
rotation: 0
});
enyo.dispatch(n);
}
},
touchend: function(e) {
enyo.forEach(e.changedTouches, function(e) {
enyo.remove(e.identifier, this.orderedTouches);
}, this);
if (e.touches.length <= 1 && this.gesture) {
var t = e.touches[0] || e.changedTouches[e.changedTouches.length - 1];
enyo.dispatch(this.makeGesture("gestureend", e, {
vector: {
xcenter: t.pageX,
ycenter: t.pageY
},
scale: this.gesture.scale,
rotation: this.gesture.rotation
})), this.gesture = null;
}
},
touchmove: function(e) {
if (this.gesture) {
var t = this.makeGesture("gesturechange", e);
this.gesture.scale = t.scale, this.gesture.rotation = t.rotation, enyo.dispatch(t);
}
},
findIdentifiedTouch: function(e, t) {
for (var n = 0, r; r = e[n]; n++) if (r.identifier === t) return r;
},
gesturePositions: function(e) {
var t = this.findIdentifiedTouch(e.touches, this.orderedTouches[0]), n = this.findIdentifiedTouch(e.touches, this.orderedTouches[this.orderedTouches.length - 1]), r = t.pageX, i = n.pageX, s = t.pageY, o = n.pageY, u = i - r, a = o - s, f = Math.sqrt(u * u + a * a);
return {
x: u,
y: a,
h: f,
fx: r,
lx: i,
fy: s,
ly: o
};
},
gestureAngle: function(e) {
var t = e, n = Math.asin(t.y / t.h) * (180 / Math.PI);
return t.x < 0 && (n = 180 - n), t.x > 0 && t.y < 0 && (n += 360), n;
},
gestureVector: function(e) {
var t = e;
return {
magnitude: t.h,
xcenter: Math.abs(Math.round(t.fx + t.x / 2)),
ycenter: Math.abs(Math.round(t.fy + t.y / 2))
};
},
makeGesture: function(e, t, n) {
var r, i, s;
if (n) r = n.vector, i = n.scale, s = n.rotation; else {
var o = this.gesturePositions(t);
r = this.gestureVector(o), i = r.magnitude / this.gesture.magnitude, s = (360 + this.gestureAngle(o) - this.gesture.angle) % 360;
}
var u = enyo.clone(t);
return enyo.mixin(u, {
type: e,
scale: i,
pageX: r.xcenter,
pageY: r.ycenter,
rotation: s
});
}
};
})();
// ScrollMath.js
enyo.kind({
name: "enyo.ScrollMath",
kind: enyo.Component,
published: {
vertical: !0,
horizontal: !0
},
events: {
onScrollStart: "",
onScroll: "",
onScrollStop: ""
},
kSpringDamping: .93,
kDragDamping: .5,
kFrictionDamping: .97,
kSnapFriction: .9,
kFlickScalar: 15,
kMaxFlick: enyo.platform.android > 2 ? 2 : 1e9,
kFrictionEpsilon: .01,
topBoundary: 0,
rightBoundary: 0,
bottomBoundary: 0,
leftBoundary: 0,
interval: 20,
fixedTime: !0,
x0: 0,
x: 0,
y0: 0,
y: 0,
destroy: function() {
this.stop(), this.inherited(arguments);
},
verlet: function(e) {
var t = this.x;
this.x += t - this.x0, this.x0 = t;
var n = this.y;
this.y += n - this.y0, this.y0 = n;
},
damping: function(e, t, n, r) {
var i = .5, s = e - t;
return Math.abs(s) < i ? t : e * r > t * r ? n * s + t : e;
},
boundaryDamping: function(e, t, n, r) {
return this.damping(this.damping(e, t, r, 1), n, r, -1);
},
constrain: function() {
var e = this.boundaryDamping(this.y, this.topBoundary, this.bottomBoundary, this.kSpringDamping);
e != this.y && (this.y0 = e - (this.y - this.y0) * this.kSnapFriction, this.y = e);
var t = this.boundaryDamping(this.x, this.leftBoundary, this.rightBoundary, this.kSpringDamping);
t != this.x && (this.x0 = t - (this.x - this.x0) * this.kSnapFriction, this.x = t);
},
friction: function(e, t, n) {
var r = this[e] - this[t], i = Math.abs(r) > this.kFrictionEpsilon ? n : 0;
this[e] = this[t] + i * r;
},
frame: 10,
simulate: function(e) {
while (e >= this.frame) e -= this.frame, this.dragging || this.constrain(), this.verlet(), this.friction("y", "y0", this.kFrictionDamping), this.friction("x", "x0", this.kFrictionDamping);
return e;
},
animate: function() {
this.stop();
var e = enyo.now(), t = 0, n, r, i = enyo.bind(this, function() {
var s = enyo.now();
this.job = enyo.requestAnimationFrame(i);
var o = s - e;
e = s, this.dragging && (this.y0 = this.y = this.uy, this.x0 = this.x = this.ux), t += Math.max(16, o), this.fixedTime && !this.isInOverScroll() && (t = this.interval), t = this.simulate(t), r != this.y || n != this.x ? this.scroll() : this.dragging || (this.stop(!0), this.scroll()), r = this.y, n = this.x;
});
this.job = enyo.requestAnimationFrame(i);
},
start: function() {
this.job || (this.animate(), this.doScrollStart());
},
stop: function(e) {
this.job = enyo.cancelRequestAnimationFrame(this.job), e && this.doScrollStop();
},
stabilize: function() {
this.start();
var e = Math.min(this.topBoundary, Math.max(this.bottomBoundary, this.y)), t = Math.min(this.leftBoundary, Math.max(this.rightBoundary, this.x));
this.y = this.y0 = e, this.x = this.x0 = t, this.scroll(), this.stop(!0);
},
startDrag: function(e) {
this.dragging = !0, this.my = e.pageY, this.py = this.uy = this.y, this.mx = e.pageX, this.px = this.ux = this.x;
},
drag: function(e) {
if (this.dragging) {
var t = this.vertical ? e.pageY - this.my : 0;
this.uy = t + this.py, this.uy = this.boundaryDamping(this.uy, this.topBoundary, this.bottomBoundary, this.kDragDamping);
var n = this.horizontal ? e.pageX - this.mx : 0;
return this.ux = n + this.px, this.ux = this.boundaryDamping(this.ux, this.leftBoundary, this.rightBoundary, this.kDragDamping), this.start(), !0;
}
},
dragDrop: function(e) {
if (this.dragging && !window.PalmSystem) {
var t = .5;
this.y = this.uy, this.y0 = this.y - (this.y - this.y0) * t, this.x = this.ux, this.x0 = this.x - (this.x - this.x0) * t;
}
this.dragFinish();
},
dragFinish: function() {
this.dragging = !1;
},
flick: function(e) {
var t;
this.vertical && (t = e.yVelocity > 0 ? Math.min(this.kMaxFlick, e.yVelocity) : Math.max(-this.kMaxFlick, e.yVelocity), this.y = this.y0 + t * this.kFlickScalar), this.horizontal && (t = e.xVelocity > 0 ? Math.min(this.kMaxFlick, e.xVelocity) : Math.max(-this.kMaxFlick, e.xVelocity), this.x = this.x0 + t * this.kFlickScalar), this.start();
},
mousewheel: function(e) {
var t = this.vertical ? e.wheelDeltaY || e.wheelDelta : 0;
if (t > 0 && this.y < this.topBoundary || t < 0 && this.y > this.bottomBoundary) return this.stop(!0), this.y = this.y0 = this.y0 + t, this.start(), !0;
},
scroll: function() {
this.doScroll();
},
scrollTo: function(e, t) {
t !== null && (this.y = this.y0 - (t + this.y0) * (1 - this.kFrictionDamping)), e !== null && (this.x = this.x0 - (e + this.x0) * (1 - this.kFrictionDamping)), this.start();
},
setScrollX: function(e) {
this.x = this.x0 = e;
},
setScrollY: function(e) {
this.y = this.y0 = e;
},
setScrollPosition: function(e) {
this.setScrollY(e);
},
isScrolling: function() {
return Boolean(this.job);
},
isInOverScroll: function() {
return this.job && (this.x > this.leftBoundary || this.x < this.rightBoundary || this.y > this.topBoundary || this.y < this.bottomBoundary);
}
});
// ScrollStrategy.js
enyo.kind({
name: "enyo.ScrollStrategy",
tag: null,
published: {
vertical: "default",
horizontal: "default",
scrollLeft: 0,
scrollTop: 0,
maxHeight: null
},
handlers: {
ondragstart: "dragstart",
ondragfinish: "dragfinish",
ondown: "down",
onmove: "move"
},
create: function() {
this.inherited(arguments), this.horizontalChanged(), this.verticalChanged(), this.maxHeightChanged();
},
rendered: function() {
this.inherited(arguments), enyo.makeBubble(this.container, "scroll"), this.scrollNode = this.calcScrollNode();
},
teardownRender: function() {
this.inherited(arguments), this.scrollNode = null;
},
calcScrollNode: function() {
return this.container.hasNode();
},
horizontalChanged: function() {
this.container.applyStyle("overflow-x", this.horizontal == "default" ? "auto" : this.horizontal);
},
verticalChanged: function() {
this.container.applyStyle("overflow-y", this.vertical == "default" ? "auto" : this.vertical);
},
maxHeightChanged: function() {
this.container.applyStyle("max-height", this.maxHeight);
},
scrollTo: function(e, t) {
this.scrollNode && (this.setScrollLeft(e), this.setScrollTop(t));
},
scrollToNode: function(e, t) {
if (this.scrollNode) {
var n = this.getScrollBounds(), r = e, i = {
height: r.offsetHeight,
width: r.offsetWidth,
top: 0,
left: 0
};
while (r && r.parentNode && r.id != this.scrollNode.id) i.top += r.offsetTop, i.left += r.offsetLeft, r = r.parentNode;
this.setScrollTop(Math.min(n.maxTop, t === !1 ? i.top - n.clientHeight + i.height : i.top)), this.setScrollLeft(Math.min(n.maxLeft, t === !1 ? i.left - n.clientWidth + i.width : i.left));
}
},
scrollIntoView: function(e, t) {
e.hasNode() && e.node.scrollIntoView(t);
},
isInView: function(e) {
var t = this.getScrollBounds(), n = e.offsetTop, r = e.offsetHeight, i = e.offsetLeft, s = e.offsetWidth;
return n >= t.top && n + r <= t.top + t.clientHeight && i >= t.left && i + s <= t.left + t.clientWidth;
},
setScrollTop: function(e) {
this.scrollTop = e, this.scrollNode && (this.scrollNode.scrollTop = this.scrollTop);
},
setScrollLeft: function(e) {
this.scrollLeft = e, this.scrollNode && (this.scrollNode.scrollLeft = this.scrollLeft);
},
getScrollLeft: function() {
return this.scrollNode ? this.scrollNode.scrollLeft : this.scrollLeft;
},
getScrollTop: function() {
return this.scrollNode ? this.scrollNode.scrollTop : this.scrollTop;
},
_getScrollBounds: function() {
var e = this.getScrollSize(), t = this.container.hasNode(), n = {
left: this.getScrollLeft(),
top: this.getScrollTop(),
clientHeight: t ? t.clientHeight : 0,
clientWidth: t ? t.clientWidth : 0,
height: e.height,
width: e.width
};
return n.maxLeft = Math.max(0, n.width - n.clientWidth), n.maxTop = Math.max(0, n.height - n.clientHeight), n;
},
getScrollSize: function() {
var e = this.scrollNode;
return {
width: e ? e.scrollWidth : 0,
height: e ? e.scrollHeight : 0
};
},
getScrollBounds: function() {
return this._getScrollBounds();
},
calcStartInfo: function() {
var e = this.getScrollBounds(), t = this.getScrollTop(), n = this.getScrollLeft();
this.canVertical = e.maxTop > 0 && this.vertical != "hidden", this.canHorizontal = e.maxLeft > 0 && this.horizontal != "hidden", this.startEdges = {
top: t === 0,
bottom: t === e.maxTop,
left: n === 0,
right: n === e.maxLeft
};
},
shouldDrag: function(e) {
var t = e.vertical;
return t && this.canVertical || !t && this.canHorizontal;
},
dragstart: function(e, t) {
this.dragging = this.shouldDrag(t);
if (this.dragging) return this.preventDragPropagation;
},
dragfinish: function(e, t) {
this.dragging && (this.dragging = !1, t.preventTap());
},
down: function(e, t) {
this.calcStartInfo();
},
move: function(e, t) {
t.which && (this.canVertical && t.vertical || this.canHorizontal && t.horizontal) && t.disablePrevention();
}
});
// Thumb.js
enyo.kind({
name: "enyo.ScrollThumb",
axis: "v",
minSize: 4,
cornerSize: 6,
classes: "enyo-thumb",
create: function() {
this.inherited(arguments);
var e = this.axis == "v";
this.dimension = e ? "height" : "width", this.offset = e ? "top" : "left", this.translation = e ? "translateY" : "translateX", this.positionMethod = e ? "getScrollTop" : "getScrollLeft", this.sizeDimension = e ? "clientHeight" : "clientWidth", this.addClass("enyo-" + this.axis + "thumb"), this.transform = enyo.dom.canTransform(), enyo.dom.canAccelerate() && enyo.dom.transformValue(this, "translateZ", 0);
},
sync: function(e) {
this.scrollBounds = e._getScrollBounds(), this.update(e);
},
update: function(e) {
if (this.showing) {
var t = this.dimension, n = this.offset, r = this.scrollBounds[this.sizeDimension], i = this.scrollBounds[t], s = 0, o = 0, u = 0;
if (r >= i) {
this.hide();
return;
}
e.isOverscrolling() && (u = e.getOverScrollBounds()["over" + n], s = Math.abs(u), o = Math.max(u, 0));
var a = e[this.positionMethod]() - u, f = r - this.cornerSize, l = Math.floor(r * r / i - s);
l = Math.max(this.minSize, l);
var c = Math.floor(f * a / i + o);
c = Math.max(0, Math.min(f - this.minSize, c)), this.needed = l < r, this.needed && this.hasNode() ? (this._pos !== c && (this._pos = c, this.transform ? enyo.dom.transformValue(this, this.translation, c + "px") : this.axis == "v" ? this.setBounds({
top: c + "px"
}) : this.setBounds({
left: c + "px"
})), this._size !== l && (this._size = l, this.node.style[t] = this.domStyles[t] = l + "px")) : this.hide();
}
},
setShowing: function(e) {
if (e && e != this.showing && this.scrollBounds[this.sizeDimension] >= this.scrollBounds[this.dimension]) return;
this.hasNode() && this.cancelDelayHide();
if (e != this.showing) {
var t = this.showing;
this.showing = e, this.showingChanged(t);
}
},
delayHide: function(e) {
this.showing && enyo.job(this.id + "hide", enyo.bind(this, "hide"), e || 0);
},
cancelDelayHide: function() {
enyo.job.stop(this.id + "hide");
}
});
// TouchScrollStrategy.js
enyo.kind({
name: "enyo.TouchScrollStrategy",
kind: "ScrollStrategy",
overscroll: !0,
preventDragPropagation: !0,
published: {
vertical: "default",
horizontal: "default",
thumb: !0,
scrim: !1,
dragDuringGesture: !0
},
events: {
onShouldDrag: ""
},
handlers: {
onscroll: "domScroll",
onflick: "flick",
onhold: "hold",
ondragstart: "dragstart",
onShouldDrag: "shouldDrag",
ondrag: "drag",
ondragfinish: "dragfinish",
onmousewheel: "mousewheel"
},
tools: [ {
kind: "ScrollMath",
onScrollStart: "scrollMathStart",
onScroll: "scrollMathScroll",
onScrollStop: "scrollMathStop"
}, {
name: "vthumb",
kind: "ScrollThumb",
axis: "v",
showing: !1
}, {
name: "hthumb",
kind: "ScrollThumb",
axis: "h",
showing: !1
} ],
scrimTools: [ {
name: "scrim",
classes: "enyo-fit",
style: "z-index: 1;",
showing: !1
} ],
components: [ {
name: "client",
classes: "enyo-touch-scroller"
} ],
listReordering: !1,
create: function() {
this.inherited(arguments), this.transform = enyo.dom.canTransform(), this.transform || this.overscroll && this.$.client.applyStyle("position", "relative"), this.accel = enyo.dom.canAccelerate();
var e = "enyo-touch-strategy-container";
enyo.platform.ios && this.accel && (e += " enyo-composite"), this.scrimChanged(), this.container.addClass(e), this.translation = this.accel ? "translate3d" : "translate";
},
initComponents: function() {
this.createChrome(this.tools), this.inherited(arguments);
},
destroy: function() {
this.container.removeClass("enyo-touch-strategy-container"), this.inherited(arguments);
},
rendered: function() {
this.inherited(arguments), enyo.makeBubble(this.$.client, "scroll"), this.calcBoundaries(), this.syncScrollMath(), this.thumb && this.alertThumbs();
},
scrimChanged: function() {
this.scrim && !this.$.scrim && this.makeScrim(), !this.scrim && this.$.scrim && this.$.scrim.destroy();
},
makeScrim: function() {
var e = this.controlParent;
this.controlParent = null, this.createChrome(this.scrimTools), this.controlParent = e;
var t = this.container.hasNode();
t && (this.$.scrim.parentNode = t, this.$.scrim.render());
},
isScrolling: function() {
var e = this.$.scrollMath;
return e ? e.isScrolling() : this.scrolling;
},
isOverscrolling: function() {
var e = this.$.scrollMath || this;
return this.overscroll ? e.isInOverScroll() : !1;
},
domScroll: function() {
this.isScrolling() || (this.calcBoundaries(), this.syncScrollMath(), this.thumb && this.alertThumbs());
},
horizontalChanged: function() {
this.$.scrollMath.horizontal = this.horizontal != "hidden";
},
verticalChanged: function() {
this.$.scrollMath.vertical = this.vertical != "hidden";
},
maxHeightChanged: function() {
this.$.client.applyStyle("max-height", this.maxHeight), this.$.client.addRemoveClass("enyo-scrollee-fit", !this.maxHeight);
},
thumbChanged: function() {
this.hideThumbs();
},
stop: function() {
this.isScrolling() && this.$.scrollMath.stop(!0);
},
stabilize: function() {
this.$.scrollMath && this.$.scrollMath.stabilize();
},
scrollTo: function(e, t) {
this.stop(), this.$.scrollMath.scrollTo(e, t || t === 0 ? t : null);
},
scrollIntoView: function() {
this.stop(), this.inherited(arguments);
},
setScrollLeft: function() {
this.stop(), this.inherited(arguments);
},
setScrollTop: function() {
this.stop(), this.inherited(arguments);
},
getScrollLeft: function() {
return this.isScrolling() ? this.scrollLeft : this.inherited(arguments);
},
getScrollTop: function() {
return this.isScrolling() ? this.scrollTop : this.inherited(arguments);
},
calcScrollNode: function() {
return this.$.client.hasNode();
},
calcAutoScrolling: function() {
var e = this.vertical == "auto", t = this.horizontal == "auto" || this.horizontal == "default";
if ((e || t) && this.scrollNode) {
var n = this.getScrollBounds();
e && (this.$.scrollMath.vertical = n.height > n.clientHeight), t && (this.$.scrollMath.horizontal = n.width > n.clientWidth);
}
},
shouldDrag: function(e, t) {
this.calcAutoScrolling();
var n = t.vertical, r = this.$.scrollMath.horizontal && !n, i = this.$.scrollMath.vertical && n, s = t.dy < 0, o = t.dx < 0, u = !s && this.startEdges.top || s && this.startEdges.bottom, a = !o && this.startEdges.left || o && this.startEdges.right;
!t.boundaryDragger && (r || i) && (t.boundaryDragger = this);
if (!u && i || !a && r) return t.dragger = this, !0;
},
flick: function(e, t) {
var n = Math.abs(t.xVelocity) > Math.abs(t.yVelocity) ? this.$.scrollMath.horizontal : this.$.scrollMath.vertical;
if (n && this.dragging) return this.$.scrollMath.flick(t), this.preventDragPropagation;
},
hold: function(e, t) {
if (this.isScrolling() && !this.isOverscrolling()) {
var n = this.$.scrollMath || this;
return n.stop(t), !0;
}
},
move: function(e, t) {},
dragstart: function(e, t) {
if (!this.dragDuringGesture && t.srcEvent.touches && t.srcEvent.touches.length > 1) return !0;
this.doShouldDrag(t), this.dragging = t.dragger == this || !t.dragger && t.boundaryDragger == this;
if (this.dragging) {
t.preventDefault(), this.syncScrollMath(), this.$.scrollMath.startDrag(t);
if (this.preventDragPropagation) return !0;
}
},
drag: function(e, t) {
if (this.listReordering) return !1;
this.dragging && (t.preventDefault(), this.$.scrollMath.drag(t), this.scrim && this.$.scrim.show());
},
dragfinish: function(e, t) {
this.dragging && (t.preventTap(), this.$.scrollMath.dragFinish(), this.dragging = !1, this.scrim && this.$.scrim.hide());
},
mousewheel: function(e, t) {
if (!this.dragging) {
this.calcBoundaries(), this.syncScrollMath(), this.stabilize();
if (this.$.scrollMath.mousewheel(t)) return t.preventDefault(), !0;
}
},
scrollMathStart: function(e) {
this.scrollNode && (this.calcBoundaries(), this.thumb && this.showThumbs());
},
scrollMathScroll: function(e) {
this.overscroll ? this.effectScroll(-e.x, -e.y) : this.effectScroll(-Math.min(e.leftBoundary, Math.max(e.rightBoundary, e.x)), -Math.min(e.topBoundary, Math.max(e.bottomBoundary, e.y))), this.thumb && this.updateThumbs();
},
scrollMathStop: function(e) {
this.effectScrollStop(), this.thumb && this.delayHideThumbs(100);
},
calcBoundaries: function() {
var e = this.$.scrollMath || this, t = this._getScrollBounds();
e.bottomBoundary = t.clientHeight - t.height, e.rightBoundary = t.clientWidth - t.width;
},
syncScrollMath: function() {
var e = this.$.scrollMath;
e && (e.setScrollX(-this.getScrollLeft()), e.setScrollY(-this.getScrollTop()));
},
effectScroll: function(e, t) {
this.scrollNode && (this.scrollLeft = this.scrollNode.scrollLeft = e, this.scrollTop = this.scrollNode.scrollTop = t, this.effectOverscroll(Math.round(e), Math.round(t)));
},
effectScrollStop: function() {
this.effectOverscroll(null, null);
},
effectOverscroll: function(e, t) {
var n = this.scrollNode, r = "0", i = "0", s = this.accel ? ",0" : "";
t !== null && Math.abs(t - n.scrollTop) > 1 && (i = n.scrollTop - t), e !== null && Math.abs(e - n.scrollLeft) > 1 && (r = n.scrollLeft - e), this.transform ? enyo.dom.transformValue(this.$.client, this.translation, r + "px, " + i + "px" + s) : this.$.client.setBounds({
left: r + "px",
top: i + "px"
});
},
getOverScrollBounds: function() {
var e = this.$.scrollMath || this;
return {
overleft: Math.min(e.leftBoundary - e.x, 0) || Math.max(e.rightBoundary - e.x, 0),
overtop: Math.min(e.topBoundary - e.y, 0) || Math.max(e.bottomBoundary - e.y, 0)
};
},
_getScrollBounds: function() {
var e = this.inherited(arguments);
return enyo.mixin(e, this.getOverScrollBounds()), e;
},
getScrollBounds: function() {
return this.stop(), this.inherited(arguments);
},
alertThumbs: function() {
this.showThumbs(), this.delayHideThumbs(500);
},
syncThumbs: function() {
this.$.vthumb.sync(this), this.$.hthumb.sync(this);
},
updateThumbs: function() {
this.$.vthumb.update(this), this.$.hthumb.update(this);
},
showThumbs: function() {
this.syncThumbs(), this.horizontal != "hidden" && this.$.hthumb.show(), this.vertical != "hidden" && this.$.vthumb.show();
},
hideThumbs: function() {
this.$.vthumb.hide(), this.$.hthumb.hide();
},
delayHideThumbs: function(e) {
this.$.vthumb.delayHide(e), this.$.hthumb.delayHide(e);
}
});
// TranslateScrollStrategy.js
enyo.kind({
name: "enyo.TranslateScrollStrategy",
kind: "TouchScrollStrategy",
translateOptimized: !1,
components: [ {
name: "clientContainer",
classes: "enyo-touch-scroller",
components: [ {
name: "client"
} ]
} ],
rendered: function() {
this.inherited(arguments), enyo.makeBubble(this.$.clientContainer, "scroll");
},
getScrollSize: function() {
var e = this.$.client.hasNode();
return {
width: e ? e.scrollWidth : 0,
height: e ? e.scrollHeight : 0
};
},
create: function() {
this.inherited(arguments), enyo.dom.transformValue(this.$.client, this.translation, "0,0,0");
},
calcScrollNode: function() {
return this.$.clientContainer.hasNode();
},
maxHeightChanged: function() {
this.$.client.applyStyle("min-height", this.maxHeight ? null : "100%"), this.$.client.applyStyle("max-height", this.maxHeight), this.$.clientContainer.addRemoveClass("enyo-scrollee-fit", !this.maxHeight);
},
shouldDrag: function(e, t) {
return this.stop(), this.calcStartInfo(), this.inherited(arguments);
},
syncScrollMath: function() {
this.translateOptimized || this.inherited(arguments);
},
setScrollLeft: function(e) {
this.stop();
if (this.translateOptimized) {
var t = this.$.scrollMath;
t.setScrollX(-e), t.stabilize();
} else this.inherited(arguments);
},
setScrollTop: function(e) {
this.stop();
if (this.translateOptimized) {
var t = this.$.scrollMath;
t.setScrollY(-e), t.stabilize();
} else this.inherited(arguments);
},
getScrollLeft: function() {
return this.translateOptimized ? this.scrollLeft : this.inherited(arguments);
},
getScrollTop: function() {
return this.translateOptimized ? this.scrollTop : this.inherited(arguments);
},
scrollMathStart: function(e) {
this.inherited(arguments), this.scrollStarting = !0, this.startX = 0, this.startY = 0, !this.translateOptimized && this.scrollNode && (this.startX = this.getScrollLeft(), this.startY = this.getScrollTop());
},
scrollMathScroll: function(e) {
this.overscroll ? (this.scrollLeft = -e.x, this.scrollTop = -e.y) : (this.scrollLeft = -Math.min(e.leftBoundary, Math.max(e.rightBoundary, e.x)), this.scrollTop = -Math.min(e.topBoundary, Math.max(e.bottomBoundary, e.y))), this.isScrolling() && (this.$.scrollMath.isScrolling() && this.effectScroll(this.startX - this.scrollLeft, this.startY - this.scrollTop), this.thumb && this.updateThumbs());
},
effectScroll: function(e, t) {
var n = e + "px, " + t + "px" + (this.accel ? ",0" : "");
enyo.dom.transformValue(this.$.client, this.translation, n);
},
effectScrollStop: function() {
if (!this.translateOptimized) {
var e = "0,0" + (this.accel ? ",0" : ""), t = this.$.scrollMath, n = this._getScrollBounds(), r = Boolean(n.maxTop + t.bottomBoundary || n.maxLeft + t.rightBoundary);
enyo.dom.transformValue(this.$.client, this.translation, r ? null : e), this.setScrollLeft(this.scrollLeft), this.setScrollTop(this.scrollTop), r && enyo.dom.transformValue(this.$.client, this.translation, e);
}
},
twiddle: function() {
this.translateOptimized && this.scrollNode && (this.scrollNode.scrollTop = 1, this.scrollNode.scrollTop = 0);
},
down: enyo.nop
});
// TransitionScrollStrategy.js
enyo.kind({
name: "enyo.TransitionScrollStrategy",
kind: "enyo.TouchScrollStrategy",
components: [ {
name: "clientContainer",
classes: "enyo-touch-scroller",
components: [ {
name: "client"
} ]
} ],
events: {
onScrollStart: "",
onScroll: "",
onScrollStop: ""
},
handlers: {
ondown: "down",
ondragfinish: "dragfinish",
onwebkitTransitionEnd: "transitionComplete"
},
tools: [ {
name: "vthumb",
kind: "ScrollThumb",
axis: "v",
showing: !0
}, {
name: "hthumb",
kind: "ScrollThumb",
axis: "h",
showing: !1
} ],
kFlickScalar: 600,
topBoundary: 0,
rightBoundary: 0,
bottomBoundary: 0,
leftBoundary: 0,
scrolling: !1,
listener: null,
boundaryX: 0,
boundaryY: 0,
stopTimeout: null,
stopTimeoutMS: 80,
scrollInterval: null,
scrollIntervalMS: 50,
transitions: {
none: "",
scroll: "3.8s cubic-bezier(.19,1,.28,1.0) 0s",
bounce: "0.5s cubic-bezier(0.06,.5,.5,.94) 0s"
},
setScrollLeft: function(e) {
var t = this.scrollLeft;
this.stop(), this.scrollLeft = e;
if (this.isInLeftOverScroll() || this.isInRightOverScroll()) this.scrollLeft = t;
this.effectScroll();
},
setScrollTop: function(e) {
var t = this.scrollTop;
this.stop(), this.scrollTop = e;
if (this.isInTopOverScroll() || this.isInBottomOverScroll()) this.scrollTop = t;
this.effectScroll();
},
setScrollX: function(e) {
this.scrollLeft = -1 * e;
},
setScrollY: function(e) {
this.scrollTop = -1 * e;
},
getScrollLeft: function() {
return this.scrollLeft;
},
getScrollTop: function() {
return this.scrollTop;
},
create: function() {
this.inherited(arguments), enyo.dom.transformValue(this.$.client, this.translation, "0,0,0");
},
destroy: function() {
this.clearCSSTransitionInterval(), this.inherited(arguments);
},
getScrollSize: function() {
var e = this.$.client.hasNode();
return {
width: e ? e.scrollWidth : 0,
height: e ? e.scrollHeight : 0
};
},
horizontalChanged: function() {
this.horizontal == "hidden" && (this.scrollHorizontal = !1);
},
verticalChanged: function() {
this.vertical == "hidden" && (this.scrollVertical = !1);
},
calcScrollNode: function() {
return this.$.clientContainer.hasNode();
},
calcBoundaries: function() {
var e = this._getScrollBounds();
this.bottomBoundary = e.clientHeight - e.height, this.rightBoundary = e.clientWidth - e.width;
},
maxHeightChanged: function() {
this.$.client.applyStyle("min-height", this.maxHeight ? null : "100%"), this.$.client.applyStyle("max-height", this.maxHeight), this.$.clientContainer.addRemoveClass("enyo-scrollee-fit", !this.maxHeight);
},
calcAutoScrolling: function() {
var e = this.getScrollBounds();
this.vertical && (this.scrollVertical = e.height > e.clientHeight), this.horizontal && (this.scrollHorizontal = e.width > e.clientWidth);
},
isInOverScroll: function() {
return this.isInTopOverScroll() || this.isInBottomOverScroll() || this.isInLeftOverScroll() || this.isInRightOverScroll();
},
isInLeftOverScroll: function() {
return this.getScrollLeft() < this.leftBoundary;
},
isInRightOverScroll: function() {
return this.getScrollLeft <= 0 ? !1 : this.getScrollLeft() * -1 < this.rightBoundary;
},
isInTopOverScroll: function() {
return this.getScrollTop() < this.topBoundary;
},
isInBottomOverScroll: function() {
return this.getScrollTop() <= 0 ? !1 : this.getScrollTop() * -1 < this.bottomBoundary;
},
calcStartInfo: function() {
var e = this.getScrollBounds(), t = this.getScrollTop(), n = this.getScrollLeft();
this.startEdges = {
top: t === 0,
bottom: t === e.maxTop,
left: n === 0,
right: n === e.maxLeft
};
},
mousewheel: function(e, t) {
if (!this.dragging) {
this.calcBoundaries(), this.syncScrollMath(), this.stabilize();
var n = this.vertical ? t.wheelDeltaY || t.wheelDelta : 0, r = parseFloat(this.getScrollTop()) + -1 * parseFloat(n);
return r = r * -1 < this.bottomBoundary ? -1 * this.bottomBoundary : r < this.topBoundary ? this.topBoundary : r, this.setScrollTop(r), this.doScroll(), t.preventDefault(), !0;
}
},
scroll: function(e, t) {
this.thumb && this.updateThumbs(), this.calcBoundaries(), this.doScroll();
},
start: function() {
this.startScrolling(), this.doScrollStart();
},
stop: function() {
this.isScrolling() && this.stopScrolling(), this.thumb && this.delayHideThumbs(100), this.doScrollStop();
},
updateX: function() {
var e = window.getComputedStyle(this.$.client.node, null).getPropertyValue(enyo.dom.getCssTransformProp()).split("(")[1];
return e = e == undefined ? 0 : e.split(")")[0].split(",")[4], -1 * parseFloat(e) === this.scrollLeft ? !1 : (this.scrollLeft = -1 * parseFloat(e), !0);
},
updateY: function() {
var e = window.getComputedStyle(this.$.client.node, null).getPropertyValue(enyo.dom.getCssTransformProp()).split("(")[1];
return e = e == undefined ? 0 : e.split(")")[0].split(",")[5], -1 * parseFloat(e) === this.scrollTop ? !1 : (this.scrollTop = -1 * parseFloat(e), !0);
},
effectScroll: function() {
var e = -1 * this.scrollLeft + "px, " + -1 * this.scrollTop + "px" + (this.accel ? ", 0" : "");
enyo.dom.transformValue(this.$.client, this.translation, e);
},
down: function(e, t) {
var n = this;
if (this.isScrolling() && !this.isOverscrolling()) return this.stopTimeout = setTimeout(function() {
n.stop();
}, this.stopTimeoutMS), !0;
},
dragstart: function(e, t) {
this.stopTimeout && clearTimeout(this.stopTimeout);
if (!this.dragDuringGesture && t.srcEvent.touches && t.srcEvent.touches.length > 1) return !0;
this.shouldDrag(t), this.dragging = t.dragger == this || !t.dragger && t.boundaryDragger == this;
if (this.dragging) {
this.isScrolling() && this.stopScrolling(), this.thumb && this.showThumbs(), t.preventDefault(), this.prevY = t.pageY, this.prevX = t.pageX;
if (this.preventDragPropagation) return !0;
}
},
shouldDrag: function(e) {
return this.calcStartInfo(), this.calcBoundaries(), this.calcAutoScrolling(), this.scrollHorizontal ? this.scrollVertical ? this.shouldDragVertical(e) || this.shouldDragHorizontal(e) : this.shouldDragHorizontal(e) : this.shouldDragVertical(e);
},
shouldDragVertical: function(e) {
var t = this.canDragVertical(e), n = this.oobVertical(e);
!e.boundaryDragger && t && (e.boundaryDragger = this);
if (!n && t) return e.dragger = this, !0;
},
shouldDragHorizontal: function(e) {
var t = this.canDragHorizontal(e), n = this.oobHorizontal(e);
!e.boundaryDragger && t && (e.boundaryDragger = this);
if (!n && t) return e.dragger = this, !0;
},
canDragVertical: function(e) {
return this.scrollVertical && e.vertical;
},
canDragHorizontal: function(e) {
return this.scrollHorizontal && !e.vertical;
},
oobVertical: function(e) {
var t = e.dy < 0;
return !t && this.startEdges.top || t && this.startEdges.bottom;
},
oobHorizontal: function(e) {
var t = e.dx < 0;
return !t && this.startEdges.left || t && this.startEdges.right;
},
drag: function(e, t) {
if (this.listReordering) return !1;
this.dragging && (t.preventDefault(), this.scrollLeft = this.scrollHorizontal ? this.calculateDragDistance(parseInt(this.getScrollLeft(), 10), -1 * (t.pageX - this.prevX), this.leftBoundary, this.rightBoundary) : this.getScrollLeft(), this.scrollTop = this.scrollVertical ? this.calculateDragDistance(this.getScrollTop(), -1 * (t.pageY - this.prevY), this.topBoundary, this.bottomBoundary) : this.getScrollTop(), this.effectScroll(), this.scroll(), this.prevY = t.pageY, this.prevX = t.pageX, this.resetBoundaryX(), this.resetBoundaryY());
},
calculateDragDistance: function(e, t, n, r) {
var i = e + t;
return this.overscrollDragDamping(e, i, t, n, r);
},
overscrollDragDamping: function(e, t, n, r, i) {
if (t < r || t * -1 < i) n /= 2, t = e + n;
return t;
},
resetBoundaryX: function() {
this.boundaryX = 0;
},
resetBoundaryY: function() {
this.boundaryY = 0;
},
dragfinish: function(e, t) {
this.dragging && (t.preventTap(), this.dragging = !1, this.isScrolling() || this.correctOverflow(), this.scrim && this.$.scrim.hide());
},
correctOverflow: function() {
if (this.isInOverScroll()) {
var e = this.scrollHorizontal ? this.correctOverflowX() : !1, t = this.scrollVertical ? this.correctOverflowY() : !1;
e !== !1 && t !== !1 ? (this.scrollLeft = e !== !1 ? e : this.getScrollLeft(), this.scrollTop = t !== !1 ? t : this.getScrollTop(), this.startOverflowScrolling()) : e !== !1 ? (this.scrollLeft = e, this.scrollTop = this.targetScrollTop || this.scrollTop, this.targetScrollLeft = this.getScrollLeft(), this.vertical ? this.startScrolling() : this.startOverflowScrolling()) : t !== !1 && (this.scrollTop = t, this.scrollLeft = this.targetScrollLeft || this.scrollLeft, this.targetScrollTop = this.getScrollTop(), this.scrollHorizontal ? this.startScrolling() : this.startOverflowScrolling());
}
},
correctOverflowX: function() {
if (this.isInLeftOverScroll()) {
if (this.beyondBoundary(this.getScrollLeft(), this.leftBoundary, this.boundaryX)) return this.leftBoundary;
} else if (this.isInRightOverScroll() && this.beyondBoundary(this.getScrollLeft(), this.rightBoundary, this.boundaryX)) return -1 * this.rightBoundary;
return !1;
},
correctOverflowY: function() {
if (this.isInTopOverScroll()) {
if (this.beyondBoundary(this.getScrollTop(), this.topBoundary, this.boundaryY)) return this.topBoundary;
} else if (this.isInBottomOverScroll() && this.beyondBoundary(this.getScrollTop(), this.bottomBoundary, this.boundaryY)) return -1 * this.bottomBoundary;
return !1;
},
beyondBoundary: function(e, t, n) {
return Math.abs(Math.abs(t) - Math.abs(e)) > Math.abs(n);
},
flick: function(e, t) {
if (this.dragging && this.flickOnEnabledAxis(t)) return this.scrollLeft = this.scrollHorizontal ? this.calculateFlickDistance(this.scrollLeft, -1 * t.xVelocity) : this.getScrollLeft(), this.scrollTop = this.scrollVertical ? this.calculateFlickDistance(this.scrollTop, -1 * t.yVelocity) : this.getScrollTop(), this.targetScrollLeft = this.scrollLeft, this.targetScrollTop = this.scrollTop, this.boundaryX = null, this.boundaryY = null, this.isInLeftOverScroll() ? this.boundaryX = this.figureBoundary(this.getScrollLeft()) : this.isInRightOverScroll() && (this.boundaryX = this.figureBoundary(-1 * this.bottomBoundary - this.getScrollLeft())), this.isInTopOverScroll() ? this.boundaryY = this.figureBoundary(this.getScrollTop()) : this.isInBottomOverScroll() && (this.boundaryY = this.figureBoundary(-1 * this.bottomBoundary - this.getScrollTop())), this.startScrolling(), this.preventDragPropagation;
},
flickOnEnabledAxis: function(e) {
return Math.abs(e.xVelocity) > Math.abs(e.yVelocity) ? this.scrollHorizontal : this.scrollVertical;
},
calculateFlickDistance: function(e, t) {
return e + t * this.kFlickScalar;
},
startScrolling: function() {
this.applyTransition("scroll"), this.effectScroll(), this.setCSSTransitionInterval(), this.scrolling = !0;
},
startOverflowScrolling: function() {
this.applyTransition("bounce"), this.effectScroll(), this.setOverflowTransitionInterval(), this.scrolling = !0;
},
applyTransition: function(e) {
var t = this.translation + ": " + this.transitions[e];
this.$.client.applyStyle("-webkit-transition", this.transitions[e]);
},
stopScrolling: function() {
this.resetCSSTranslationVals(), this.clearCSSTransitionInterval(), this.scrolling = !1;
},
setCSSTransitionInterval: function() {
this.clearCSSTransitionInterval(), this.scrollInterval = setInterval(enyo.bind(this, function() {
this.updateScrollPosition(), this.correctOverflow();
}), this.scrollIntervalMS);
},
setOverflowTransitionInterval: function() {
this.clearCSSTransitionInterval(), this.scrollInterval = setInterval(enyo.bind(this, function() {
this.updateScrollPosition();
}), this.scrollIntervalMS);
},
updateScrollPosition: function() {
var e = this.updateY(), t = this.updateX();
this.scroll(), !e && !t && this.stop();
},
clearCSSTransitionInterval: function() {
this.scrollInterval && (clearInterval(this.scrollInterval), this.scrollInterval = null);
},
resetCSSTranslationVals: function() {
var e = enyo.dom.getCssTransformProp(), t = window.getComputedStyle(this.$.client.node, null).getPropertyValue(e).split("(")[1].split(")")[0].split(",");
this.applyTransition("none"), this.scrollLeft = -1 * t[4], this.scrollTop = -1 * t[5], this.effectScroll();
},
figureBoundary: function(e) {
var t = Math.abs(e), n = t - t / Math.pow(t, .02);
return n = e < 0 ? -1 * n : n, n;
},
transitionComplete: function(e, t) {
if (t.originator !== this.$.client) return;
var n = !1;
this.isInTopOverScroll() ? (n = !0, this.scrollTop = this.topBoundary) : this.isInBottomOverScroll() && (n = !0, this.scrollTop = -1 * this.bottomBoundary), this.isInLeftOverScroll() ? (n = !0, this.scrollLeft = this.leftBoundary) : this.isInRightOverScroll() && (n = !0, this.scrollLeft = -1 * this.rightBoundary), n ? this.startOverflowScrolling() : this.stop();
},
scrollTo: function(e, t) {
this.setScrollTop(t), this.setScrollLeft(e), this.start();
},
getOverScrollBounds: function() {
return {
overleft: Math.min(this.leftBoundary + this.scrollLeft, 0) || Math.max(this.rightBoundary + this.scrollLeft, 0),
overtop: Math.min(this.topBoundary + this.scrollTop, 0) || Math.max(this.bottomBoundary + this.scrollTop, 0)
};
}
});
// Scroller.js
enyo.kind({
name: "enyo.Scroller",
published: {
horizontal: "default",
vertical: "default",
scrollTop: 0,
scrollLeft: 0,
maxHeight: null,
touch: !1,
strategyKind: "ScrollStrategy",
thumb: !0
},
events: {
onScrollStart: "",
onScroll: "",
onScrollStop: ""
},
touchOverscroll: !0,
preventDragPropagation: !0,
preventScrollPropagation: !0,
handlers: {
onscroll: "domScroll",
onScrollStart: "scrollStart",
onScroll: "scroll",
onScrollStop: "scrollStop"
},
classes: "enyo-scroller",
statics: {
osInfo: [ {
os: "android",
version: 3
}, {
os: "androidChrome",
version: 18
}, {
os: "androidFirefox",
version: 16
}, {
os: "firefoxOS",
version: 16
}, {
os: "ios",
version: 5
}, {
os: "webos",
version: 1e9
}, {
os: "blackberry",
version: 1e9
} ],
hasTouchScrolling: function() {
for (var e = 0, t, n; t = this.osInfo[e]; e++) if (enyo.platform[t.os]) return !0;
if ((enyo.platform.ie >= 10 || enyo.platform.windowsPhone >= 8) && enyo.platform.touch) return !0;
},
hasNativeScrolling: function() {
for (var e = 0, t, n; t = this.osInfo[e]; e++) if (enyo.platform[t.os] < t.version) return !1;
return !0;
},
getTouchStrategy: function() {
return enyo.platform.android >= 3 || enyo.platform.windowsPhone === 8 ? "TranslateScrollStrategy" : "TouchScrollStrategy";
}
},
controlParentName: "strategy",
create: function() {
this.inherited(arguments), this.horizontalChanged(), this.verticalChanged();
},
importProps: function(e) {
this.inherited(arguments), e && e.strategyKind === undefined && (enyo.Scroller.touchScrolling || this.touch) && (this.strategyKind = enyo.Scroller.getTouchStrategy());
},
initComponents: function() {
this.strategyKindChanged(), this.inherited(arguments);
},
teardownChildren: function() {
this.cacheScrollPosition(), this.inherited(arguments);
},
rendered: function() {
this.inherited(arguments), this.restoreScrollPosition();
},
strategyKindChanged: function() {
this.$.strategy && (this.$.strategy.destroy(), this.controlParent = null), this.createStrategy(), this.hasNode() && this.render();
},
createStrategy: function() {
this.createComponents([ {
name: "strategy",
maxHeight: this.maxHeight,
kind: this.strategyKind,
thumb: this.thumb,
preventDragPropagation: this.preventDragPropagation,
overscroll: this.touchOverscroll,
isChrome: !0
} ]);
},
getStrategy: function() {
return this.$.strategy;
},
maxHeightChanged: function() {
this.$.strategy.setMaxHeight(this.maxHeight);
},
showingChanged: function() {
this.showing || (this.cacheScrollPosition(), this.setScrollLeft(0), this.setScrollTop(0)), this.inherited(arguments), this.showing && this.restoreScrollPosition();
},
thumbChanged: function() {
this.$.strategy.setThumb(this.thumb);
},
cacheScrollPosition: function() {
this.cachedPosition = {
left: this.getScrollLeft(),
top: this.getScrollTop()
};
},
restoreScrollPosition: function() {
this.cachedPosition && (this.setScrollLeft(this.cachedPosition.left), this.setScrollTop(this.cachedPosition.top), this.cachedPosition = null);
},
horizontalChanged: function() {
this.$.strategy.setHorizontal(this.horizontal);
},
verticalChanged: function() {
this.$.strategy.setVertical(this.vertical);
},
setScrollLeft: function(e) {
this.scrollLeft = e, this.$.strategy.setScrollLeft(this.scrollLeft);
},
setScrollTop: function(e) {
this.scrollTop = e, this.$.strategy.setScrollTop(e);
},
getScrollLeft: function() {
return this.$.strategy.getScrollLeft();
},
getScrollTop: function() {
return this.$.strategy.getScrollTop();
},
getScrollBounds: function() {
return this.$.strategy.getScrollBounds();
},
scrollIntoView: function(e, t) {
this.$.strategy.scrollIntoView(e, t);
},
scrollTo: function(e, t) {
this.$.strategy.scrollTo(e, t);
},
scrollToControl: function(e, t) {
this.scrollToNode(e.hasNode(), t);
},
scrollToNode: function(e, t) {
this.$.strategy.scrollToNode(e, t);
},
domScroll: function(e, t) {
return this.$.strategy.domScroll && t.originator == this && this.$.strategy.scroll(e, t), this.doScroll(t), !0;
},
shouldStopScrollEvent: function(e) {
return this.preventScrollPropagation && e.originator.owner != this.$.strategy;
},
scrollStart: function(e, t) {
return this.shouldStopScrollEvent(t);
},
scroll: function(e, t) {
return t.dispatchTarget ? this.preventScrollPropagation && t.originator != this && t.originator.owner != this.$.strategy : this.shouldStopScrollEvent(t);
},
scrollStop: function(e, t) {
return this.shouldStopScrollEvent(t);
},
scrollToTop: function() {
this.setScrollTop(0);
},
scrollToBottom: function() {
this.setScrollTop(this.getScrollBounds().maxTop);
},
scrollToRight: function() {
this.setScrollLeft(this.getScrollBounds().maxLeft);
},
scrollToLeft: function() {
this.setScrollLeft(0);
},
stabilize: function() {
var e = this.getStrategy();
e.stabilize && e.stabilize();
}
}), enyo.Scroller.hasTouchScrolling() && (enyo.Scroller.prototype.strategyKind = enyo.Scroller.getTouchStrategy());
// Animator.js
enyo.kind({
name: "enyo.Animator",
kind: "Component",
published: {
duration: 350,
startValue: 0,
endValue: 1,
node: null,
easingFunction: enyo.easing.cubicOut
},
events: {
onStep: "",
onEnd: "",
onStop: ""
},
constructed: function() {
this.inherited(arguments), this._next = enyo.bind(this, "next");
},
destroy: function() {
this.stop(), this.inherited(arguments);
},
play: function(e) {
return this.stop(), this.reversed = !1, e && enyo.mixin(this, e), this.t0 = this.t1 = enyo.now(), this.value = this.startValue, this.job = !0, this.next(), this;
},
stop: function() {
if (this.isAnimating()) return this.cancel(), this.fire("onStop"), this;
},
reverse: function() {
if (this.isAnimating()) {
this.reversed = !this.reversed;
var e = this.t1 = enyo.now(), t = e - this.t0;
this.t0 = e + t - this.duration;
var n = this.startValue;
return this.startValue = this.endValue, this.endValue = n, this;
}
},
isAnimating: function() {
return Boolean(this.job);
},
requestNext: function() {
this.job = enyo.requestAnimationFrame(this._next, this.node);
},
cancel: function() {
enyo.cancelRequestAnimationFrame(this.job), this.node = null, this.job = null;
},
shouldEnd: function() {
return this.dt >= this.duration;
},
next: function() {
this.t1 = enyo.now(), this.dt = this.t1 - this.t0;
var e = this.fraction = enyo.easedLerp(this.t0, this.duration, this.easingFunction, this.reversed);
this.value = this.startValue + e * (this.endValue - this.startValue), e >= 1 || this.shouldEnd() ? (this.value = this.endValue, this.fraction = 1, this.fire("onStep"), this.fire("onEnd"), this.cancel()) : (this.fire("onStep"), this.requestNext());
},
fire: function(e) {
var t = this[e];
enyo.isString(t) ? this.bubble(e) : t && t.call(this.context || window, this);
}
});
// BaseLayout.js
enyo.kind({
name: "enyo.BaseLayout",
kind: enyo.Layout,
layoutClass: "enyo-positioned",
reflow: function() {
enyo.forEach(this.container.children, function(e) {
e.fit !== null && e.addRemoveClass("enyo-fit", e.fit);
}, this);
}
});
// Image.js
enyo.kind({
name: "enyo.Image",
noEvents: !1,
tag: "img",
attributes: {
draggable: "false"
},
create: function() {
this.noEvents && (delete this.attributes.onload, delete this.attributes.onerror), this.inherited(arguments);
},
rendered: function() {
this.inherited(arguments), enyo.makeBubble(this, "load", "error");
}
});
// Input.js
enyo.kind({
name: "enyo.Input",
published: {
value: "",
placeholder: "",
type: "",
disabled: !1,
selectOnFocus: !1
},
events: {
onDisabledChange: ""
},
defaultFocus: !1,
tag: "input",
classes: "enyo-input",
handlers: {
onfocus: "focused",
oninput: "input",
onclear: "clear",
ondragstart: "dragstart"
},
create: function() {
enyo.platform.ie && (this.handlers.onkeyup = "iekeyup"), enyo.platform.windowsPhone && (this.handlers.onkeydown = "iekeydown"), this.inherited(arguments), this.placeholderChanged(), this.type && this.typeChanged(), this.valueChanged();
},
rendered: function() {
this.inherited(arguments), enyo.makeBubble(this, "focus", "blur"), enyo.platform.ie == 8 && this.setAttribute("onchange", enyo.bubbler), this.disabledChanged(), this.defaultFocus && this.focus();
},
typeChanged: function() {
this.setAttribute("type", this.type);
},
placeholderChanged: function() {
this.setAttribute("placeholder", this.placeholder);
},
disabledChanged: function() {
this.setAttribute("disabled", this.disabled), this.bubble("onDisabledChange");
},
getValue: function() {
return this.getNodeProperty("value", this.value);
},
valueChanged: function() {
this.setAttribute("value", this.value), this.setNodeProperty("value", this.value);
},
iekeyup: function(e, t) {
var n = enyo.platform.ie, r = t.keyCode;
(n <= 8 || n == 9 && (r == 8 || r == 46)) && this.bubble("oninput", t);
},
iekeydown: function(e, t) {
var n = enyo.platform.windowsPhone, r = t.keyCode, i = t.dispatchTarget;
n <= 8 && r == 13 && this.tag == "input" && i.hasNode() && i.node.blur();
},
clear: function() {
this.setValue("");
},
focus: function() {
this.hasNode() && this.node.focus();
},
hasFocus: function() {
if (this.hasNode()) return document.activeElement === this.node;
},
dragstart: function() {
return this.hasFocus();
},
focused: function() {
this.selectOnFocus && enyo.asyncMethod(this, "selectContents");
},
selectContents: function() {
var e = this.hasNode();
if (e && e.setSelectionRange) e.setSelectionRange(0, e.value.length); else if (e && e.createTextRange) {
var t = e.createTextRange();
t.expand("textedit"), t.select();
}
}
});
// RichText.js
enyo.kind({
name: "enyo.RichText",
classes: "enyo-richtext enyo-selectable",
published: {
allowHtml: !0,
disabled: !1,
value: ""
},
defaultFocus: !1,
statics: {
osInfo: [ {
os: "android",
version: 3
}, {
os: "ios",
version: 5
} ],
hasContentEditable: function() {
for (var e = 0, t, n; t = enyo.RichText.osInfo[e]; e++) if (enyo.platform[t.os] < t.version) return !1;
return !0;
}
},
kind: enyo.Input,
attributes: {
contenteditable: !0
},
handlers: {
onfocus: "focusHandler",
onblur: "blurHandler"
},
create: function() {
this.setTag(enyo.RichText.hasContentEditable() ? "div" : "textarea"), this.inherited(arguments);
},
focusHandler: function() {
this._value = this.getValue();
},
blurHandler: function() {
this._value !== this.getValue() && this.bubble("onchange");
},
valueChanged: function() {
this.hasFocus() ? (this.selectAll(), this.insertAtCursor(this.value)) : this.setPropertyValue("content", this.value, "contentChanged");
},
getValue: function() {
if (this.hasNode()) return this.node.innerHTML;
},
hasFocus: function() {
if (this.hasNode()) return document.activeElement === this.node;
},
getSelection: function() {
if (this.hasFocus()) return window.getSelection();
},
removeSelection: function(e) {
var t = this.getSelection();
t && t[e ? "collapseToStart" : "collapseToEnd"]();
},
modifySelection: function(e, t, n) {
var r = this.getSelection();
r && r.modify(e || "move", t, n);
},
moveCursor: function(e, t) {
this.modifySelection("move", e, t);
},
moveCursorToEnd: function() {
this.moveCursor("forward", "documentboundary");
},
moveCursorToStart: function() {
this.moveCursor("backward", "documentboundary");
},
selectAll: function() {
this.hasFocus() && document.execCommand("selectAll");
},
insertAtCursor: function(e) {
if (this.hasFocus()) {
var t = this.allowHtml ? e : enyo.Control.escapeHtml(e).replace(/\n/g, "<br/>");
document.execCommand("insertHTML", !1, t);
}
}
});
// TextArea.js
enyo.kind({
name: "enyo.TextArea",
kind: enyo.Input,
tag: "textarea",
classes: "enyo-textarea",
rendered: function() {
this.inherited(arguments), this.valueChanged();
}
});
// Select.js
enyo.kind({
name: "enyo.Select",
published: {
selected: 0
},
handlers: {
onchange: "change"
},
tag: "select",
defaultKind: "enyo.Option",
rendered: function() {
this.inherited(arguments), enyo.platform.ie == 8 && this.setAttribute("onchange", enyo.bubbler), this.selectedChanged();
},
getSelected: function() {
return Number(this.getNodeProperty("selectedIndex", this.selected));
},
setSelected: function(e) {
this.setPropertyValue("selected", Number(e), "selectedChanged");
},
selectedChanged: function() {
this.setNodeProperty("selectedIndex", this.selected);
},
change: function() {
this.selected = this.getSelected();
},
render: function() {
enyo.platform.ie ? this.parent.render() : this.inherited(arguments);
},
getValue: function() {
if (this.hasNode()) return this.node.value;
}
}), enyo.kind({
name: "enyo.Option",
published: {
value: ""
},
tag: "option",
create: function() {
this.inherited(arguments), this.valueChanged();
},
valueChanged: function() {
this.setAttribute("value", this.value);
}
}), enyo.kind({
name: "enyo.OptionGroup",
published: {
label: ""
},
tag: "optgroup",
defaultKind: "enyo.Option",
create: function() {
this.inherited(arguments), this.labelChanged();
},
labelChanged: function() {
this.setAttribute("label", this.label);
}
});
// Group.js
enyo.kind({
name: "enyo.Group",
published: {
highlander: !0,
active: null
},
handlers: {
onActivate: "activate"
},
activate: function(e, t) {
this.highlander && (t.originator.active ? this.setActive(t.originator) : t.originator == this.active && this.active.setActive(!0));
},
activeChanged: function(e) {
e && (e.setActive(!1), e.removeClass("active")), this.active && this.active.addClass("active");
}
});
// GroupItem.js
enyo.kind({
name: "enyo.GroupItem",
published: {
active: !1
},
rendered: function() {
this.inherited(arguments), this.activeChanged();
},
activeChanged: function() {
this.bubble("onActivate");
}
});
// ToolDecorator.js
enyo.kind({
name: "enyo.ToolDecorator",
kind: enyo.GroupItem,
classes: "enyo-tool-decorator"
});
// Button.js
enyo.kind({
name: "enyo.Button",
kind: enyo.ToolDecorator,
tag: "button",
attributes: {
type: "button"
},
published: {
disabled: !1
},
create: function() {
this.inherited(arguments), this.disabledChanged();
},
disabledChanged: function() {
this.setAttribute("disabled", this.disabled);
},
tap: function() {
if (this.disabled) return !0;
this.setActive(!0);
}
});
// Checkbox.js
enyo.kind({
name: "enyo.Checkbox",
kind: enyo.Input,
classes: "enyo-checkbox",
events: {
onActivate: ""
},
published: {
checked: !1,
active: !1,
type: "checkbox"
},
kindClasses: "",
handlers: {
onchange: "change",
onclick: "click"
},
create: function() {
this.inherited(arguments);
},
rendered: function() {
this.inherited(arguments), this.active && this.activeChanged(), this.checkedChanged();
},
getChecked: function() {
return enyo.isTrue(this.getNodeProperty("checked", this.checked));
},
checkedChanged: function() {
this.setNodeProperty("checked", this.checked), this.setAttribute("checked", this.checked ? "checked" : ""), this.setActive(this.checked);
},
activeChanged: function() {
this.active = enyo.isTrue(this.active), this.setChecked(this.active), this.bubble("onActivate");
},
setValue: function(e) {
this.setChecked(enyo.isTrue(e));
},
getValue: function() {
return this.getChecked();
},
valueChanged: function() {},
change: function() {
this.setActive(this.getChecked());
},
click: function(e, t) {
enyo.platform.ie <= 8 && this.bubble("onchange", t);
}
});
// Repeater.js
enyo.kind({
name: "enyo.Repeater",
published: {
count: 0
},
events: {
onSetupItem: ""
},
create: function() {
this.inherited(arguments), this.countChanged();
},
initComponents: function() {
this.itemComponents = this.components || this.kindComponents, this.components = this.kindComponents = null, this.inherited(arguments);
},
setCount: function(e) {
this.setPropertyValue("count", e, "countChanged");
},
countChanged: function() {
this.build();
},
itemAtIndex: function(e) {
return this.controlAtIndex(e);
},
build: function() {
this.destroyClientControls();
for (var e = 0, t; e < this.count; e++) t = this.createComponent({
kind: "enyo.OwnerProxy",
index: e
}), t.createComponents(this.itemComponents), this.doSetupItem({
index: e,
item: t
});
this.render();
},
renderRow: function(e) {
var t = this.itemAtIndex(e);
this.doSetupItem({
index: e,
item: t
});
}
}), enyo.kind({
name: "enyo.OwnerProxy",
tag: null,
decorateEvent: function(e, t, n) {
t && (t.index = this.index), this.inherited(arguments);
},
delegateEvent: function(e, t, n, r, i) {
return e == this && (e = this.owner.owner), this.inherited(arguments, [ e, t, n, r, i ]);
}
});
// DragAvatar.js
enyo.kind({
name: "enyo._DragAvatar",
style: "position: absolute; z-index: 10; pointer-events: none; cursor: move;",
showing: !1,
showingChanged: function() {
this.inherited(arguments), document.body.style.cursor = this.showing ? "move" : null;
}
}), enyo.kind({
name: "enyo.DragAvatar",
kind: enyo.Component,
published: {
showing: !1,
offsetX: 20,
offsetY: 30
},
initComponents: function() {
this.avatarComponents = this.components, this.components = null, this.inherited(arguments);
},
requireAvatar: function() {
this.avatar || (this.avatar = this.createComponent({
kind: enyo._DragAvatar,
parentNode: document.body,
showing: !1,
components: this.avatarComponents
}).render());
},
showingChanged: function() {
this.avatar.setShowing(this.showing), document.body.style.cursor = this.showing ? "move" : null;
},
drag: function(e) {
this.requireAvatar(), this.avatar.setBounds({
top: e.pageY - this.offsetY,
left: e.pageX + this.offsetX
}), this.show();
},
show: function() {
this.setShowing(!0);
},
hide: function() {
this.setShowing(!1);
}
});
// FloatingLayer.js
enyo.kind({
name: "enyo.FloatingLayer",
create: function() {
this.inherited(arguments), this.setParent(null);
},
render: function() {
return this.parentNode = document.body, this.inherited(arguments);
},
generateInnerHtml: function() {
return "";
},
beforeChildRender: function() {
this.hasNode() || this.render();
},
teardownChildren: function() {}
}), enyo.floatingLayer = new enyo.FloatingLayer;
// Popup.js
enyo.kind({
name: "enyo.Popup",
classes: "enyo-popup enyo-no-touch-action",
published: {
modal: !1,
autoDismiss: !0,
floating: !1,
centered: !1
},
showing: !1,
handlers: {
ondown: "down",
onkeydown: "keydown",
ondragstart: "dragstart",
onfocus: "focus",
onblur: "blur",
onRequestShow: "requestShow",
onRequestHide: "requestHide"
},
captureEvents: !0,
events: {
onShow: "",
onHide: ""
},
tools: [ {
kind: "Signals",
onKeydown: "keydown"
} ],
create: function() {
this.inherited(arguments), this.canGenerate = !this.floating;
},
render: function() {
this.floating && (enyo.floatingLayer.hasNode() || enyo.floatingLayer.render(), this.parentNode = enyo.floatingLayer.hasNode()), this.inherited(arguments);
},
destroy: function() {
this.showing && this.release(), this.inherited(arguments);
},
reflow: function() {
this.updatePosition(), this.inherited(arguments);
},
calcViewportSize: function() {
if (window.innerWidth) return {
width: window.innerWidth,
height: window.innerHeight
};
var e = document.documentElement;
return {
width: e.offsetWidth,
height: e.offsetHeight
};
},
updatePosition: function() {
var e = this.calcViewportSize(), t = this.getBounds();
if (this.targetPosition) {
var n = this.targetPosition;
typeof n.left == "number" ? n.left + t.width > e.width ? (n.left - t.width >= 0 ? n.right = e.width - n.left : n.right = 0, n.left = null) : n.right = null : typeof n.right == "number" && (n.right + t.width > e.width ? (n.right - t.width >= 0 ? n.left = e.width - n.right : n.left = 0, n.right = null) : n.left = null), typeof n.top == "number" ? n.top + t.height > e.height ? (n.top - t.height >= 0 ? n.bottom = e.height - n.top : n.bottom = 0, n.top = null) : n.bottom = null : typeof n.bottom == "number" && (n.bottom + t.height > e.height ? (n.bottom - t.height >= 0 ? n.top = e.height - n.bottom : n.top = 0, n.bottom = null) : n.top = null), this.addStyles("left: " + (n.left !== null ? n.left + "px" : "initial") + "; right: " + (n.right !== null ? n.right + "px" : "initial") + "; top: " + (n.top !== null ? n.top + "px" : "initial") + "; bottom: " + (n.bottom !== null ? n.bottom + "px" : "initial") + ";");
} else this.centered && this.addStyles("top: " + Math.max((e.height - t.height) / 2, 0) + "px; left: " + Math.max((e.width - t.width) / 2, 0) + "px;");
},
showingChanged: function() {
this.floating && this.showing && !this.hasNode() && this.render();
if (this.centered || this.targetPosition) this.applyStyle("visibility", "hidden"), this.addStyles("top: 0px; left: 0px; right: initial; bottom: initial;");
this.inherited(arguments), this.showing ? (this.resized(), this.captureEvents && this.capture()) : this.captureEvents && this.release(), (this.centered || this.targetPosition) && this.applyStyle("visibility", null), this.hasNode() && this[this.showing ? "doShow" : "doHide"]();
},
capture: function() {
enyo.dispatcher.capture(this, !this.modal);
},
release: function() {
enyo.dispatcher.release();
},
down: function(e, t) {
this.downEvent = t, this.modal && !t.dispatchTarget.isDescendantOf(this) && t.preventDefault();
},
tap: function(e, t) {
if (this.autoDismiss && !t.dispatchTarget.isDescendantOf(this) && this.downEvent && !this.downEvent.dispatchTarget.isDescendantOf(this)) return this.downEvent = null, this.hide(), !0;
},
dragstart: function(e, t) {
var n = t.dispatchTarget === this || t.dispatchTarget.isDescendantOf(this);
return e.autoDismiss && !n && e.setShowing(!1), !0;
},
keydown: function(e, t) {
this.showing && this.autoDismiss && t.keyCode == 27 && this.hide();
},
blur: function(e, t) {
t.dispatchTarget.isDescendantOf(this) && (this.lastFocus = t.originator);
},
focus: function(e, t) {
var n = t.dispatchTarget;
if (this.modal && !n.isDescendantOf(this)) {
n.hasNode() && n.node.blur();
var r = this.lastFocus && this.lastFocus.hasNode() || this.hasNode();
r && r.focus();
}
},
requestShow: function(e, t) {
return this.show(), !0;
},
requestHide: function(e, t) {
return this.hide(), !0;
},
showAtEvent: function(e, t) {
var n = {
left: e.centerX || e.clientX || e.pageX,
top: e.centerY || e.clientY || e.pageY
};
t && (n.left += t.left || 0, n.top += t.top || 0), this.showAtPosition(n);
},
showAtPosition: function(e) {
this.targetPosition = e, this.show();
}
});
// Selection.js
enyo.kind({
name: "enyo.Selection",
kind: enyo.Component,
published: {
multi: !1
},
events: {
onSelect: "",
onDeselect: "",
onChange: ""
},
create: function() {
this.clear(), this.inherited(arguments);
},
multiChanged: function() {
this.multi || this.clear(), this.doChange();
},
highlander: function(e) {
this.multi || this.deselect(this.lastSelected);
},
clear: function() {
this.selected = {};
},
isSelected: function(e) {
return this.selected[e];
},
setByKey: function(e, t, n) {
if (t) this.selected[e] = n || !0, this.lastSelected = e, this.doSelect({
key: e,
data: this.selected[e]
}); else {
var r = this.isSelected(e);
delete this.selected[e], this.doDeselect({
key: e,
data: r
});
}
this.doChange();
},
deselect: function(e) {
this.isSelected(e) && this.setByKey(e, !1);
},
select: function(e, t) {
this.multi ? this.setByKey(e, !this.isSelected(e), t) : this.isSelected(e) || (this.highlander(), this.setByKey(e, !0, t));
},
toggle: function(e, t) {
!this.multi && this.lastSelected != e && this.deselect(this.lastSelected), this.setByKey(e, !this.isSelected(e), t);
},
getSelected: function() {
return this.selected;
},
remove: function(e) {
var t = {};
for (var n in this.selected) n < e ? t[n] = this.selected[n] : n > e && (t[n - 1] = this.selected[n]);
this.selected = t;
}
});
| webOS-ports/org.webosports.app.pdf | tools/build/enyo.js | JavaScript | gpl-3.0 | 134,137 |
/*!
* jquery.inputmask.phone.extensions.js
* http://github.com/RobinHerbots/jquery.inputmask
* Copyright (c) 2010 - 2014 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 3.1.46
*/
;!function(a){"function"==typeof define&&define.amd?define(["jquery","./jquery.inputmask"],a):a(jQuery)}(function(a){return a.extend(a.inputmask.defaults.aliases,{phone:{url:"phone-codes/phone-codes.js",maskInit:"+pp(pp)pppppppp",countrycode:"",mask:function(b){b.definitions={p:{validator:function(){return !1},cardinality:1},"#":{validator:"[0-9]",cardinality:1}};var c=[];return a.ajax({url:b.url,async:!1,dataType:"json",success:function(d){c=d},error:function(f,d,e){alert(e+" - "+b.url)}}),c=c.sort(function(e,d){return(e.mask||e)<(d.mask||d)?-1:1}),""!=b.countrycode&&(b.maskInit="+"+b.countrycode+b.maskInit.substring(3)),c.splice(0,0,b.maskInit),c},nojumps:!0,nojumpsThreshold:1,onBeforeMask:function(d,c){var b=d.replace(/^0/g,"");return(b.indexOf(c.countrycode)>1||-1==b.indexOf(c.countrycode))&&(b="+"+c.countrycode+b),b}},phonebe:{alias:"phone",url:"phone-codes/phone-be.js",countrycode:"32",nojumpsThreshold:4}}),a.fn.inputmask}); | tholu/cdnjs | ajax/libs/jquery.inputmask/3.1.46/inputmask/jquery.inputmask.phone.extensions.min.js | JavaScript | mit | 1,186 |
require([
// Application.
"app",
// Main Router.
"router"
],
function(app, Router) {
// Define your master router on the application namespace and trigger all
// navigation from this instance.
app.router = new Router();
// Trigger the initial route and enable HTML5 History API support, set the
// root folder to '/' by default. Change in app.js.
Backbone.history.start({ pushState: true, root: app.root });
// All navigation that is relative should be passed through the navigate
// method, to be processed by the router. If the link has a `data-bypass`
// attribute, bypass the delegation completely.
$(document).on("click", "a[href]:not([data-bypass])", function(evt) {
// Get the absolute anchor href.
var href = { prop: $(this).prop("href"), attr: $(this).attr("href") };
// Get the absolute root.
var root = location.protocol + "//" + location.host + app.root;
// Ensure the root is part of the anchor href, meaning it's relative.
if (href.prop.slice(0, root.length) === root) {
// Stop the default event to ensure the link will not cause a page
// refresh.
evt.preventDefault();
// `Backbone.history.navigate` is sufficient for all Routers and will
// trigger the correct events. The Router's internal `navigate` method
// calls this anyways. The fragment is sliced from the root.
Backbone.history.navigate(href.attr, true);
}
});
});
| sethwhitaker/backbone-boilerplate | www/app/main.js | JavaScript | mit | 1,452 |
var win = Titanium.UI.currentWindow;
// make a transparent view that obscures another view (sits on top)
// but turn off touches against the view so that it won't explicitly
// handle any interaction events against it. this means that the
// other view in the hiearchry should instead receive the touch event
// which is view2.
var view1 = Ti.UI.createView({
width:200,
height:200,
touchEnabled:false
});
var view2 = Ti.UI.createView({
width:200,
height:200,
borderRadius:10,
backgroundColor:'purple'
});
var label = Ti.UI.createLabel({
text:'Click on me',
color:'white',
font:{fontSize:15,fontWeight:'bold'},
width:'auto',
height:'auto'
});
view2.add(label);
win.add(view2);
win.add(view1);
var l = Ti.UI.createLabel({
text:'click on box',
width:300,
height:'auto',
top:10,
font:{fontSize:13}
});
win.add(l);
var l2 = Ti.UI.createLabel({
text:'click on label',
width:300,
height:'auto',
top:25,
font:{fontSize:13}
});
win.add(l2);
view2.addEventListener('click',function()
{
l.text = "You were able to click on the box. Good!";
setTimeout(function()
{
l.text = "click on box";
},1000);
});
label.addEventListener('click',function()
{
l2.text = "You were able to click on the label. Good!";
setTimeout(function()
{
l2.text = "click on label";
},1000);
});
| formalin14/titanium_mobile | demos/SmokeTest/Resources/examples/view_event_interaction.js | JavaScript | apache-2.0 | 1,308 |
'use strict';
var sendVerificationEmail = function(req, res, options) {
req.app.utility.sendmail(req, res, {
from: req.app.config.smtp.from.name +' <'+ req.app.config.smtp.from.address +'>',
to: options.email,
subject: 'Verify Your '+ req.app.config.projectName +' Account',
textPath: 'account/verification/email-text',
htmlPath: 'account/verification/email-html',
locals: {
verifyURL: req.protocol +'://'+ req.headers.host +'/account/verification/' + options.verificationToken + '/',
projectName: req.app.config.projectName
},
success: function() {
options.onSuccess();
},
error: function(err) {
options.onError(err);
}
});
};
exports.init = function(req, res, next){
if (req.user.roles.account.isVerified === 'yes') {
return res.redirect(req.user.defaultReturnUrl());
}
var workflow = req.app.utility.workflow(req, res);
workflow.on('renderPage', function() {
req.app.db.models.User.findById(req.user.id, 'email').exec(function(err, user) {
if (err) {
return next(err);
}
res.render('account/verification/index', {
data: {
user: JSON.stringify(user)
}
});
});
});
workflow.on('generateTokenOrRender', function() {
if (req.user.roles.account.verificationToken !== '') {
return workflow.emit('renderPage');
}
workflow.emit('generateToken');
});
workflow.on('generateToken', function() {
var crypto = require('crypto');
crypto.randomBytes(21, function(err, buf) {
if (err) {
return next(err);
}
var token = buf.toString('hex');
req.app.db.models.User.encryptPassword(token, function(err, hash) {
if (err) {
return next(err);
}
workflow.emit('patchAccount', token, hash);
});
});
});
workflow.on('patchAccount', function(token, hash) {
var fieldsToSet = { verificationToken: hash };
req.app.db.models.Account.findByIdAndUpdate(req.user.roles.account.id, fieldsToSet, function(err, account) {
if (err) {
return next(err);
}
sendVerificationEmail(req, res, {
email: req.user.email,
verificationToken: token,
onSuccess: function() {
return workflow.emit('renderPage');
},
onError: function(err) {
return next(err);
}
});
});
});
workflow.emit('generateTokenOrRender');
};
exports.resendVerification = function(req, res, next){
if (req.user.roles.account.isVerified === 'yes') {
return res.redirect(req.user.defaultReturnUrl());
}
var workflow = req.app.utility.workflow(req, res);
workflow.on('validate', function() {
if (!req.body.email) {
workflow.outcome.errfor.email = 'required';
}
else if (!/^[a-zA-Z0-9\-\_\.\+]+@[a-zA-Z0-9\-\_\.]+\.[a-zA-Z0-9\-\_]+$/.test(req.body.email)) {
workflow.outcome.errfor.email = 'invalid email format';
}
if (workflow.hasErrors()) {
return workflow.emit('response');
}
workflow.emit('duplicateEmailCheck');
});
workflow.on('duplicateEmailCheck', function() {
req.app.db.models.User.findOne({ email: req.body.email.toLowerCase(), _id: { $ne: req.user.id } }, function(err, user) {
if (err) {
return workflow.emit('exception', err);
}
if (user) {
workflow.outcome.errfor.email = 'email already taken';
return workflow.emit('response');
}
workflow.emit('patchUser');
});
});
workflow.on('patchUser', function() {
var fieldsToSet = { email: req.body.email.toLowerCase() };
req.app.db.models.User.findByIdAndUpdate(req.user.id, fieldsToSet, function(err, user) {
if (err) {
return workflow.emit('exception', err);
}
workflow.user = user;
workflow.emit('generateToken');
});
});
workflow.on('generateToken', function() {
var crypto = require('crypto');
crypto.randomBytes(21, function(err, buf) {
if (err) {
return next(err);
}
var token = buf.toString('hex');
req.app.db.models.User.encryptPassword(token, function(err, hash) {
if (err) {
return next(err);
}
workflow.emit('patchAccount', token, hash);
});
});
});
workflow.on('patchAccount', function(token, hash) {
var fieldsToSet = { verificationToken: hash };
req.app.db.models.Account.findByIdAndUpdate(req.user.roles.account.id, fieldsToSet, function(err, account) {
if (err) {
return workflow.emit('exception', err);
}
sendVerificationEmail(req, res, {
email: workflow.user.email,
verificationToken: token,
onSuccess: function() {
workflow.emit('response');
},
onError: function(err) {
workflow.outcome.errors.push('Error Sending: '+ err);
workflow.emit('response');
}
});
});
});
workflow.emit('validate');
};
exports.verify = function(req, res, next){
req.app.db.models.User.validatePassword(req.params.token, req.user.roles.account.verificationToken, function(err, isValid) {
if (!isValid) {
return res.redirect(req.user.defaultReturnUrl());
}
var fieldsToSet = { isVerified: 'yes', verificationToken: '' };
req.app.db.models.Account.findByIdAndUpdate(req.user.roles.account._id, fieldsToSet, function(err, account) {
if (err) {
return next(err);
}
return res.redirect(req.user.defaultReturnUrl());
});
});
};
| pwithers/agrippa | views/app/verification/index.js | JavaScript | mit | 5,554 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var __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 __());
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { CompilerInjectable } from '../injectable';
import { getHtmlTagDefinition } from './html_tags';
import { DEFAULT_INTERPOLATION_CONFIG } from './interpolation_config';
import { Parser } from './parser';
export { ParseTreeResult, TreeError } from './parser';
export var HtmlParser = (function (_super) {
__extends(HtmlParser, _super);
function HtmlParser() {
_super.call(this, getHtmlTagDefinition);
}
/**
* @param {?} source
* @param {?} url
* @param {?=} parseExpansionForms
* @param {?=} interpolationConfig
* @return {?}
*/
HtmlParser.prototype.parse = function (source, url, parseExpansionForms, interpolationConfig) {
if (parseExpansionForms === void 0) { parseExpansionForms = false; }
if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
return _super.prototype.parse.call(this, source, url, parseExpansionForms, interpolationConfig);
};
HtmlParser = __decorate([
CompilerInjectable(),
__metadata('design:paramtypes', [])
], HtmlParser);
return HtmlParser;
}(Parser));
//# sourceMappingURL=html_parser.js.map | mo-norant/FinHeartBel | website/node_modules/@angular/compiler/src/ml_parser/html_parser.js | JavaScript | gpl-3.0 | 2,386 |
// Copyright 2012 Google Inc. All Rights Reserved.
/**
* @fileoverview Context information about nodes in their nodeset.
*/
goog.provide('wgxpath.NodeSet');
goog.require('goog.dom');
goog.require('wgxpath.Node');
/**
* A set of nodes sorted by their prefix order in the document.
*
* @constructor
*/
wgxpath.NodeSet = function() {
// In violation of standard Closure practice, we initialize properties to
// immutable constants in the constructor instead of on the prototype,
// because we have empirically measured better performance by doing so.
/**
* A pointer to the first node in the linked list.
*
* @private
* @type {wgxpath.NodeSet.Entry_}
*/
this.first_ = null;
/**
* A pointer to the last node in the linked list.
*
* @private
* @type {wgxpath.NodeSet.Entry_}
*/
this.last_ = null;
/**
* Length of the linked list.
*
* @private
* @type {number}
*/
this.length_ = 0;
};
/**
* A entry for a node in a linked list
*
* @param {!wgxpath.Node} node The node to be added.
* @constructor
* @private
*/
wgxpath.NodeSet.Entry_ = function(node) {
// In violation of standard Closure practice, we initialize properties to
// immutable constants in the constructor instead of on the prototype,
// because we have empirically measured better performance by doing so.
/**
* @type {!wgxpath.Node}
*/
this.node = node;
/**
* @type {wgxpath.NodeSet.Entry_}
*/
this.prev = null;
/**
* @type {wgxpath.NodeSet.Entry_}
*/
this.next = null;
};
/**
* Merges two nodesets, removing duplicates. This function may modify both
* nodesets, and will return a reference to one of the two.
*
* <p> Note: We assume that the two nodesets are already sorted in DOM order.
*
* @param {!wgxpath.NodeSet} a The first nodeset.
* @param {!wgxpath.NodeSet} b The second nodeset.
* @return {!wgxpath.NodeSet} The merged nodeset.
*/
wgxpath.NodeSet.merge = function(a, b) {
if (!a.first_) {
return b;
} else if (!b.first_) {
return a;
}
var aCurr = a.first_;
var bCurr = b.first_;
var merged = a, tail = null, next = null, length = 0;
while (aCurr && bCurr) {
if (wgxpath.Node.equal(aCurr.node, bCurr.node)) {
next = aCurr;
aCurr = aCurr.next;
bCurr = bCurr.next;
} else {
var compareResult = goog.dom.compareNodeOrder(
/** @type {!Node} */ (aCurr.node),
/** @type {!Node} */ (bCurr.node));
if (compareResult > 0) {
next = bCurr;
bCurr = bCurr.next;
} else {
next = aCurr;
aCurr = aCurr.next;
}
}
next.prev = tail;
if (tail) {
tail.next = next;
} else {
merged.first_ = next;
}
tail = next;
length++;
}
next = aCurr || bCurr;
while (next) {
next.prev = tail;
tail.next = next;
tail = next;
length++;
next = next.next;
}
merged.last_ = tail;
merged.length_ = length;
return merged;
};
/**
* Prepends a node to this nodeset.
*
* @param {!wgxpath.Node} node The node to be added.
*/
wgxpath.NodeSet.prototype.unshift = function(node) {
var entry = new wgxpath.NodeSet.Entry_(node);
entry.next = this.first_;
if (!this.last_) {
this.first_ = this.last_ = entry;
} else {
this.first_.prev = entry;
}
this.first_ = entry;
this.length_++;
};
/**
* Adds a node to this nodeset.
*
* @param {!wgxpath.Node} node The node to be added.
*/
wgxpath.NodeSet.prototype.add = function(node) {
var entry = new wgxpath.NodeSet.Entry_(node);
entry.prev = this.last_;
if (!this.first_) {
this.first_ = this.last_ = entry;
} else {
this.last_.next = entry;
}
this.last_ = entry;
this.length_++;
};
/**
* Returns the first node of the nodeset.
*
* @return {?wgxpath.Node} The first node of the nodeset
if the nodeset is non-empty;
* otherwise null.
*/
wgxpath.NodeSet.prototype.getFirst = function() {
var first = this.first_;
if (first) {
return first.node;
} else {
return null;
}
};
/**
* Return the length of this nodeset.
*
* @return {number} The length of the nodeset.
*/
wgxpath.NodeSet.prototype.getLength = function() {
return this.length_;
};
/**
* Returns the string representation of this nodeset.
*
* @return {string} The string representation of this nodeset.
*/
wgxpath.NodeSet.prototype.string = function() {
var node = this.getFirst();
return node ? wgxpath.Node.getValueAsString(node) : '';
};
/**
* Returns the number representation of this nodeset.
*
* @return {number} The number representation of this nodeset.
*/
wgxpath.NodeSet.prototype.number = function() {
return +this.string();
};
/**
* Returns an iterator over this nodeset. Once this iterator is made, DO NOT
* add to this nodeset until the iterator is done.
*
* @param {boolean=} opt_reverse Whether to iterate right to left or vice versa.
* @return {!wgxpath.NodeSet.Iterator} An iterator over the nodes.
*/
wgxpath.NodeSet.prototype.iterator = function(opt_reverse) {
return new wgxpath.NodeSet.Iterator(this, !!opt_reverse);
};
/**
* An iterator over the nodes of this nodeset.
*
* @param {!wgxpath.NodeSet} nodeset The nodeset to be iterated over.
* @param {boolean} reverse Whether to iterate in ascending or descending
* order.
* @constructor
*/
wgxpath.NodeSet.Iterator = function(nodeset, reverse) {
// In violation of standard Closure practice, we initialize properties to
// immutable constants in the constructor instead of on the prototype,
// because we have empirically measured better performance by doing so.
/**
* @type {!wgxpath.NodeSet}
* @private
*/
this.nodeset_ = nodeset;
/**
* @type {boolean}
* @private
*/
this.reverse_ = reverse;
/**
* @type {wgxpath.NodeSet.Entry_}
* @private
*/
this.current_ = reverse ? nodeset.last_ : nodeset.first_;
/**
* @type {wgxpath.NodeSet.Entry_}
* @private
*/
this.lastReturned_ = null;
};
/**
* Returns the next value of the iteration or null if passes the end.
*
* @return {?wgxpath.Node} The next node from this iterator.
*/
wgxpath.NodeSet.Iterator.prototype.next = function() {
var current = this.current_;
if (current == null) {
return null;
} else {
var lastReturned = this.lastReturned_ = current;
if (this.reverse_) {
this.current_ = current.prev;
} else {
this.current_ = current.next;
}
return lastReturned.node;
}
};
/**
* Deletes the last node that was returned from this iterator.
*/
wgxpath.NodeSet.Iterator.prototype.remove = function() {
var nodeset = this.nodeset_;
var entry = this.lastReturned_;
if (!entry) {
throw Error('Next must be called at least once before remove.');
}
var prev = entry.prev;
var next = entry.next;
// Modify the pointers of prev and next
if (prev) {
prev.next = next;
} else {
// If there was no prev node entry must've been first_, so update first_.
nodeset.first_ = next;
}
if (next) {
next.prev = prev;
} else {
// If there was no prev node entry must've been last_, so update last_.
nodeset.last_ = prev;
}
nodeset.length_--;
this.lastReturned_ = null;
};
| thanhpete/selenium | third_party/js/wgxpath/nodeset.js | JavaScript | apache-2.0 | 7,271 |
/**
* Satellizer
* (c) 2014 Sahat Yalkabov
* License: MIT
*/
(function(window, angular, undefined) {
'use strict';
angular.module('satellizer', [])
.constant('satellizer.config', {
loginOnSignup: true,
loginRedirect: '/',
logoutRedirect: '/',
signupRedirect: '/login',
loginUrl: '/auth/login',
signupUrl: '/auth/signup',
loginRoute: '/login',
signupRoute: '/signup',
tokenName: 'token',
tokenPrefix: 'satellizer',
unlinkUrl: '/auth/unlink/',
authHeader: 'Authorization',
providers: {
google: {
url: '/auth/google',
authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',
redirectUri: currentUrl(),
scope: ['profile', 'email'],
scopePrefix: 'openid',
scopeDelimiter: ' ',
requiredUrlParams: ['scope'],
optionalUrlParams: ['display'],
display: 'popup',
type: '2.0',
popupOptions: { width: 452, height: 633 }
},
facebook: {
url: '/auth/facebook',
authorizationEndpoint: 'https://www.facebook.com/dialog/oauth',
redirectUri: currentUrl() + '/',
scope: ['email'],
scopeDelimiter: ',',
requiredUrlParams: ['display', 'scope'],
display: 'popup',
type: '2.0',
popupOptions: { width: 481, height: 269 }
},
linkedin: {
url: '/auth/linkedin',
authorizationEndpoint: 'https://www.linkedin.com/uas/oauth2/authorization',
redirectUri: currentUrl(),
requiredUrlParams: ['state'],
scope: ['r_emailaddress'],
scopeDelimiter: ' ',
state: 'STATE',
type: '2.0',
popupOptions: { width: 527, height: 582 }
},
github: {
url: '/auth/github',
authorizationEndpoint: 'https://github.com/login/oauth/authorize',
redirectUri: currentUrl(),
scope: [],
scopeDelimiter: ' ',
type: '2.0',
popupOptions: { width: 1020, height: 618 }
},
yahoo: {
url: '/auth/yahoo',
authorizationEndpoint: 'https://api.login.yahoo.com/oauth2/request_auth',
redirectUri: currentUrl(),
scope: [],
scopeDelimiter: ',',
type: '2.0',
popupOptions: { width: 559, height: 519 }
},
twitter: {
url: '/auth/twitter',
type: '1.0',
popupOptions: { width: 495, height: 645 }
}
}
})
.provider('$auth', ['satellizer.config', function(config) {
Object.defineProperties(this, {
logoutRedirect: {
get: function() { return config.logoutRedirect; },
set: function(value) { config.logoutRedirect = value; }
},
loginRedirect: {
set: function(value) { config.loginRedirect = value; },
get: function() { return config.loginRedirect; }
},
signupRedirect: {
get: function() { return config.signupRedirect; },
set: function(value) { config.signupRedirect = value; }
},
loginOnSignup: {
get: function() { return config.loginOnSignup; },
set: function(value) { config.loginOnSignup = value; }
},
loginUrl: {
get: function() { return config.loginUrl; },
set: function(value) { config.loginUrl = value; }
},
signupUrl: {
get: function() { return config.signupUrl; },
set: function(value) { config.signupUrl = value; }
},
loginRoute: {
get: function() { return config.loginRoute; },
set: function(value) { config.loginRoute = value; }
},
signupRoute: {
get: function() { return config.signupRoute; },
set: function(value) { config.signupRoute = value; }
},
tokenName: {
get: function() { return config.tokenName; },
set: function(value) { config.tokenName = value; }
},
tokenPrefix: {
get: function() { return config.tokenPrefix; },
set: function(value) { config.tokenPrefix = value; }
},
unlinkUrl: {
get: function() { return config.unlinkUrl; },
set: function(value) { config.unlinkUrl = value; }
},
authHeader: {
get: function() { return config.authHeader; },
set: function(value) { config.authHeader = value; }
}
});
angular.forEach(Object.keys(config.providers), function(provider) {
this[provider] = function(params) {
return angular.extend(config.providers[provider], params);
};
}, this);
var oauth = function(params) {
config.providers[params.name] = config.providers[params.name] || {};
angular.extend(config.providers[params.name], params);
};
this.oauth1 = function(params) {
oauth(params);
config.providers[params.name].type = '1.0';
};
this.oauth2 = function(params) {
oauth(params);
config.providers[params.name].type = '2.0';
};
this.$get = [
'$q',
'satellizer.shared',
'satellizer.local',
'satellizer.oauth',
function($q, shared, local, oauth) {
var $auth = {};
$auth.authenticate = function(name, userData) {
return oauth.authenticate(name, false, userData);
};
$auth.login = function(user) {
return local.login(user);
};
$auth.signup = function(user) {
return local.signup(user);
};
$auth.logout = function() {
return shared.logout();
};
$auth.isAuthenticated = function() {
return shared.isAuthenticated();
};
$auth.link = function(name, userData) {
return oauth.authenticate(name, true, userData);
};
$auth.unlink = function(provider) {
return oauth.unlink(provider);
};
$auth.getToken = function() {
return shared.getToken();
};
$auth.getPayload = function() {
return shared.getPayload();
};
return $auth;
}];
}])
.factory('satellizer.shared', [
'$q',
'$window',
'$location',
'satellizer.config',
function($q, $window, $location, config) {
var shared = {};
shared.getToken = function() {
var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName;
return $window.localStorage[tokenName];
};
shared.getPayload = function() {
var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName;
var token = $window.localStorage[tokenName];
if (token && token.split('.').length === 3) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace('-', '+').replace('_', '/');
return JSON.parse($window.atob(base64));
}
};
shared.setToken = function(response, deferred, isLinking) {
var token = response.data[config.tokenName];
var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName;
if (!token) {
throw new Error('Expecting a token named "' + config.tokenName + '" but instead got: ' + JSON.stringify(response.data));
}
$window.localStorage[tokenName] = token;
if (config.loginRedirect && !isLinking) {
$location.path(config.loginRedirect);
}
deferred.resolve(response);
};
shared.isAuthenticated = function() {
var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName;
var token = $window.localStorage[tokenName];
if (token) {
if (token.split('.').length === 3) {
var base64Url = token.split('.')[1];
var base64 = base64Url.replace('-', '+').replace('_', '/');
var exp = JSON.parse($window.atob(base64)).exp;
return Math.round(new Date().getTime() / 1000) <= exp;
} else {
return true;
}
}
return false;
};
shared.logout = function() {
var deferred = $q.defer();
var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName;
delete $window.localStorage[tokenName];
if (config.logoutRedirect) {
$location.path(config.logoutRedirect);
}
deferred.resolve();
return deferred.promise;
};
return shared;
}])
.factory('satellizer.oauth', [
'$q',
'$http',
'satellizer.config',
'satellizer.shared',
'satellizer.Oauth1',
'satellizer.Oauth2',
function($q, $http, config, shared, Oauth1, Oauth2) {
var oauth = {};
oauth.authenticate = function(name, isLinking, userData) {
var deferred = $q.defer();
var provider = config.providers[name].type === '1.0' ? new Oauth1() : new Oauth2();
provider.open(config.providers[name], userData || {})
.then(function(response) {
shared.setToken(response, deferred, isLinking);
})
.then(null, function(response) {
deferred.reject(response);
});
return deferred.promise;
};
oauth.unlink = function(provider) {
return $http.get(config.unlinkUrl + provider);
};
return oauth;
}])
.factory('satellizer.local', [
'$q',
'$http',
'$location',
'satellizer.utils',
'satellizer.shared',
'satellizer.config',
function($q, $http, $location, utils, shared, config) {
var local = {};
local.login = function(user) {
var deferred = $q.defer();
$http.post(config.loginUrl, user)
.then(function(response) {
shared.setToken(response, deferred);
})
.then(null, function(response) {
deferred.reject(response);
});
return deferred.promise;
};
local.signup = function(user) {
var deferred = $q.defer();
$http.post(config.signupUrl, user)
.then(function(response) {
if (config.loginOnSignup) {
shared.setToken(response, deferred);
} else {
$location.path(config.signupRedirect);
deferred.resolve(response);
}
})
.then(null, function(response) {
deferred.reject(response);
});
return deferred.promise;
};
return local;
}])
.factory('satellizer.Oauth2', [
'$q',
'$http',
'satellizer.popup',
'satellizer.utils',
'satellizer.config',
function($q, $http, popup, utils, config) {
return function() {
var defaults = {
url: null,
name: null,
scope: null,
scopeDelimiter: null,
clientId: null,
redirectUri: null,
popupOptions: null,
authorizationEndpoint: null,
requiredUrlParams: null,
optionalUrlParams: null,
defaultUrlParams: ['response_type', 'client_id', 'redirect_uri'],
responseType: 'code'
};
var oauth2 = {};
oauth2.open = function(options, userData) {
angular.extend(defaults, options);
var deferred = $q.defer();
var url = oauth2.buildUrl();
popup.open(url, defaults.popupOptions)
.then(function(oauthData) {
// TODO: Change defaults name to options
if (defaults.responseType === 'token') {
// TODO: Check for access_token property after deferred is resolved instead of creating a fake response object
var response = { data: {} };
response.data[config.tokenName] = oauthData.access_token;
deferred.resolve(response);
} else {
oauth2.exchangeForToken(oauthData, userData)
.then(function(response) {
deferred.resolve(response);
})
.then(null, function(response) {
deferred.reject(response);
});
}
})
.then(null, function(error) {
deferred.reject(error);
});
return deferred.promise;
};
oauth2.exchangeForToken = function(oauthData, userData) {
var data = angular.extend({}, userData, {
code: oauthData.code,
clientId: defaults.clientId,
redirectUri: defaults.redirectUri
});
return $http.post(defaults.url, data);
};
oauth2.buildUrl = function() {
var baseUrl = defaults.authorizationEndpoint;
var qs = oauth2.buildQueryString();
return [baseUrl, qs].join('?');
};
oauth2.buildQueryString = function() {
var keyValuePairs = [];
var urlParams = ['defaultUrlParams', 'requiredUrlParams', 'optionalUrlParams'];
angular.forEach(urlParams, function(params) {
angular.forEach(defaults[params], function(paramName) {
var camelizedName = utils.camelCase(paramName);
var paramValue = defaults[camelizedName];
if (paramName === 'scope' && Array.isArray(paramValue)) {
paramValue = paramValue.join(defaults.scopeDelimiter);
if (defaults.scopePrefix) {
paramValue = [defaults.scopePrefix, paramValue].join(defaults.scopeDelimiter);
}
}
keyValuePairs.push([paramName, paramValue]);
});
});
return keyValuePairs.map(function(pair) {
return pair.join('=');
}).join('&');
};
return oauth2;
};
}])
.factory('satellizer.Oauth1', ['$q', '$http', 'satellizer.popup', function($q, $http, popup) {
return function() {
var defaults = {
url: null,
name: null,
popupOptions: null
};
var oauth1 = {};
oauth1.open = function(options, userData) {
angular.extend(defaults, options);
var deferred = $q.defer();
popup.open(defaults.url, defaults.popupOptions)
.then(function(response) {
oauth1.exchangeForToken(response, userData)
.then(function(response) {
deferred.resolve(response);
})
.then(null, function(response) {
deferred.reject(response);
});
})
.then(null, function(response) {
deferred.reject(response);
});
return deferred.promise;
};
oauth1.exchangeForToken = function(oauthData, userData) {
var data = angular.extend({}, userData, oauthData);
var qs = oauth1.buildQueryString(data);
return $http.get(defaults.url + '?' + qs);
};
oauth1.buildQueryString = function(obj) {
var str = [];
angular.forEach(obj, function(value, key) {
str.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return str.join('&');
};
return oauth1;
};
}])
.factory('satellizer.popup', [
'$q',
'$interval',
'$window',
'$location',
'satellizer.utils',
function($q, $interval, $window, $location, utils) {
var popupWindow = null;
var polling = null;
var popup = {};
popup.popupWindow = popupWindow;
popup.open = function(url, options) {
var deferred = $q.defer();
var optionsString = popup.stringifyOptions(popup.prepareOptions(options || {}));
popupWindow = window.open(url, '_blank', optionsString);
if (popupWindow && popupWindow.focus) {
popupWindow.focus();
}
popup.pollPopup(deferred);
return deferred.promise;
};
popup.pollPopup = function(deferred) {
polling = $interval(function() {
try {
if (popupWindow.document.domain === document.domain && (popupWindow.location.search || popupWindow.location.hash)) {
var queryParams = popupWindow.location.search.substring(1).replace(/\/$/, '');
var hashParams = popupWindow.location.hash.substring(1).replace(/\/$/, '');
var hash = utils.parseQueryString(hashParams);
var qs = utils.parseQueryString(queryParams);
angular.extend(qs, hash);
if (qs.error) {
deferred.reject({ error: qs.error });
} else {
deferred.resolve(qs);
}
popupWindow.close();
$interval.cancel(polling);
}
} catch (error) {}
if (popupWindow.closed) {
$interval.cancel(polling);
deferred.reject({ data: 'Authorization Failed' });
}
}, 35);
};
popup.prepareOptions = function(options) {
var width = options.width || 500;
var height = options.height || 500;
return angular.extend({
width: width,
height: height,
left: $window.screenX + (($window.outerWidth - width) / 2),
top: $window.screenY + (($window.outerHeight - height) / 2.5)
}, options);
};
popup.stringifyOptions = function(options) {
var parts = [];
angular.forEach(options, function(value, key) {
parts.push(key + '=' + value);
});
return parts.join(',');
};
return popup;
}])
.service('satellizer.utils', function() {
this.camelCase = function(name) {
return name.replace(/([\:\-\_]+(.))/g, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
});
};
this.parseQueryString = function(keyValue) {
var obj = {}, key, value;
angular.forEach((keyValue || '').split('&'), function(keyValue) {
if (keyValue) {
value = keyValue.split('=');
key = decodeURIComponent(value[0]);
obj[key] = angular.isDefined(value[1]) ? decodeURIComponent(value[1]) : true;
}
});
return obj;
};
})
.config(['$httpProvider', '$authProvider', 'satellizer.config', function($httpProvider, $authProvider, config) {
$httpProvider.interceptors.push(['$q', function($q) {
var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName;
return {
request: function(httpConfig) {
var token = localStorage.getItem(tokenName);
if (token) {
token = config.authHeader === 'Authorization' ? 'Bearer ' + token : token;
httpConfig.headers[config.authHeader] = token;
}
return httpConfig;
},
responseError: function(response) {
// TODO: check if coming from the same origin or pre-approved domain
if (response.status === 401) {
localStorage.removeItem(tokenName);
}
return $q.reject(response);
}
};
}]);
}]);
// Helper functions
function currentUrl() {
return window.location.origin || window.location.protocol + '//' + window.location.host;
}
})(window, window.angular);
// Base64.js polyfill (https://github.com/davidchambers/Base64.js/)
(function() {
var object = typeof exports != 'undefined' ? exports : this; // #8: web workers
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
function InvalidCharacterError(message) {
this.message = message;
}
InvalidCharacterError.prototype = new Error;
InvalidCharacterError.prototype.name = 'InvalidCharacterError';
// encoder
// [https://gist.github.com/999166] by [https://github.com/nignag]
object.btoa || (
object.btoa = function (input) {
var str = String(input);
for (
// initialize result and counter
var block, charCode, idx = 0, map = chars, output = '';
// if the next str index does not exist:
// change the mapping table to "="
// check if d has no fractional digits
str.charAt(idx | 0) || (map = '=', idx % 1);
// "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
output += map.charAt(63 & block >> 8 - idx % 1 * 8)
) {
charCode = str.charCodeAt(idx += 3/4);
if (charCode > 0xFF) {
throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
}
block = block << 8 | charCode;
}
return output;
});
// decoder
// [https://gist.github.com/1020396] by [https://github.com/atk]
object.atob || (
object.atob = function (input) {
var str = String(input).replace(/=+$/, '');
if (str.length % 4 == 1) {
throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (
// initialize result and counters
var bc = 0, bs, buffer, idx = 0, output = '';
// get next character
buffer = str.charAt(idx++);
// character found in table? initialize bit storage and add its ascii value;
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
// and if not first of each 4 characters,
// convert the first 8 bits to one ascii character
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
// try to find character in table (0-63, not found => -1)
buffer = chars.indexOf(buffer);
}
return output;
});
}());
| BobbieBel/cdnjs | ajax/libs/satellizer/0.8.3/satellizer.js | JavaScript | mit | 22,758 |
"use strict";
exports.__esModule = true;
var _getIterator2 = require("babel-runtime/core-js/get-iterator");
var _getIterator3 = _interopRequireDefault(_getIterator2);
exports.getStatementParent = getStatementParent;
exports.getOpposite = getOpposite;
exports.getCompletionRecords = getCompletionRecords;
exports.getSibling = getSibling;
exports.get = get;
exports._getKey = _getKey;
exports._getPattern = _getPattern;
exports.getBindingIdentifiers = getBindingIdentifiers;
exports.getOuterBindingIdentifiers = getOuterBindingIdentifiers;
var _index = require("./index");
var _index2 = _interopRequireDefault(_index);
var _babelTypes = require("babel-types");
var t = _interopRequireWildcard(_babelTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function getStatementParent() {
var path = this;
do {
if (!path.parentPath || Array.isArray(path.container) && path.isStatement()) {
break;
} else {
path = path.parentPath;
}
} while (path);
if (path && (path.isProgram() || path.isFile())) {
throw new Error("File/Program node, we can't possibly find a statement parent to this");
}
return path;
}
function getOpposite() {
if (this.key === "left") {
return this.getSibling("right");
} else if (this.key === "right") {
return this.getSibling("left");
}
}
function getCompletionRecords() {
var paths = [];
var add = function add(path) {
if (path) paths = paths.concat(path.getCompletionRecords());
};
if (this.isIfStatement()) {
add(this.get("consequent"));
add(this.get("alternate"));
} else if (this.isDoExpression() || this.isFor() || this.isWhile()) {
add(this.get("body"));
} else if (this.isProgram() || this.isBlockStatement()) {
add(this.get("body").pop());
} else if (this.isFunction()) {
return this.get("body").getCompletionRecords();
} else if (this.isTryStatement()) {
add(this.get("block"));
add(this.get("handler"));
add(this.get("finalizer"));
} else {
paths.push(this);
}
return paths;
}
function getSibling(key) {
return _index2.default.get({
parentPath: this.parentPath,
parent: this.parent,
container: this.container,
listKey: this.listKey,
key: key
});
}
function get(key, context) {
if (context === true) context = this.context;
var parts = key.split(".");
if (parts.length === 1) {
return this._getKey(key, context);
} else {
return this._getPattern(parts, context);
}
}
function _getKey(key, context) {
var _this = this;
var node = this.node;
var container = node[key];
if (Array.isArray(container)) {
return container.map(function (_, i) {
return _index2.default.get({
listKey: key,
parentPath: _this,
parent: node,
container: container,
key: i
}).setContext(context);
});
} else {
return _index2.default.get({
parentPath: this,
parent: node,
container: node,
key: key
}).setContext(context);
}
}
function _getPattern(parts, context) {
var path = this;
for (var _iterator = parts, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : (0, _getIterator3.default)(_iterator);;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var part = _ref;
if (part === ".") {
path = path.parentPath;
} else {
if (Array.isArray(path)) {
path = path[part];
} else {
path = path.get(part, context);
}
}
}
return path;
}
function getBindingIdentifiers(duplicates) {
return t.getBindingIdentifiers(this.node, duplicates);
}
function getOuterBindingIdentifiers(duplicates) {
return t.getOuterBindingIdentifiers(this.node, duplicates);
} | Nrupesh29/Web-Traffic-Visualizer | vizceral/node_modules/babel-traverse/lib/path/family.js | JavaScript | mit | 4,201 |
/* */
"format cjs";
/* eslint no-new-func: 0 */
"use strict";
require("./node");
var transform = module.exports = require("../transformation");
/**
* Add `options` and `version` to `babel` global.
*/
transform.options = require("../transformation/file/options");
transform.version = require("../../package").version;
/**
* Add `transform` api to `babel` global.
*/
transform.transform = transform;
/**
* Tranform and execute script, adding in inline sourcemaps.
*/
transform.run = function (code) {
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
opts.sourceMaps = "inline";
return new Function(transform(code, opts).code)();
};
/**
* Load scripts via xhr, and `transform` when complete (optional).
*/
transform.load = function (url, callback, opts, hold) {
if (opts === undefined) opts = {};
opts.filename = opts.filename || url;
var xhr = global.ActiveXObject ? new global.ActiveXObject("Microsoft.XMLHTTP") : new global.XMLHttpRequest();
xhr.open("GET", url, true);
if ("overrideMimeType" in xhr) xhr.overrideMimeType("text/plain");
/**
* When successfully loaded, transform (optional), and call `callback`.
*/
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) return;
var status = xhr.status;
if (status === 0 || status === 200) {
var param = [xhr.responseText, opts];
if (!hold) transform.run.apply(transform, param);
if (callback) callback(param);
} else {
throw new Error("Could not load " + url);
}
};
xhr.send(null);
};
/**
* Load and transform all scripts of `types`.
*
* @example
* <script type="module"></script>
*/
var runScripts = function runScripts() {
var scripts = [];
var types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"];
var index = 0;
/**
* Transform and execute script. Ensures correct load order.
*/
var exec = function exec() {
var param = scripts[index];
if (param instanceof Array) {
transform.run.apply(transform, param);
index++;
exec();
}
};
/**
* Load, transform, and execute all scripts.
*/
var run = function run(script, i) {
var opts = {};
if (script.src) {
transform.load(script.src, function (param) {
scripts[i] = param;
exec();
}, opts, true);
} else {
opts.filename = "embedded";
scripts[i] = [script.innerHTML, opts];
}
};
// Collect scripts with Babel `types`.
var _scripts = global.document.getElementsByTagName("script");
for (var i = 0; i < _scripts.length; ++i) {
var _script = _scripts[i];
if (types.indexOf(_script.type) >= 0) scripts.push(_script);
}
for (i in scripts) {
run(scripts[i], i);
}
exec();
};
/**
* Register load event to transform and execute scripts.
*/
if (global.addEventListener) {
global.addEventListener("DOMContentLoaded", runScripts, false);
} else if (global.attachEvent) {
global.attachEvent("onload", runScripts);
} | pauldijou/outdated | test/basic/jspm_packages/npm/[email protected]/lib/api/browser.js | JavaScript | apache-2.0 | 3,022 |
this is file 139 | edyhernandez/brand-knew-wordpress | wp-content/themes/socialimpact/node_modules/gulp-if/fixture/twohundred/file139.js | JavaScript | mit | 16 |
function bcmul (left_operand, right_operand, scale) {
// http://kevin.vanzonneveld.net
// + original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/)
// - depends on: _phpjs_shared_bc
// * example 1: bcmul(1, 2);
// * returns 1: 3
// @todo: implement these testcases
// bcscale(0);
//
// bcmath.test.result('bcmul', 1, '2', bcmul("1", "2"));
// bcmath.test.result('bcmul', 2, '-15', bcmul("-3", "5"));
// bcmath.test.result('bcmul', 3, '12193263111263526900', bcmul("1234567890", "9876543210"));
// bcmath.test.result('bcmul', 4, '3.75', bcmul("2.5", "1.5", 2));
// bcmath.test.result('bcmul', 5, '13008.1522', bcmul("5573.33", "2.334", 4));
var libbcmath = this._phpjs_shared_bc();
var first, second, result;
if (typeof scale === 'undefined') {
scale = libbcmath.scale;
}
scale = ((scale < 0) ? 0 : scale);
// create objects
first = libbcmath.bc_init_num();
second = libbcmath.bc_init_num();
result = libbcmath.bc_init_num();
first = libbcmath.php_str2num(left_operand.toString());
second = libbcmath.php_str2num(right_operand.toString());
result = libbcmath.bc_multiply(first, second, scale);
if (result.n_scale > scale) {
result.n_scale = scale;
}
return result.toString();
}
| montanaflynn/phpjs | functions/bc/bcmul.js | JavaScript | mit | 1,315 |
/**
* @author Steven A. Zahm
*/
// Use jQuery() instead of $()for WordPress compatibility with the included prototype js library which uses $()
// http://ipaulpro.com/blog/tutorials/2008/08/jquery-and-wordpress-getting-started/
// See http://chrismeller.com/using-jquery-in-wordpress
jQuery(document).ready(function($){
/*
* Hide the image loading spinner and show the image.
*/
$('.connections').cn_preloader({
delay:200,
imgSelector:'.cn-image img.photo, .cn-image img.logo',
beforeShow:function(){
$(this).closest('.cn-image img').css('visibility','hidden');
},
afterShow:function(){
//var image = $(this).closest('.cn-image');
//$(image).spin(false);
}
});
jQuery(function() {
jQuery('a.detailsbutton')
.css("cursor","pointer")
.attr("title","Click to show details.")
.click(function()
{
jQuery('.child-'+this.id).each(function(i, elem)
{
jQuery(elem).toggle(jQuery(elem).css('display') == 'none');
});
return false;
})
.toggle
(
function()
{
jQuery(this).html('Hide Details');
jQuery(this).attr("title","Click to hide details.")
},
function()
{
jQuery(this).html('Show Details');
jQuery(this).attr("title","Click to show details.")
}
);
//jQuery('tr[@class^=child-]').hide().children('td');
return false;
});
jQuery(function() {
jQuery('input#entry_type_0')
.click(function(){
jQuery('#family').slideUp();
jQuery('.namefield').slideDown();
jQuery('#contact_name').slideUp();
jQuery('.celebrate').slideDown();
jQuery('.celebrate-disabled').slideUp();
});
});
jQuery(function() {
jQuery('input#entry_type_1')
.click(function(){
jQuery('#family').slideUp();
jQuery('.namefield').slideUp();
jQuery('#contact_name').slideDown();
jQuery('.celebrate').slideUp();
jQuery('.celebrate-disabled').slideDown();
});
});
jQuery(function() {
jQuery('input#entry_type_2')
.click(function(){
jQuery('#family').slideDown();
jQuery('.namefield').slideUp();
jQuery('.celebrate').slideUp();
jQuery('.celebrate-disabled').slideDown();
});
});
jQuery(function() {
var $entryType = (jQuery('input[name^=entry_type]:checked').val());
switch ($entryType)
{
case 'individual':
jQuery('#family').slideUp();
jQuery('#contact_name').slideUp();
jQuery('.celebrate-disabled').slideUp();
break;
case 'organization':
jQuery('#family').slideUp();
jQuery('.namefield').slideUp();
jQuery('.celebrate').slideUp();
jQuery('.celebrate-disabled').slideDown();
break;
case 'family':
jQuery('.namefield').slideUp();
jQuery('.celebrate').slideUp();
jQuery('.celebrate-disabled').slideDown();
break;
}
});
/*
* Add relations to the family entry type.
*/
$('#add-relation').click(function() {
var template = (jQuery('#relation-template').text());
var d = new Date();
var token = Math.floor( Math.random() * d.getTime() );
template = template.replace(
new RegExp('::FIELD::', 'gi'),
token
);
$('#relations').append( '<div id="relation-row-' + token + '" class="relation" style="display: none;">' + template + '<a href="#" class="cn-remove cn-button button button-warning" data-type="relation" data-token="' + token + '">Remove</a>' + '</div>' );
$('#relation-row-' + token).slideDown();
/*
* Add jQuery Chosen to the family name and relation fields.
*/
$('.family-member-name, .family-member-relation').chosen();
return false
});
/*
* Add jQuery Chosen to the family name and relation fields.
*/
if ($.fn.chosen) {
$('.family-member-name, .family-member-relation').chosen();
}
$('a.cn-add.cn-button').click(function() {
var $this = $(this);
var type = $this.attr('data-type');
var container = '#' + $this.attr('data-container');
var id = '#' + type + '-template';
//console.log(id);
var template = $(id).text();
//console.log(template);
var d = new Date();
var token = Math.floor( Math.random() * d.getTime() );
template = template.replace(
new RegExp('::FIELD::', 'gi'),
token
);
//console.log(template);
//console.log(container);
$(container).append( '<div class="widget ' + type + '" id="' + type + '-row-' + token + '" style="display: none;">' + template + '</div>' );
$('#' + type + '-row-' + token).slideDown();
return false;
});
$('a.cn-remove.cn-button').live('click', function() {
var $this = $(this);
var token = $this.attr('data-token');
var type = $this.attr('data-type');
var id = '#' + type + '-row-' + token;
//alert(id);
$(id).slideUp('fast', function(){ $(this).remove(); });
return false;
});
/*
* Switching Visual/HTML Modes With TinyMCE
* http://www.keighl.com/2010/04/switching-visualhtml-modes-with-tinymce/
*/
jQuery('a#toggleBioEditor').click(
function() {
id = 'bio';
if (tinyMCE.get(id))
{
tinyMCE.execCommand('mceRemoveControl', false, id);
}
else
{
tinyMCE.execCommand('mceAddControl', false, id);
}
}
);
jQuery('a#toggleNoteEditor').click(
function() {
id = 'note';
if (tinyMCE.get(id))
{
tinyMCE.execCommand('mceRemoveControl', false, id);
}
else
{
tinyMCE.execCommand('mceAddControl', false, id);
}
}
);
/*
* Add the jQuery UI Datepicker to the date input fields.
*/
if ($.fn.datepicker) {
$('.datepicker').live('focus', function() {
$(this).datepicker({
changeMonth: true,
changeYear: true,
showOtherMonths: true,
selectOtherMonths: true,
yearRange: 'c-100:c+10'
});
});
}
/*
* Geocode the address
*/
$('a.geocode.button').live('click', function() {
var address = new Object();
var $this = $(this);
var lat;
var lng;
var uid = $this.attr('data-uid');
//console.log(uid);
address.line_1 = $('input[name=address\\[' + uid + '\\]\\[line_1\\]]').val();
address.line_2 = $('input[name=address\\[' + uid + '\\]\\[line_2\\]]').val();
address.line_3 = $('input[name=address\\[' + uid + '\\]\\[line_3\\]]').val();
address.city = $('input[name=address\\[' + uid + '\\]\\[city\\]]').val();
address.state = $('input[name=address\\[' + uid + '\\]\\[state\\]]').val();
address.zipcode = $('input[name=address\\[' + uid + '\\]\\[zipcode\\]]').val();
address.country = $('input[name=address\\[' + uid + '\\]\\[country\\]]').val();
//console.log(address);
$( '#map-' + uid ).fadeIn('slow' , function() {
$( '#map-' + uid ).goMap({
maptype: 'ROADMAP'/*,
latitude: 40.366502,
longitude: -75.887637,
zoom: 14*/
});
$.goMap.clearMarkers();
$.goMap.createMarker({
address: '\'' + address.line_1 + ', ' + address.city + ', ' + address.state + ', ' + address.zipcode + ', ' + '\'' , id: 'baseMarker' , draggable: true
});
$.goMap.setMap({ address: '\'' + address.line_1 + ', ' + address.city + ', ' + address.state + ', ' + address.zipcode + ', ' + '\'' , zoom: 18 });
$.goMap.createListener( {type:'marker', marker:'baseMarker'} , 'idle', function(event) {
var lat = event.latLng.lat();
var lng = event.latLng.lng();
console.log(lat);
console.log(lng);
$('input[name=address\\[' + uid + '\\]\\[latitude\\]]').val(lat);
$('input[name=address\\[' + uid + '\\]\\[longitude\\]]').val(lng);
});
$.goMap.createListener( {type:'marker', marker:'baseMarker'} , 'dragend', function(event) {
var lat = event.latLng.lat();
var lng = event.latLng.lng();
console.log(lat);
console.log(lng);
$('input[name=address\\[' + uid + '\\]\\[latitude\\]]').val(lat);
$('input[name=address\\[' + uid + '\\]\\[longitude\\]]').val(lng);
});
});
// There has to be a better way than setting a delay. I know I have to use a callback b/c the geocode is an asyn request.
setTimeout( function(){
setLatLngInfo(uid);
}, 1500)
return false;
});
function setLatLngInfo(uid)
{
var baseMarkerPosition = $( '#map-' + uid ).data('baseMarker').getPosition();
$('input[name=address\\[' + uid + '\\]\\[latitude\\]]').val( baseMarkerPosition.lat() );
$('input[name=address\\[' + uid + '\\]\\[longitude\\]]').val( baseMarkerPosition.lng() );
}
}); | mikenunes/atrevetepages | wp-content/plugins/connections/js/cn-admin.js | JavaScript | gpl-2.0 | 8,329 |
/**
* angular-strap
* @version v2.1.3 - 2014-11-06
* @link http://mgcrea.github.io/angular-strap
* @author Olivier Louvignes ([email protected])
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
'use strict';
angular.module('mgcrea.ngStrap.helpers.dateParser', [])
.provider('$dateParser', ["$localeProvider", function($localeProvider) {
// define a custom ParseDate object to use instead of native Date
// to avoid date values wrapping when setting date component values
function ParseDate() {
this.year = 1970;
this.month = 0;
this.day = 1;
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
this.milliseconds = 0;
}
ParseDate.prototype.setMilliseconds = function(value) { this.milliseconds = value; };
ParseDate.prototype.setSeconds = function(value) { this.seconds = value; };
ParseDate.prototype.setMinutes = function(value) { this.minutes = value; };
ParseDate.prototype.setHours = function(value) { this.hours = value; };
ParseDate.prototype.getHours = function() { return this.hours; };
ParseDate.prototype.setDate = function(value) { this.day = value; };
ParseDate.prototype.setMonth = function(value) { this.month = value; };
ParseDate.prototype.setFullYear = function(value) { this.year = value; };
ParseDate.prototype.fromDate = function(value) {
this.year = value.getFullYear();
this.month = value.getMonth();
this.day = value.getDate();
this.hours = value.getHours();
this.minutes = value.getMinutes();
this.seconds = value.getSeconds();
this.milliseconds = value.getMilliseconds();
return this;
};
ParseDate.prototype.toDate = function() {
return new Date(this.year, this.month, this.day, this.hours, this.minutes, this.seconds, this.milliseconds);
};
var proto = ParseDate.prototype;
function noop() {
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function indexOfCaseInsensitive(array, value) {
var len = array.length, str=value.toString().toLowerCase();
for (var i=0; i<len; i++) {
if (array[i].toLowerCase() === str) { return i; }
}
return -1; // Return -1 per the "Array.indexOf()" method.
}
var defaults = this.defaults = {
format: 'shortDate',
strict: false
};
this.$get = ["$locale", "dateFilter", function($locale, dateFilter) {
var DateParserFactory = function(config) {
var options = angular.extend({}, defaults, config);
var $dateParser = {};
var regExpMap = {
'sss' : '[0-9]{3}',
'ss' : '[0-5][0-9]',
's' : options.strict ? '[1-5]?[0-9]' : '[0-9]|[0-5][0-9]',
'mm' : '[0-5][0-9]',
'm' : options.strict ? '[1-5]?[0-9]' : '[0-9]|[0-5][0-9]',
'HH' : '[01][0-9]|2[0-3]',
'H' : options.strict ? '1?[0-9]|2[0-3]' : '[01]?[0-9]|2[0-3]',
'hh' : '[0][1-9]|[1][012]',
'h' : options.strict ? '[1-9]|1[012]' : '0?[1-9]|1[012]',
'a' : 'AM|PM',
'EEEE' : $locale.DATETIME_FORMATS.DAY.join('|'),
'EEE' : $locale.DATETIME_FORMATS.SHORTDAY.join('|'),
'dd' : '0[1-9]|[12][0-9]|3[01]',
'd' : options.strict ? '[1-9]|[1-2][0-9]|3[01]' : '0?[1-9]|[1-2][0-9]|3[01]',
'MMMM' : $locale.DATETIME_FORMATS.MONTH.join('|'),
'MMM' : $locale.DATETIME_FORMATS.SHORTMONTH.join('|'),
'MM' : '0[1-9]|1[012]',
'M' : options.strict ? '[1-9]|1[012]' : '0?[1-9]|1[012]',
'yyyy' : '[1]{1}[0-9]{3}|[2]{1}[0-9]{3}',
'yy' : '[0-9]{2}',
'y' : options.strict ? '-?(0|[1-9][0-9]{0,3})' : '-?0*[0-9]{1,4}',
};
var setFnMap = {
'sss' : proto.setMilliseconds,
'ss' : proto.setSeconds,
's' : proto.setSeconds,
'mm' : proto.setMinutes,
'm' : proto.setMinutes,
'HH' : proto.setHours,
'H' : proto.setHours,
'hh' : proto.setHours,
'h' : proto.setHours,
'EEEE' : noop,
'EEE' : noop,
'dd' : proto.setDate,
'd' : proto.setDate,
'a' : function(value) { var hours = this.getHours() % 12; return this.setHours(value.match(/pm/i) ? hours + 12 : hours); },
'MMMM' : function(value) { return this.setMonth(indexOfCaseInsensitive($locale.DATETIME_FORMATS.MONTH, value)); },
'MMM' : function(value) { return this.setMonth(indexOfCaseInsensitive($locale.DATETIME_FORMATS.SHORTMONTH, value)); },
'MM' : function(value) { return this.setMonth(1 * value - 1); },
'M' : function(value) { return this.setMonth(1 * value - 1); },
'yyyy' : proto.setFullYear,
'yy' : function(value) { return this.setFullYear(2000 + 1 * value); },
'y' : proto.setFullYear
};
var regex, setMap;
$dateParser.init = function() {
$dateParser.$format = $locale.DATETIME_FORMATS[options.format] || options.format;
regex = regExpForFormat($dateParser.$format);
setMap = setMapForFormat($dateParser.$format);
};
$dateParser.isValid = function(date) {
if(angular.isDate(date)) return !isNaN(date.getTime());
return regex.test(date);
};
$dateParser.parse = function(value, baseDate, format) {
if(angular.isDate(value)) value = dateFilter(value, format || $dateParser.$format);
var formatRegex = format ? regExpForFormat(format) : regex;
var formatSetMap = format ? setMapForFormat(format) : setMap;
var matches = formatRegex.exec(value);
if(!matches) return false;
// use custom ParseDate object to set parsed values
var date = baseDate && !isNaN(baseDate.getTime()) ? new ParseDate().fromDate(baseDate) : new ParseDate().fromDate(new Date(1970, 0, 1, 0));
for(var i = 0; i < matches.length - 1; i++) {
formatSetMap[i] && formatSetMap[i].call(date, matches[i+1]);
}
// convert back to native Date object
return date.toDate();
};
$dateParser.getDateForAttribute = function(key, value) {
var date;
if(value === 'today') {
var today = new Date();
date = new Date(today.getFullYear(), today.getMonth(), today.getDate() + (key === 'maxDate' ? 1 : 0), 0, 0, 0, (key === 'minDate' ? 0 : -1));
} else if(angular.isString(value) && value.match(/^".+"$/)) { // Support {{ dateObj }}
date = new Date(value.substr(1, value.length - 2));
} else if(isNumeric(value)) {
date = new Date(parseInt(value, 10));
} else if (angular.isString(value) && 0 === value.length) { // Reset date
date = key === 'minDate' ? -Infinity : +Infinity;
} else {
date = new Date(value);
}
return date;
};
$dateParser.getTimeForAttribute = function(key, value) {
var time;
if(value === 'now') {
time = new Date().setFullYear(1970, 0, 1);
} else if(angular.isString(value) && value.match(/^".+"$/)) {
time = new Date(value.substr(1, value.length - 2)).setFullYear(1970, 0, 1);
} else if(isNumeric(value)) {
time = new Date(parseInt(value, 10)).setFullYear(1970, 0, 1);
} else if (angular.isString(value) && 0 === value.length) { // Reset time
time = key === 'minTime' ? -Infinity : +Infinity;
} else {
time = $dateParser.parse(value, new Date(1970, 0, 1, 0));
}
return time;
};
// Private functions
function setMapForFormat(format) {
var keys = Object.keys(setFnMap), i;
var map = [], sortedMap = [];
// Map to setFn
var clonedFormat = format;
for(i = 0; i < keys.length; i++) {
if(format.split(keys[i]).length > 1) {
var index = clonedFormat.search(keys[i]);
format = format.split(keys[i]).join('');
if(setFnMap[keys[i]]) {
map[index] = setFnMap[keys[i]];
}
}
}
// Sort result map
angular.forEach(map, function(v) {
// conditional required since angular.forEach broke around v1.2.21
// related pr: https://github.com/angular/angular.js/pull/8525
if(v) sortedMap.push(v);
});
return sortedMap;
}
function escapeReservedSymbols(text) {
return text.replace(/\//g, '[\\/]').replace('/-/g', '[-]').replace(/\./g, '[.]').replace(/\\s/g, '[\\s]');
}
function regExpForFormat(format) {
var keys = Object.keys(regExpMap), i;
var re = format;
// Abstract replaces to avoid collisions
for(i = 0; i < keys.length; i++) {
re = re.split(keys[i]).join('${' + i + '}');
}
// Replace abstracted values
for(i = 0; i < keys.length; i++) {
re = re.split('${' + i + '}').join('(' + regExpMap[keys[i]] + ')');
}
format = escapeReservedSymbols(format);
return new RegExp('^' + re + '$', ['i']);
}
$dateParser.init();
return $dateParser;
};
return DateParserFactory;
}];
}]);
| tmthrgd/pagespeed-libraries-cdnjs | packages/angular-strap/2.1.3/modules/date-parser.js | JavaScript | mit | 9,192 |
/**
* tFunk for colours/compiler
*/
var tfunk = require("tfunk");
/**
* Lodash.clonedeep for deep cloning
*/
var cloneDeep = require("lodash.clonedeep");
/**
* opt-merger for option merging
*/
var merge = require("opt-merger");
/**
* Default configuration.
* Can be overridden in first constructor arg
*/
var defaults = {
/**
* Initial log level
*/
level: "info",
/**
* Prefix for logger
*/
prefix: "",
/**
* Available levels and their score
*/
levels: {
"trace": 100,
"debug": 200,
"warn": 300,
"info": 400,
"error": 500
},
/**
* Default prefixes
*/
prefixes: {
"trace": "[trace] ",
"debug": "{yellow:[debug]} ",
"info": "{cyan:[info]} ",
"warn": "{magenta:[warn]} ",
"error": "{red:[error]} "
},
/**
* Should easy log statement be prefixed with the level?
*/
useLevelPrefixes: false
};
/**
* @param {Object} config
* @constructor
*/
var Logger = function(config) {
if (!(this instanceof Logger)) {
return new Logger(config);
}
config = config || {};
this._mute = false;
this.config = merge.set({simple: true}).merge(defaults, config);
this.addLevelMethods(this.config.levels);
this.compiler = new tfunk.Compiler(this.config.custom || {}, this.config);
this._memo = {};
return this;
};
/**
* Set an option once
* @param path
* @param value
*/
Logger.prototype.setOnce = function (path, value) {
if (typeof this.config[path] !== "undefined") {
if (typeof this._memo[path] === "undefined") {
this._memo[path] = this.config[path];
}
this.config[path] = value;
}
return this;
};
/**
* Add convenience method such as
* logger.warn("msg")
* logger.error("msg")
* logger.info("msg")
*
* instead of
* logger.log("warn", "msg");
* @param items
*/
Logger.prototype.addLevelMethods = function (items) {
Object.keys(items).forEach(function (item) {
if (!this[item]) {
this[item] = function () {
var args = Array.prototype.slice.call(arguments);
this.log.apply(this, args);
return this;
}.bind(this, item);
}
}, this);
};
/**
* Reset the state of the logger.
* @returns {Logger}
*/
Logger.prototype.reset = function () {
this.setLevel(defaults.level)
.setLevelPrefixes(defaults.useLevelPrefixes)
.mute(false);
return this;
};
/**
* @param {String} level
* @returns {boolean}
*/
Logger.prototype.canLog = function (level) {
return this.config.levels[level] >= this.config.levels[this.config.level] && !this._mute;
};
/**
* Log to the console with prefix
* @param {String} level
* @param {String} msg
* @returns {Logger}
*/
Logger.prototype.log = function (level, msg) {
var args = Array.prototype.slice.call(arguments);
this.logOne(args, msg, level);
return this;
};
/**
* Set the log level
* @param {String} level
* @returns {Logger}
*/
Logger.prototype.setLevel = function (level) {
this.config.level = level;
return this;
};
/**
* @param {boolean} state
* @returns {Logger}
*/
Logger.prototype.setLevelPrefixes = function (state) {
this.config.useLevelPrefixes = state;
return this;
};
/**
* @param prefix
*/
Logger.prototype.setPrefix = function (prefix) {
if (typeof prefix === "string") {
this.compiler.prefix = this.compiler.compile(prefix, true);
}
if (typeof prefix === "function") {
this.compiler.prefix = prefix;
}
};
/**
* @param {String} level
* @param {String} msg
* @returns {Logger}
*/
Logger.prototype.unprefixed = function (level, msg) {
var args = Array.prototype.slice.call(arguments);
this.logOne(args, msg, level, true);
return this;
};
/**
* @param {Array} args
* @param {String} msg
* @param {String} level
* @param {boolean} [unprefixed]
* @returns {Logger}
*/
Logger.prototype.logOne = function (args, msg, level, unprefixed) {
if (!this.canLog(level)) {
return;
}
args = args.slice(2);
if (this.config.useLevelPrefixes && !unprefixed) {
msg = this.config.prefixes[level] + msg;
}
msg = this.compiler.compile(msg, unprefixed);
args.unshift(msg);
console.log.apply(console, args);
this.resetTemps();
return this;
};
/**
* Reset any temporary value
*/
Logger.prototype.resetTemps = function () {
Object.keys(this._memo).forEach(function (key) {
this.config[key] = this._memo[key];
}, this);
};
/**
* Mute the logger
*/
Logger.prototype.mute = function (bool) {
this._mute = bool;
return this;
};
/**
* Clone the instance to share setup
* @param opts
* @returns {Logger}
*/
Logger.prototype.clone = function (opts) {
var config = cloneDeep(this.config);
if (typeof opts === "function") {
config = opts(config) || {};
} else {
config = merge.set({simple: true}).merge(config, opts || {});
}
return new Logger(config);
};
module.exports.Logger = Logger;
module.exports.compile = tfunk;
| lokiiart/upali-mobile | www/frontend/node_modules/eazy-logger/index.js | JavaScript | gpl-3.0 | 5,199 |
$(function(){$("body").on("click",".page-scroll a",function(event){var $anchor=$(this);$("html, body").stop().animate({scrollTop:$($anchor.attr("href")).offset().top},1500,"easeInOutExpo");event.preventDefault()})});$(function(){$("body").on("input propertychange",".floating-label-form-group",function(e){$(this).toggleClass("floating-label-form-group-with-value",!!$(e.target).val())}).on("focus",".floating-label-form-group",function(){$(this).addClass("floating-label-form-group-with-focus")}).on("blur",".floating-label-form-group",function(){$(this).removeClass("floating-label-form-group-with-focus")})});$("body").scrollspy({target:".navbar-fixed-top"});$(".navbar-collapse ul li a").click(function(){$(".navbar-toggle:visible").click()});
| jonobr1/cdnjs | ajax/libs/startbootstrap-freelancer/1.0.5/js/freelancer.min.js | JavaScript | mit | 748 |
/*
* bootstrap-table - v1.10.1 - 2016-02-17
* https://github.com/wenzhixin/bootstrap-table
* Copyright (c) 2016 zhixin wen
* Licensed MIT License
*/
!function(a){"use strict";a.fn.bootstrapTable.locales["vi-VN"]={formatLoadingMessage:function(){return"Đang tải..."},formatRecordsPerPage:function(a){return a+" bản ghi mỗi trang"},formatShowingRows:function(a,b,c){return"Hiển thị từ trang "+a+" đến "+b+" của "+c+" bảng ghi"},formatSearch:function(){return"Tìm kiếm"},formatNoMatches:function(){return"Không có dữ liệu"}},a.extend(a.fn.bootstrapTable.defaults,a.fn.bootstrapTable.locales["vi-VN"])}(jQuery); | cswanson310/buildbaron | www/www/static/content/table/locale/bootstrap-table-vi-VN.min.js | JavaScript | apache-2.0 | 636 |
/**
* angular-strap
* @version v2.0.0 - 2014-04-07
* @link http://mgcrea.github.io/angular-strap
* @author Olivier Louvignes ([email protected])
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
"use strict";angular.module("mgcrea.ngStrap.dropdown").run(["$templateCache",function(e){e.put("dropdown/dropdown.tpl.html",'<ul tabindex="-1" class="dropdown-menu" role="menu"><li role="presentation" ng-class="{divider: item.divider}" ng-repeat="item in content"><a role="menuitem" tabindex="-1" ng-href="{{item.href}}" ng-if="!item.divider && item.href" ng-bind="item.text"></a> <a role="menuitem" tabindex="-1" href="javascript:void(0)" ng-if="!item.divider && item.click" ng-click="$eval(item.click);$hide()" ng-bind="item.text"></a></li></ul>')}]); | tmthrgd/pagespeed-libraries-cdnjs | packages/angular-strap/2.0.0/modules/dropdown.tpl.min.js | JavaScript | mit | 772 |
/*!
* json-schema-faker library v0.3.1
* http://json-schema-faker.js.org
* @preserve
*
* Copyright (c) 2014-2016 Alvaro Cabrera & Tomasz Ducin
* Released under the MIT license
*
* Date: 2016-04-15 18:37:35.154Z
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.jsf = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var Registry = require('../class/Registry');
// instantiate
var registry = new Registry();
/**
* Custom format API
*
* @see https://github.com/json-schema-faker/json-schema-faker#custom-formats
* @param nameOrFormatMap
* @param callback
* @returns {any}
*/
function formatAPI(nameOrFormatMap, callback) {
if (typeof nameOrFormatMap === 'undefined') {
return registry.list();
}
else if (typeof nameOrFormatMap === 'string') {
if (typeof callback === 'function') {
registry.register(nameOrFormatMap, callback);
}
else {
return registry.get(nameOrFormatMap);
}
}
else {
registry.registerMany(nameOrFormatMap);
}
}
module.exports = formatAPI;
},{"../class/Registry":5}],2:[function(require,module,exports){
var OptionRegistry = require('../class/OptionRegistry');
// instantiate
var registry = new OptionRegistry();
/**
* Custom option API
*
* @param nameOrOptionMap
* @returns {any}
*/
function optionAPI(nameOrOptionMap) {
if (typeof nameOrOptionMap === 'string') {
return registry.get(nameOrOptionMap);
}
else {
return registry.registerMany(nameOrOptionMap);
}
}
module.exports = optionAPI;
},{"../class/OptionRegistry":4}],3:[function(require,module,exports){
var randexp = require('randexp');
/**
* Container is used to wrap external libraries (faker, chance, randexp) that are used among the whole codebase. These
* libraries might be configured, customized, etc. and each internal JSF module needs to access those instances instead
* of pure npm module instances. This class supports consistent access to these instances.
*/
var Container = (function () {
function Container() {
// static requires - handle both initial dependency load (deps will be available
// among other modules) as well as they will be included by browserify AST
this.registry = {
faker: null,
chance: null,
// randexp is required for "pattern" values
randexp: randexp
};
}
/**
* Override dependency given by name
* @param name
* @param callback
*/
Container.prototype.extend = function (name, callback) {
if (typeof this.registry[name] === 'undefined') {
throw new ReferenceError('"' + name + '" dependency is not allowed.');
}
this.registry[name] = callback(this.registry[name]);
};
/**
* Returns dependency given by name
* @param name
* @returns {Dependency}
*/
Container.prototype.get = function (name) {
if (typeof this.registry[name] === 'undefined') {
throw new ReferenceError('"' + name + '" dependency doesn\'t exist.');
}
else if (name === 'randexp') {
return this.registry['randexp'].randexp;
}
return this.registry[name];
};
/**
* Returns all dependencies
*
* @returns {Registry}
*/
Container.prototype.getAll = function () {
return {
faker: this.get('faker'),
chance: this.get('chance'),
randexp: this.get('randexp')
};
};
return Container;
})();
// TODO move instantiation somewhere else (out from class file)
// instantiate
var container = new Container();
module.exports = container;
},{"randexp":161}],4:[function(require,module,exports){
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 __());
};
var Registry = require('./Registry');
/**
* This class defines a registry for custom formats used within JSF.
*/
var OptionRegistry = (function (_super) {
__extends(OptionRegistry, _super);
function OptionRegistry() {
_super.call(this);
this.data['failOnInvalidTypes'] = true;
this.data['defaultInvalidTypeProduct'] = null;
}
return OptionRegistry;
})(Registry);
module.exports = OptionRegistry;
},{"./Registry":5}],5:[function(require,module,exports){
/**
* This class defines a registry for custom formats used within JSF.
*/
var Registry = (function () {
function Registry() {
// empty by default
this.data = {};
}
/**
* Registers custom format
*/
Registry.prototype.register = function (name, callback) {
this.data[name] = callback;
};
/**
* Register many formats at one shot
*/
Registry.prototype.registerMany = function (formats) {
for (var name in formats) {
this.data[name] = formats[name];
}
};
/**
* Returns element by registry key
*/
Registry.prototype.get = function (name) {
var format = this.data[name];
if (typeof format === 'undefined') {
throw new Error('unknown registry key ' + JSON.stringify(name));
}
return format;
};
/**
* Returns the whole registry content
*/
Registry.prototype.list = function () {
return this.data;
};
return Registry;
})();
module.exports = Registry;
},{}],6:[function(require,module,exports){
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 __());
};
var ParseError = (function (_super) {
__extends(ParseError, _super);
function ParseError(message, path) {
_super.call(this);
this.path = path;
Error.captureStackTrace(this, this.constructor);
this.name = 'ParseError';
this.message = message;
this.path = path;
}
return ParseError;
})(Error);
module.exports = ParseError;
},{}],7:[function(require,module,exports){
var inferredProperties = {
array: [
'additionalItems',
'items',
'maxItems',
'minItems',
'uniqueItems'
],
integer: [
'exclusiveMaximum',
'exclusiveMinimum',
'maximum',
'minimum',
'multipleOf'
],
object: [
'additionalProperties',
'dependencies',
'maxProperties',
'minProperties',
'patternProperties',
'properties',
'required'
],
string: [
'maxLength',
'minLength',
'pattern'
]
};
inferredProperties.number = inferredProperties.integer;
var subschemaProperties = [
'additionalItems',
'items',
'additionalProperties',
'dependencies',
'patternProperties',
'properties'
];
/**
* Iterates through all keys of `obj` and:
* - checks whether those keys match properties of a given inferred type
* - makes sure that `obj` is not a subschema; _Do not attempt to infer properties named as subschema containers. The
* reason for this is that any property name within those containers that matches one of the properties used for
* inferring missing type values causes the container itself to get processed which leads to invalid output. (Issue 62)_
*
* @returns {boolean}
*/
function matchesType(obj, lastElementInPath, inferredTypeProperties) {
return Object.keys(obj).filter(function (prop) {
var isSubschema = subschemaProperties.indexOf(lastElementInPath) > -1, inferredPropertyFound = inferredTypeProperties.indexOf(prop) > -1;
if (inferredPropertyFound && !isSubschema) {
return true;
}
}).length > 0;
}
/**
* Checks whether given `obj` type might be inferred. The mechanism iterates through all inferred types definitions,
* tries to match allowed properties with properties of given `obj`. Returns type name, if inferred, or null.
*
* @returns {string|null}
*/
function inferType(obj, schemaPath) {
for (var typeName in inferredProperties) {
var lastElementInPath = schemaPath[schemaPath.length - 1];
if (matchesType(obj, lastElementInPath, inferredProperties[typeName])) {
return typeName;
}
}
}
module.exports = inferType;
},{}],8:[function(require,module,exports){
/// <reference path="../index.d.ts" />
/**
* Returns random element of a collection
*
* @param collection
* @returns {T}
*/
function pick(collection) {
return collection[Math.floor(Math.random() * collection.length)];
}
/**
* Returns shuffled collection of elements
*
* @param collection
* @returns {T[]}
*/
function shuffle(collection) {
var copy = collection.slice(), length = collection.length;
for (; length > 0;) {
var key = Math.floor(Math.random() * length), tmp = copy[--length];
copy[length] = copy[key];
copy[key] = tmp;
}
return copy;
}
/**
* These values determine default range for random.number function
*
* @type {number}
*/
var MIN_NUMBER = -100, MAX_NUMBER = 100;
/**
* Generates random number according to parameters passed
*
* @param min
* @param max
* @param defMin
* @param defMax
* @param hasPrecision
* @returns {number}
*/
function number(min, max, defMin, defMax, hasPrecision) {
if (hasPrecision === void 0) { hasPrecision = false; }
defMin = typeof defMin === 'undefined' ? MIN_NUMBER : defMin;
defMax = typeof defMax === 'undefined' ? MAX_NUMBER : defMax;
min = typeof min === 'undefined' ? defMin : min;
max = typeof max === 'undefined' ? defMax : max;
if (max < min) {
max += min;
}
var result = Math.random() * (max - min) + min;
if (!hasPrecision) {
return parseInt(result + '', 10);
}
return result;
}
module.exports = {
pick: pick,
shuffle: shuffle,
number: number
};
},{}],9:[function(require,module,exports){
var deref = require('deref');
var traverse = require('./traverse');
var random = require('./random');
var utils = require('./utils');
function isKey(prop) {
return prop === 'enum' || prop === 'required' || prop === 'definitions';
}
// TODO provide types
function run(schema, refs, ex) {
var $ = deref();
try {
var seen = {};
return traverse($(schema, refs, ex), [], function reduce(sub) {
if (seen[sub.$ref] <= 0) {
delete sub.$ref;
delete sub.oneOf;
delete sub.anyOf;
delete sub.allOf;
return sub;
}
if (typeof sub.$ref === 'string') {
var id = sub.$ref;
delete sub.$ref;
if (!seen[id]) {
// TODO: this should be configurable
seen[id] = random.number(1, 5);
}
seen[id] -= 1;
utils.merge(sub, $.util.findByRef(id, $.refs));
}
if (Array.isArray(sub.allOf)) {
var schemas = sub.allOf;
delete sub.allOf;
// this is the only case where all sub-schemas
// must be resolved before any merge
schemas.forEach(function (schema) {
utils.merge(sub, reduce(schema));
});
}
if (Array.isArray(sub.oneOf || sub.anyOf)) {
var mix = sub.oneOf || sub.anyOf;
delete sub.anyOf;
delete sub.oneOf;
utils.merge(sub, random.pick(mix));
}
for (var prop in sub) {
if ((Array.isArray(sub[prop]) || typeof sub[prop] === 'object') && !isKey(prop)) {
sub[prop] = reduce(sub[prop]);
}
}
return sub;
});
}
catch (e) {
if (e.path) {
throw new Error(e.message + ' in ' + '/' + e.path.join('/'));
}
else {
throw e;
}
}
}
module.exports = run;
},{"./random":8,"./traverse":10,"./utils":11,"deref":29}],10:[function(require,module,exports){
var random = require('./random');
var ParseError = require('./error');
var inferType = require('./infer');
var types = require('../types/index');
var option = require('../api/option');
function isExternal(schema) {
return schema.faker || schema.chance;
}
function reduceExternal(schema, path) {
if (schema['x-faker']) {
schema.faker = schema['x-faker'];
}
if (schema['x-chance']) {
schema.chance = schema['x-chance'];
}
var fakerUsed = schema.faker !== undefined, chanceUsed = schema.chance !== undefined;
if (fakerUsed && chanceUsed) {
throw new ParseError('ambiguous generator when using both faker and chance: ' + JSON.stringify(schema), path);
}
return schema;
}
// TODO provide types
function traverse(schema, path, resolve) {
resolve(schema);
if (Array.isArray(schema.enum)) {
return random.pick(schema.enum);
}
// TODO remove the ugly overcome
var type = schema.type;
if (Array.isArray(type)) {
type = random.pick(type);
}
else if (typeof type === 'undefined') {
// Attempt to infer the type
type = inferType(schema, path) || type;
}
schema = reduceExternal(schema, path);
if (isExternal(schema)) {
type = 'external';
}
if (typeof type === 'string') {
if (!types[type]) {
if (option('failOnInvalidTypes')) {
throw new ParseError('unknown primitive ' + JSON.stringify(type), path.concat(['type']));
}
else {
return option('defaultInvalidTypeProduct');
}
}
else {
try {
return types[type](schema, path, resolve, traverse);
}
catch (e) {
if (typeof e.path === 'undefined') {
throw new ParseError(e.message, path);
}
throw e;
}
}
}
var copy = {};
if (Array.isArray(schema)) {
copy = [];
}
for (var prop in schema) {
if (typeof schema[prop] === 'object' && prop !== 'definitions') {
copy[prop] = traverse(schema[prop], path.concat([prop]), resolve);
}
else {
copy[prop] = schema[prop];
}
}
return copy;
}
module.exports = traverse;
},{"../api/option":2,"../types/index":23,"./error":6,"./infer":7,"./random":8}],11:[function(require,module,exports){
function getSubAttribute(obj, dotSeparatedKey) {
var keyElements = dotSeparatedKey.split('.');
while (keyElements.length) {
var prop = keyElements.shift();
if (!obj[prop]) {
break;
}
obj = obj[prop];
}
return obj;
}
/**
* Returns true/false whether the object parameter has its own properties defined
*
* @param obj
* @returns {boolean}
*/
function hasProperties(obj) {
var properties = [];
for (var _i = 1; _i < arguments.length; _i++) {
properties[_i - 1] = arguments[_i];
}
return properties.filter(function (key) {
return typeof obj[key] !== 'undefined';
}).length > 0;
}
function clone(arr) {
var out = [];
arr.forEach(function (item, index) {
if (typeof item === 'object' && item !== null) {
out[index] = Array.isArray(item) ? clone(item) : merge({}, item);
}
else {
out[index] = item;
}
});
return out;
}
// TODO refactor merge function
function merge(a, b) {
for (var key in b) {
if (typeof b[key] !== 'object' || b[key] === null) {
a[key] = b[key];
}
else if (Array.isArray(b[key])) {
a[key] = (a[key] || []).concat(clone(b[key]));
}
else if (typeof a[key] !== 'object' || a[key] === null || Array.isArray(a[key])) {
a[key] = merge({}, b[key]);
}
else {
a[key] = merge(a[key], b[key]);
}
}
return a;
}
module.exports = {
getSubAttribute: getSubAttribute,
hasProperties: hasProperties,
clone: clone,
merge: merge
};
},{}],12:[function(require,module,exports){
/**
* Generates randomized boolean value.
*
* @returns {boolean}
*/
function booleanGenerator() {
return Math.random() > 0.5;
}
module.exports = booleanGenerator;
},{}],13:[function(require,module,exports){
var container = require('../class/Container');
var randexp = container.get('randexp');
var regexps = {
email: '[a-zA-Z\\d][a-zA-Z\\d-]{1,13}[a-zA-Z\\d]@{hostname}',
hostname: '[a-zA-Z]{1,33}\\.[a-z]{2,4}',
ipv6: '[a-f\\d]{4}(:[a-f\\d]{4}){7}',
uri: '[a-zA-Z][a-zA-Z0-9+-.]*'
};
/**
* Generates randomized string basing on a built-in regex format
*
* @param coreFormat
* @returns {string}
*/
function coreFormatGenerator(coreFormat) {
return randexp(regexps[coreFormat]).replace(/\{(\w+)\}/, function (match, key) {
return randexp(regexps[key]);
});
}
module.exports = coreFormatGenerator;
},{"../class/Container":3}],14:[function(require,module,exports){
var random = require('../core/random');
/**
* Generates randomized date time ISO format string.
*
* @returns {string}
*/
function dateTimeGenerator() {
return new Date(random.number(0, 100000000000000)).toISOString();
}
module.exports = dateTimeGenerator;
},{"../core/random":8}],15:[function(require,module,exports){
var random = require('../core/random');
/**
* Generates randomized ipv4 address.
*
* @returns {string}
*/
function ipv4Generator() {
return [0, 0, 0, 0].map(function () {
return random.number(0, 255);
}).join('.');
}
module.exports = ipv4Generator;
},{"../core/random":8}],16:[function(require,module,exports){
/**
* Generates null value.
*
* @returns {null}
*/
function nullGenerator() {
return null;
}
module.exports = nullGenerator;
},{}],17:[function(require,module,exports){
var words = require('../generators/words');
var random = require('../core/random');
function produce() {
var length = random.number(1, 5);
return words(length).join(' ');
}
/**
* Generates randomized concatenated string based on words generator.
*
* @returns {string}
*/
function thunkGenerator(min, max) {
if (min === void 0) { min = 0; }
if (max === void 0) { max = 140; }
var min = Math.max(0, min), max = random.number(min, max), sample = produce();
while (sample.length < min) {
sample += produce();
}
if (sample.length > max) {
sample = sample.substr(0, max);
}
return sample;
}
module.exports = thunkGenerator;
},{"../core/random":8,"../generators/words":18}],18:[function(require,module,exports){
var random = require('../core/random');
var LIPSUM_WORDS = ('Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore'
+ ' et dolore magna aliqua Ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea'
+ ' commodo consequat Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla'
+ ' pariatur Excepteur sint occaecat cupidatat non proident sunt in culpa qui officia deserunt mollit anim id est'
+ ' laborum').split(' ');
/**
* Generates randomized array of single lorem ipsum words.
*
* @param length
* @returns {Array.<string>}
*/
function wordsGenerator(length) {
var words = random.shuffle(LIPSUM_WORDS);
return words.slice(0, length);
}
module.exports = wordsGenerator;
},{"../core/random":8}],19:[function(require,module,exports){
var container = require('./class/Container');
var format = require('./api/format');
var option = require('./api/option');
var run = require('./core/run');
var jsf = function (schema, refs) {
return run(schema, refs);
};
jsf.format = format;
jsf.option = option;
// returns itself for chaining
jsf.extend = function (name, cb) {
container.extend(name, cb);
return jsf;
};
module.exports = jsf;
},{"./api/format":1,"./api/option":2,"./class/Container":3,"./core/run":9}],20:[function(require,module,exports){
var random = require('../core/random');
var utils = require('../core/utils');
var ParseError = require('../core/error');
// TODO provide types
function unique(path, items, value, sample, resolve, traverseCallback) {
var tmp = [], seen = [];
function walk(obj) {
var json = JSON.stringify(obj);
if (seen.indexOf(json) === -1) {
seen.push(json);
tmp.push(obj);
}
}
items.forEach(walk);
// TODO: find a better solution?
var limit = 100;
while (tmp.length !== items.length) {
walk(traverseCallback(value.items || sample, path, resolve));
if (!limit--) {
break;
}
}
return tmp;
}
// TODO provide types
function arrayType(value, path, resolve, traverseCallback) {
var items = [];
if (!(value.items || value.additionalItems)) {
if (utils.hasProperties(value, 'minItems', 'maxItems', 'uniqueItems')) {
throw new ParseError('missing items for ' + JSON.stringify(value), path);
}
return items;
}
if (Array.isArray(value.items)) {
return Array.prototype.concat.apply(items, value.items.map(function (item, key) {
return traverseCallback(item, path.concat(['items', key]), resolve);
}));
}
var length = random.number(value.minItems, value.maxItems, 1, 5), sample = typeof value.additionalItems === 'object' ? value.additionalItems : {};
for (var current = items.length; current < length; current += 1) {
items.push(traverseCallback(value.items || sample, path.concat(['items', current]), resolve));
}
if (value.uniqueItems) {
return unique(path.concat(['items']), items, value, sample, resolve, traverseCallback);
}
return items;
}
module.exports = arrayType;
},{"../core/error":6,"../core/random":8,"../core/utils":11}],21:[function(require,module,exports){
var booleanGenerator = require('../generators/boolean');
var booleanType = booleanGenerator;
module.exports = booleanType;
},{"../generators/boolean":12}],22:[function(require,module,exports){
var utils = require('../core/utils');
var container = require('../class/Container');
function externalType(value, path) {
var libraryName = value.faker ? 'faker' : 'chance', libraryModule = value.faker ? container.get('faker') : container.get('chance'), key = value.faker || value.chance, path = key, args = [];
if (typeof path === 'object') {
path = Object.keys(path)[0];
if (Array.isArray(key[path])) {
args = key[path];
}
else {
args.push(key[path]);
}
}
var genFunction = utils.getSubAttribute(libraryModule, path);
if (typeof genFunction !== 'function') {
throw new Error('unknown ' + libraryName + '-generator for ' + JSON.stringify(key));
}
// see #116, #117 - faker.js 3.1.0 introduced local dependencies between generators
// making jsf break after upgrading from 3.0.1
var contextObject = libraryModule;
if (libraryName === 'faker') {
var fakerModuleName = path.split('.')[0];
contextObject = libraryModule[fakerModuleName];
}
return genFunction.apply(contextObject, args);
}
module.exports = externalType;
},{"../class/Container":3,"../core/utils":11}],23:[function(require,module,exports){
var _boolean = require('./boolean');
var _null = require('./null');
var _array = require('./array');
var _integer = require('./integer');
var _number = require('./number');
var _object = require('./object');
var _string = require('./string');
var _external = require('./external');
var typeMap = {
boolean: _boolean,
null: _null,
array: _array,
integer: _integer,
number: _number,
object: _object,
string: _string,
external: _external
};
module.exports = typeMap;
},{"./array":20,"./boolean":21,"./external":22,"./integer":24,"./null":25,"./number":26,"./object":27,"./string":28}],24:[function(require,module,exports){
var number = require('./number');
// The `integer` type is just a wrapper for the `number` type. The `number` type
// returns floating point numbers, and `integer` type truncates the fraction
// part, leaving the result as an integer.
function integerType(value) {
var generated = number(value);
// whether the generated number is positive or negative, need to use either
// floor (positive) or ceil (negative) function to get rid of the fraction
return generated > 0 ? Math.floor(generated) : Math.ceil(generated);
}
module.exports = integerType;
},{"./number":26}],25:[function(require,module,exports){
var nullGenerator = require('../generators/null');
var nullType = nullGenerator;
module.exports = nullType;
},{"../generators/null":16}],26:[function(require,module,exports){
var random = require('../core/random');
var MIN_INTEGER = -100000000, MAX_INTEGER = 100000000;
function numberType(value) {
var multipleOf = value.multipleOf;
var min = typeof value.minimum === 'undefined' ? MIN_INTEGER : value.minimum, max = typeof value.maximum === 'undefined' ? MAX_INTEGER : value.maximum;
if (multipleOf) {
max = Math.floor(max / multipleOf) * multipleOf;
min = Math.ceil(min / multipleOf) * multipleOf;
}
if (value.exclusiveMinimum && value.minimum && min === value.minimum) {
min += multipleOf || 1;
}
if (value.exclusiveMaximum && value.maximum && max === value.maximum) {
max -= multipleOf || 1;
}
if (multipleOf) {
return Math.floor(random.number(min, max) / multipleOf) * multipleOf;
}
if (min > max) {
return NaN;
}
return random.number(min, max, undefined, undefined, true);
}
module.exports = numberType;
},{"../core/random":8}],27:[function(require,module,exports){
var container = require('../class/Container');
var random = require('../core/random');
var words = require('../generators/words');
var utils = require('../core/utils');
var ParseError = require('../core/error');
var randexp = container.get('randexp');
// TODO provide types
function objectType(value, path, resolve, traverseCallback) {
var props = {};
if (!(value.properties || value.patternProperties || value.additionalProperties)) {
if (utils.hasProperties(value, 'minProperties', 'maxProperties', 'dependencies', 'required')) {
throw new ParseError('missing properties for ' + JSON.stringify(value), path);
}
return props;
}
var reqProps = value.required || [], allProps = value.properties ? Object.keys(value.properties) : [];
reqProps.forEach(function (key) {
if (value.properties && value.properties[key]) {
props[key] = value.properties[key];
}
});
var optProps = allProps.filter(function (prop) {
return reqProps.indexOf(prop) === -1;
});
if (value.patternProperties) {
optProps = Array.prototype.concat.apply(optProps, Object.keys(value.patternProperties));
}
var length = random.number(value.minProperties, value.maxProperties, 0, optProps.length);
random.shuffle(optProps).slice(0, length).forEach(function (key) {
if (value.properties && value.properties[key]) {
props[key] = value.properties[key];
}
else {
props[randexp(key)] = value.patternProperties[key];
}
});
var current = Object.keys(props).length, sample = typeof value.additionalProperties === 'object' ? value.additionalProperties : {};
if (current < length) {
words(length - current).forEach(function (key) {
props[key + randexp('[a-f\\d]{4,7}')] = sample;
});
}
return traverseCallback(props, path.concat(['properties']), resolve);
}
module.exports = objectType;
},{"../class/Container":3,"../core/error":6,"../core/random":8,"../core/utils":11,"../generators/words":18}],28:[function(require,module,exports){
var thunk = require('../generators/thunk');
var ipv4 = require('../generators/ipv4');
var dateTime = require('../generators/dateTime');
var coreFormat = require('../generators/coreFormat');
var format = require('../api/format');
var container = require('../class/Container');
var randexp = container.get('randexp');
function generateFormat(value) {
switch (value.format) {
case 'date-time':
return dateTime();
case 'ipv4':
return ipv4();
case 'regex':
// TODO: discuss
return '.+?';
case 'email':
case 'hostname':
case 'ipv6':
case 'uri':
return coreFormat(value.format);
default:
var callback = format(value.format);
return callback(container.getAll(), value);
}
}
function stringType(value) {
if (value.format) {
return generateFormat(value);
}
else if (value.pattern) {
return randexp(value.pattern);
}
else {
return thunk(value.minLength, value.maxLength);
}
}
module.exports = stringType;
},{"../api/format":1,"../class/Container":3,"../generators/coreFormat":13,"../generators/dateTime":14,"../generators/ipv4":15,"../generators/thunk":17}],29:[function(require,module,exports){
'use strict';
var $ = require('./util/uri-helpers');
$.findByRef = require('./util/find-reference');
$.resolveSchema = require('./util/resolve-schema');
$.normalizeSchema = require('./util/normalize-schema');
var instance = module.exports = function() {
function $ref(fakeroot, schema, refs, ex) {
if (typeof fakeroot === 'object') {
ex = refs;
refs = schema;
schema = fakeroot;
fakeroot = undefined;
}
if (typeof schema !== 'object') {
throw new Error('schema must be an object');
}
if (typeof refs === 'object' && refs !== null) {
var aux = refs;
refs = [];
for (var k in aux) {
aux[k].id = aux[k].id || k;
refs.push(aux[k]);
}
}
if (typeof refs !== 'undefined' && !Array.isArray(refs)) {
ex = !!refs;
refs = [];
}
function push(ref) {
if (typeof ref.id === 'string') {
var id = $.resolveURL(fakeroot, ref.id).replace(/\/#?$/, '');
if (id.indexOf('#') > -1) {
var parts = id.split('#');
if (parts[1].charAt() === '/') {
id = parts[0];
} else {
id = parts[1] || parts[0];
}
}
if (!$ref.refs[id]) {
$ref.refs[id] = ref;
}
}
}
(refs || []).concat([schema]).forEach(function(ref) {
schema = $.normalizeSchema(fakeroot, ref, push);
push(schema);
});
return $.resolveSchema(schema, $ref.refs, ex);
}
$ref.refs = {};
$ref.util = $;
return $ref;
};
instance.util = $;
},{"./util/find-reference":31,"./util/normalize-schema":32,"./util/resolve-schema":33,"./util/uri-helpers":34}],30:[function(require,module,exports){
'use strict';
var clone = module.exports = function(obj, seen) {
seen = seen || [];
if (seen.indexOf(obj) > -1) {
throw new Error('unable dereference circular structures');
}
if (!obj || typeof obj !== 'object') {
return obj;
}
seen = seen.concat([obj]);
var target = Array.isArray(obj) ? [] : {};
function copy(key, value) {
target[key] = clone(value, seen);
}
if (Array.isArray(target)) {
obj.forEach(function(value, key) {
copy(key, value);
});
} else if (Object.prototype.toString.call(obj) === '[object Object]') {
Object.keys(obj).forEach(function(key) {
copy(key, obj[key]);
});
}
return target;
};
},{}],31:[function(require,module,exports){
'use strict';
var $ = require('./uri-helpers');
function get(obj, path) {
var hash = path.split('#')[1];
var parts = hash.split('/').slice(1);
while (parts.length) {
var key = decodeURIComponent(parts.shift()).replace(/~1/g, '/').replace(/~0/g, '~');
if (typeof obj[key] === 'undefined') {
throw new Error('JSON pointer not found: ' + path);
}
obj = obj[key];
}
return obj;
}
var find = module.exports = function(id, refs) {
var target = refs[id] || refs[id.split('#')[1]] || refs[$.getDocumentURI(id)];
if (target) {
target = id.indexOf('#/') > -1 ? get(target, id) : target;
} else {
for (var key in refs) {
if ($.resolveURL(refs[key].id, id) === refs[key].id) {
target = refs[key];
break;
}
}
}
if (!target) {
throw new Error('Reference not found: ' + id);
}
while (target.$ref) {
target = find(target.$ref, refs);
}
return target;
};
},{"./uri-helpers":34}],32:[function(require,module,exports){
'use strict';
var $ = require('./uri-helpers');
var cloneObj = require('./clone-obj');
var SCHEMA_URI = [
'http://json-schema.org/schema#',
'http://json-schema.org/draft-04/schema#'
];
function expand(obj, parent, callback) {
if (obj) {
var id = typeof obj.id === 'string' ? obj.id : '#';
if (!$.isURL(id)) {
id = $.resolveURL(parent === id ? null : parent, id);
}
if (typeof obj.$ref === 'string' && !$.isURL(obj.$ref)) {
obj.$ref = $.resolveURL(id, obj.$ref);
}
if (typeof obj.id === 'string') {
obj.id = parent = id;
}
}
for (var key in obj) {
var value = obj[key];
if (typeof value === 'object' && !(key === 'enum' || key === 'required')) {
expand(value, parent, callback);
}
}
if (typeof callback === 'function') {
callback(obj);
}
}
module.exports = function(fakeroot, schema, push) {
if (typeof fakeroot === 'object') {
push = schema;
schema = fakeroot;
fakeroot = null;
}
var base = fakeroot || '',
copy = cloneObj(schema);
if (copy.$schema && SCHEMA_URI.indexOf(copy.$schema) === -1) {
throw new Error('Unsupported schema version (v4 only)');
}
base = $.resolveURL(copy.$schema || SCHEMA_URI[0], base);
expand(copy, $.resolveURL(copy.id || '#', base), push);
copy.id = copy.id || base;
return copy;
};
},{"./clone-obj":30,"./uri-helpers":34}],33:[function(require,module,exports){
'use strict';
var $ = require('./uri-helpers');
var find = require('./find-reference');
var deepExtend = require('deep-extend');
function isKey(prop) {
return prop === 'enum' || prop === 'required' || prop === 'definitions';
}
function copy(obj, refs, parent, resolve) {
var target = Array.isArray(obj) ? [] : {};
if (typeof obj.$ref === 'string') {
var base = $.getDocumentURI(obj.$ref);
if (parent !== base || (resolve && obj.$ref.indexOf('#/') > -1)) {
var fixed = find(obj.$ref, refs);
deepExtend(obj, fixed);
delete obj.$ref;
delete obj.id;
}
}
for (var prop in obj) {
if (typeof obj[prop] === 'object' && !isKey(prop)) {
target[prop] = copy(obj[prop], refs, parent, resolve);
} else {
target[prop] = obj[prop];
}
}
return target;
}
module.exports = function(obj, refs, resolve) {
var fixedId = $.resolveURL(obj.$schema, obj.id),
parent = $.getDocumentURI(fixedId);
return copy(obj, refs, parent, resolve);
};
},{"./find-reference":31,"./uri-helpers":34,"deep-extend":35}],34:[function(require,module,exports){
'use strict';
// https://gist.github.com/pjt33/efb2f1134bab986113fd
function URLUtils(url, baseURL) {
// remove leading ./
url = url.replace(/^\.\//, '');
var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(?:\/\/(?:([^:@]*)(?::([^:@]*))?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
if (!m) {
throw new RangeError();
}
var href = m[0] || '';
var protocol = m[1] || '';
var username = m[2] || '';
var password = m[3] || '';
var host = m[4] || '';
var hostname = m[5] || '';
var port = m[6] || '';
var pathname = m[7] || '';
var search = m[8] || '';
var hash = m[9] || '';
if (baseURL !== undefined) {
var base = new URLUtils(baseURL);
var flag = protocol === '' && host === '' && username === '';
if (flag && pathname === '' && search === '') {
search = base.search;
}
if (flag && pathname.charAt(0) !== '/') {
pathname = (pathname !== '' ? (base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + pathname) : base.pathname);
}
// dot segments removal
var output = [];
pathname.replace(/\/?[^\/]+/g, function(p) {
if (p === '/..') {
output.pop();
} else {
output.push(p);
}
});
pathname = output.join('') || '/';
if (flag) {
port = base.port;
hostname = base.hostname;
host = base.host;
password = base.password;
username = base.username;
}
if (protocol === '') {
protocol = base.protocol;
}
href = protocol + (host !== '' ? '//' : '') + (username !== '' ? username + (password !== '' ? ':' + password : '') + '@' : '') + host + pathname + search + hash;
}
this.href = href;
this.origin = protocol + (host !== '' ? '//' + host : '');
this.protocol = protocol;
this.username = username;
this.password = password;
this.host = host;
this.hostname = hostname;
this.port = port;
this.pathname = pathname;
this.search = search;
this.hash = hash;
}
function isURL(path) {
if (typeof path === 'string' && /^\w+:\/\//.test(path)) {
return true;
}
}
function parseURI(href, base) {
return new URLUtils(href, base);
}
function resolveURL(base, href) {
base = base || 'http://json-schema.org/schema#';
href = parseURI(href, base);
base = parseURI(base);
if (base.hash && !href.hash) {
return href.href + base.hash;
}
return href.href;
}
function getDocumentURI(uri) {
return typeof uri === 'string' && uri.split('#')[0];
}
module.exports = {
isURL: isURL,
parseURI: parseURI,
resolveURL: resolveURL,
getDocumentURI: getDocumentURI
};
},{}],35:[function(require,module,exports){
/*!
* @description Recursive object extending
* @author Viacheslav Lotsmanov <[email protected]>
* @license MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2015 Viacheslav Lotsmanov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
'use strict';
function isSpecificValue(val) {
return (
val instanceof Buffer
|| val instanceof Date
|| val instanceof RegExp
) ? true : false;
}
function cloneSpecificValue(val) {
if (val instanceof Buffer) {
var x = new Buffer(val.length);
val.copy(x);
return x;
} else if (val instanceof Date) {
return new Date(val.getTime());
} else if (val instanceof RegExp) {
return new RegExp(val);
} else {
throw new Error('Unexpected situation');
}
}
/**
* Recursive cloning array.
*/
function deepCloneArray(arr) {
var clone = [];
arr.forEach(function (item, index) {
if (typeof item === 'object' && item !== null) {
if (Array.isArray(item)) {
clone[index] = deepCloneArray(item);
} else if (isSpecificValue(item)) {
clone[index] = cloneSpecificValue(item);
} else {
clone[index] = deepExtend({}, item);
}
} else {
clone[index] = item;
}
});
return clone;
}
/**
* Extening object that entered in first argument.
*
* Returns extended object or false if have no target object or incorrect type.
*
* If you wish to clone source object (without modify it), just use empty new
* object as first argument, like this:
* deepExtend({}, yourObj_1, [yourObj_N]);
*/
var deepExtend = module.exports = function (/*obj_1, [obj_2], [obj_N]*/) {
if (arguments.length < 1 || typeof arguments[0] !== 'object') {
return false;
}
if (arguments.length < 2) {
return arguments[0];
}
var target = arguments[0];
// convert arguments to array and cut off target object
var args = Array.prototype.slice.call(arguments, 1);
var val, src, clone;
args.forEach(function (obj) {
// skip argument if it is array or isn't object
if (typeof obj !== 'object' || Array.isArray(obj)) {
return;
}
Object.keys(obj).forEach(function (key) {
src = target[key]; // source value
val = obj[key]; // new value
// recursion prevention
if (val === target) {
return;
/**
* if new value isn't object then just overwrite by new value
* instead of extending.
*/
} else if (typeof val !== 'object' || val === null) {
target[key] = val;
return;
// just clone arrays (and recursive clone objects inside)
} else if (Array.isArray(val)) {
target[key] = deepCloneArray(val);
return;
// custom cloning and overwrite for specific objects
} else if (isSpecificValue(val)) {
target[key] = cloneSpecificValue(val);
return;
// overwrite by new value if source isn't object or array
} else if (typeof src !== 'object' || src === null || Array.isArray(src)) {
target[key] = deepExtend({}, val);
return;
// source value and new value is objects both, extending...
} else {
target[key] = deepExtend(src, val);
return;
}
});
});
return target;
}
},{}],36:[function(require,module,exports){
/**
*
* @namespace faker.address
*/
function Address (faker) {
var f = faker.fake,
Helpers = faker.helpers;
/**
* Generates random zipcode from format. If format is not specified, the
* locale's zip format is used.
*
* @method faker.address.zipCode
* @param {String} format
*/
this.zipCode = function(format) {
// if zip format is not specified, use the zip format defined for the locale
if (typeof format === 'undefined') {
var localeFormat = faker.definitions.address.postcode;
if (typeof localeFormat === 'string') {
format = localeFormat;
} else {
format = faker.random.arrayElement(localeFormat);
}
}
return Helpers.replaceSymbols(format);
}
/**
* Generates a random localized city name. The format string can contain any
* method provided by faker wrapped in `{{}}`, e.g. `{{name.firstName}}` in
* order to build the city name.
*
* If no format string is provided one of the following is randomly used:
*
* * `{{address.cityPrefix}} {{name.firstName}}{{address.citySuffix}}`
* * `{{address.cityPrefix}} {{name.firstName}}`
* * `{{name.firstName}}{{address.citySuffix}}`
* * `{{name.lastName}}{{address.citySuffix}}`
*
* @method faker.address.city
* @param {String} format
*/
this.city = function (format) {
var formats = [
'{{address.cityPrefix}} {{name.firstName}}{{address.citySuffix}}',
'{{address.cityPrefix}} {{name.firstName}}',
'{{name.firstName}}{{address.citySuffix}}',
'{{name.lastName}}{{address.citySuffix}}'
];
if (typeof format !== "number") {
format = faker.random.number(formats.length - 1);
}
return f(formats[format]);
}
/**
* Return a random localized city prefix
* @method faker.address.cityPrefix
*/
this.cityPrefix = function () {
return faker.random.arrayElement(faker.definitions.address.city_prefix);
}
/**
* Return a random localized city suffix
*
* @method faker.address.citySuffix
*/
this.citySuffix = function () {
return faker.random.arrayElement(faker.definitions.address.city_suffix);
}
/**
* Returns a random localized street name
*
* @method faker.address.streetName
*/
this.streetName = function () {
var result;
var suffix = faker.address.streetSuffix();
if (suffix !== "") {
suffix = " " + suffix
}
switch (faker.random.number(1)) {
case 0:
result = faker.name.lastName() + suffix;
break;
case 1:
result = faker.name.firstName() + suffix;
break;
}
return result;
}
//
// TODO: change all these methods that accept a boolean to instead accept an options hash.
//
/**
* Returns a random localized street address
*
* @method faker.address.streetAddress
* @param {Boolean} useFullAddress
*/
this.streetAddress = function (useFullAddress) {
if (useFullAddress === undefined) { useFullAddress = false; }
var address = "";
switch (faker.random.number(2)) {
case 0:
address = Helpers.replaceSymbolWithNumber("#####") + " " + faker.address.streetName();
break;
case 1:
address = Helpers.replaceSymbolWithNumber("####") + " " + faker.address.streetName();
break;
case 2:
address = Helpers.replaceSymbolWithNumber("###") + " " + faker.address.streetName();
break;
}
return useFullAddress ? (address + " " + faker.address.secondaryAddress()) : address;
}
/**
* streetSuffix
*
* @method faker.address.streetSuffix
*/
this.streetSuffix = function () {
return faker.random.arrayElement(faker.definitions.address.street_suffix);
}
/**
* streetPrefix
*
* @method faker.address.streetPrefix
*/
this.streetPrefix = function () {
return faker.random.arrayElement(faker.definitions.address.street_prefix);
}
/**
* secondaryAddress
*
* @method faker.address.secondaryAddress
*/
this.secondaryAddress = function () {
return Helpers.replaceSymbolWithNumber(faker.random.arrayElement(
[
'Apt. ###',
'Suite ###'
]
));
}
/**
* county
*
* @method faker.address.county
*/
this.county = function () {
return faker.random.arrayElement(faker.definitions.address.county);
}
/**
* country
*
* @method faker.address.country
*/
this.country = function () {
return faker.random.arrayElement(faker.definitions.address.country);
}
/**
* countryCode
*
* @method faker.address.countryCode
*/
this.countryCode = function () {
return faker.random.arrayElement(faker.definitions.address.country_code);
}
/**
* state
*
* @method faker.address.state
* @param {Boolean} useAbbr
*/
this.state = function (useAbbr) {
return faker.random.arrayElement(faker.definitions.address.state);
}
/**
* stateAbbr
*
* @method faker.address.stateAbbr
*/
this.stateAbbr = function () {
return faker.random.arrayElement(faker.definitions.address.state_abbr);
}
/**
* latitude
*
* @method faker.address.latitude
*/
this.latitude = function () {
return (faker.random.number(180 * 10000) / 10000.0 - 90.0).toFixed(4);
}
/**
* longitude
*
* @method faker.address.longitude
*/
this.longitude = function () {
return (faker.random.number(360 * 10000) / 10000.0 - 180.0).toFixed(4);
}
return this;
}
module.exports = Address;
},{}],37:[function(require,module,exports){
/**
*
* @namespace faker.commerce
*/
var Commerce = function (faker) {
var self = this;
/**
* color
*
* @method faker.commerce.color
*/
self.color = function() {
return faker.random.arrayElement(faker.definitions.commerce.color);
};
/**
* department
*
* @method faker.commerce.department
* @param {number} max
* @param {number} fixedAmount
*/
self.department = function(max, fixedAmount) {
return faker.random.arrayElement(faker.definitions.commerce.department);
};
/**
* productName
*
* @method faker.commerce.productName
*/
self.productName = function() {
return faker.commerce.productAdjective() + " " +
faker.commerce.productMaterial() + " " +
faker.commerce.product();
};
/**
* price
*
* @method faker.commerce.price
* @param {number} min
* @param {number} max
* @param {number} dec
* @param {string} symbol
*/
self.price = function(min, max, dec, symbol) {
min = min || 0;
max = max || 1000;
dec = dec || 2;
symbol = symbol || '';
if(min < 0 || max < 0) {
return symbol + 0.00;
}
var randValue = faker.random.number({ max: max, min: min });
return symbol + (Math.round(randValue * Math.pow(10, dec)) / Math.pow(10, dec)).toFixed(dec);
};
/*
self.categories = function(num) {
var categories = [];
do {
var category = faker.random.arrayElement(faker.definitions.commerce.department);
if(categories.indexOf(category) === -1) {
categories.push(category);
}
} while(categories.length < num);
return categories;
};
*/
/*
self.mergeCategories = function(categories) {
var separator = faker.definitions.separator || " &";
// TODO: find undefined here
categories = categories || faker.definitions.commerce.categories;
var commaSeparated = categories.slice(0, -1).join(', ');
return [commaSeparated, categories[categories.length - 1]].join(separator + " ");
};
*/
/**
* productAdjective
*
* @method faker.commerce.productAdjective
*/
self.productAdjective = function() {
return faker.random.arrayElement(faker.definitions.commerce.product_name.adjective);
};
/**
* productMaterial
*
* @method faker.commerce.productMaterial
*/
self.productMaterial = function() {
return faker.random.arrayElement(faker.definitions.commerce.product_name.material);
};
/**
* product
*
* @method faker.commerce.product
*/
self.product = function() {
return faker.random.arrayElement(faker.definitions.commerce.product_name.product);
}
return self;
};
module['exports'] = Commerce;
},{}],38:[function(require,module,exports){
/**
*
* @namespace faker.company
*/
var Company = function (faker) {
var self = this;
var f = faker.fake;
/**
* suffixes
*
* @method faker.company.suffixes
*/
this.suffixes = function () {
// Don't want the source array exposed to modification, so return a copy
return faker.definitions.company.suffix.slice(0);
}
/**
* companyName
*
* @method faker.company.companyName
* @param {string} format
*/
this.companyName = function (format) {
var formats = [
'{{name.lastName}} {{company.companySuffix}}',
'{{name.lastName}} - {{name.lastName}}',
'{{name.lastName}}, {{name.lastName}} and {{name.lastName}}'
];
if (typeof format !== "number") {
format = faker.random.number(formats.length - 1);
}
return f(formats[format]);
}
/**
* companySuffix
*
* @method faker.company.companySuffix
*/
this.companySuffix = function () {
return faker.random.arrayElement(faker.company.suffixes());
}
/**
* catchPhrase
*
* @method faker.company.catchPhrase
*/
this.catchPhrase = function () {
return f('{{company.catchPhraseAdjective}} {{company.catchPhraseDescriptor}} {{company.catchPhraseNoun}}')
}
/**
* bs
*
* @method faker.company.bs
*/
this.bs = function () {
return f('{{company.bsAdjective}} {{company.bsBuzz}} {{company.bsNoun}}');
}
/**
* catchPhraseAdjective
*
* @method faker.company.catchPhraseAdjective
*/
this.catchPhraseAdjective = function () {
return faker.random.arrayElement(faker.definitions.company.adjective);
}
/**
* catchPhraseDescriptor
*
* @method faker.company.catchPhraseDescriptor
*/
this.catchPhraseDescriptor = function () {
return faker.random.arrayElement(faker.definitions.company.descriptor);
}
/**
* catchPhraseNoun
*
* @method faker.company.catchPhraseNoun
*/
this.catchPhraseNoun = function () {
return faker.random.arrayElement(faker.definitions.company.noun);
}
/**
* bsAdjective
*
* @method faker.company.bsAdjective
*/
this.bsAdjective = function () {
return faker.random.arrayElement(faker.definitions.company.bs_adjective);
}
/**
* bsBuzz
*
* @method faker.company.bsBuzz
*/
this.bsBuzz = function () {
return faker.random.arrayElement(faker.definitions.company.bs_verb);
}
/**
* bsNoun
*
* @method faker.company.bsNoun
*/
this.bsNoun = function () {
return faker.random.arrayElement(faker.definitions.company.bs_noun);
}
}
module['exports'] = Company;
},{}],39:[function(require,module,exports){
/**
*
* @namespace faker.date
*/
var _Date = function (faker) {
var self = this;
/**
* past
*
* @method faker.date.past
* @param {number} years
* @param {date} refDate
*/
self.past = function (years, refDate) {
var date = (refDate) ? new Date(Date.parse(refDate)) : new Date();
var range = {
min: 1000,
max: (years || 1) * 365 * 24 * 3600 * 1000
};
var past = date.getTime();
past -= faker.random.number(range); // some time from now to N years ago, in milliseconds
date.setTime(past);
return date;
};
/**
* future
*
* @method faker.date.future
* @param {number} years
* @param {date} refDate
*/
self.future = function (years, refDate) {
var date = (refDate) ? new Date(Date.parse(refDate)) : new Date();
var range = {
min: 1000,
max: (years || 1) * 365 * 24 * 3600 * 1000
};
var future = date.getTime();
future += faker.random.number(range); // some time from now to N years later, in milliseconds
date.setTime(future);
return date;
};
/**
* between
*
* @method faker.date.between
* @param {date} from
* @param {date} to
*/
self.between = function (from, to) {
var fromMilli = Date.parse(from);
var dateOffset = faker.random.number(Date.parse(to) - fromMilli);
var newDate = new Date(fromMilli + dateOffset);
return newDate;
};
/**
* recent
*
* @method faker.date.recent
* @param {number} days
*/
self.recent = function (days) {
var date = new Date();
var range = {
min: 1000,
max: (days || 1) * 24 * 3600 * 1000
};
var future = date.getTime();
future -= faker.random.number(range); // some time from now to N days ago, in milliseconds
date.setTime(future);
return date;
};
/**
* month
*
* @method faker.date.month
* @param {object} options
*/
self.month = function (options) {
options = options || {};
var type = 'wide';
if (options.abbr) {
type = 'abbr';
}
if (options.context && typeof faker.definitions.date.month[type + '_context'] !== 'undefined') {
type += '_context';
}
var source = faker.definitions.date.month[type];
return faker.random.arrayElement(source);
};
/**
* weekday
*
* @param {object} options
* @method faker.date.weekday
*/
self.weekday = function (options) {
options = options || {};
var type = 'wide';
if (options.abbr) {
type = 'abbr';
}
if (options.context && typeof faker.definitions.date.weekday[type + '_context'] !== 'undefined') {
type += '_context';
}
var source = faker.definitions.date.weekday[type];
return faker.random.arrayElement(source);
};
return self;
};
module['exports'] = _Date;
},{}],40:[function(require,module,exports){
/*
fake.js - generator method for combining faker methods based on string input
*/
function Fake (faker) {
/**
* Generator method for combining faker methods based on string input
*
* __Example:__
*
* ```
* console.log(faker.fake('{{name.lastName}}, {{name.firstName}} {{name.suffix}}'));
* //outputs: "Marks, Dean Sr."
* ```
*
* This will interpolate the format string with the value of methods
* [name.lastName]{@link faker.name.lastName}, [name.firstName]{@link faker.name.firstName},
* and [name.suffix]{@link faker.name.suffix}
*
* @method faker.fake
* @param {string} str
*/
this.fake = function fake (str) {
// setup default response as empty string
var res = '';
// if incoming str parameter is not provided, return error message
if (typeof str !== 'string' || str.length === 0) {
res = 'string parameter is required!';
return res;
}
// find first matching {{ and }}
var start = str.search('{{');
var end = str.search('}}');
// if no {{ and }} is found, we are done
if (start === -1 && end === -1) {
return str;
}
// console.log('attempting to parse', str);
// extract method name from between the {{ }} that we found
// for example: {{name.firstName}}
var token = str.substr(start + 2, end - start - 2);
var method = token.replace('}}', '').replace('{{', '');
// console.log('method', method)
// extract method parameters
var regExp = /\(([^)]+)\)/;
var matches = regExp.exec(method);
var parameters = '';
if (matches) {
method = method.replace(regExp, '');
parameters = matches[1];
}
// split the method into module and function
var parts = method.split('.');
if (typeof faker[parts[0]] === "undefined") {
throw new Error('Invalid module: ' + parts[0]);
}
if (typeof faker[parts[0]][parts[1]] === "undefined") {
throw new Error('Invalid method: ' + parts[0] + "." + parts[1]);
}
// assign the function from the module.function namespace
var fn = faker[parts[0]][parts[1]];
// If parameters are populated here, they are always going to be of string type
// since we might actually be dealing with an object or array,
// we always attempt to the parse the incoming parameters into JSON
var params;
// Note: we experience a small performance hit here due to JSON.parse try / catch
// If anyone actually needs to optimize this specific code path, please open a support issue on github
try {
params = JSON.parse(parameters)
} catch (err) {
// since JSON.parse threw an error, assume parameters was actually a string
params = parameters;
}
var result;
if (typeof params === "string" && params.length === 0) {
result = fn.call(this);
} else {
result = fn.call(this, params);
}
// replace the found tag with the returned fake value
res = str.replace('{{' + token + '}}', result);
// return the response recursively until we are done finding all tags
return fake(res);
}
return this;
}
module['exports'] = Fake;
},{}],41:[function(require,module,exports){
/**
*
* @namespace faker.finance
*/
var Finance = function (faker) {
var Helpers = faker.helpers,
self = this;
/**
* account
*
* @method faker.finance.account
* @param {number} length
*/
self.account = function (length) {
length = length || 8;
var template = '';
for (var i = 0; i < length; i++) {
template = template + '#';
}
length = null;
return Helpers.replaceSymbolWithNumber(template);
}
/**
* accountName
*
* @method faker.finance.accountName
*/
self.accountName = function () {
return [Helpers.randomize(faker.definitions.finance.account_type), 'Account'].join(' ');
}
/**
* mask
*
* @method faker.finance.mask
* @param {number} length
* @param {boolean} parens
* @param {boolean} elipsis
*/
self.mask = function (length, parens, elipsis) {
//set defaults
length = (length == 0 || !length || typeof length == 'undefined') ? 4 : length;
parens = (parens === null) ? true : parens;
elipsis = (elipsis === null) ? true : elipsis;
//create a template for length
var template = '';
for (var i = 0; i < length; i++) {
template = template + '#';
}
//prefix with elipsis
template = (elipsis) ? ['...', template].join('') : template;
template = (parens) ? ['(', template, ')'].join('') : template;
//generate random numbers
template = Helpers.replaceSymbolWithNumber(template);
return template;
}
//min and max take in minimum and maximum amounts, dec is the decimal place you want rounded to, symbol is $, €, £, etc
//NOTE: this returns a string representation of the value, if you want a number use parseFloat and no symbol
/**
* amount
*
* @method faker.finance.amount
* @param {number} min
* @param {number} max
* @param {number} dec
* @param {string} symbol
*/
self.amount = function (min, max, dec, symbol) {
min = min || 0;
max = max || 1000;
dec = dec || 2;
symbol = symbol || '';
var randValue = faker.random.number({ max: max, min: min });
return symbol + (Math.round(randValue * Math.pow(10, dec)) / Math.pow(10, dec)).toFixed(dec);
}
/**
* transactionType
*
* @method faker.finance.transactionType
*/
self.transactionType = function () {
return Helpers.randomize(faker.definitions.finance.transaction_type);
}
/**
* currencyCode
*
* @method faker.finance.currencyCode
*/
self.currencyCode = function () {
return faker.random.objectElement(faker.definitions.finance.currency)['code'];
}
/**
* currencyName
*
* @method faker.finance.currencyName
*/
self.currencyName = function () {
return faker.random.objectElement(faker.definitions.finance.currency, 'key');
}
/**
* currencySymbol
*
* @method faker.finance.currencySymbol
*/
self.currencySymbol = function () {
var symbol;
while (!symbol) {
symbol = faker.random.objectElement(faker.definitions.finance.currency)['symbol'];
}
return symbol;
}
/**
* bitcoinAddress
*
* @method faker.finance.bitcoinAddress
*/
self.bitcoinAddress = function () {
var addressLength = faker.random.number({ min: 27, max: 34 });
var address = faker.random.arrayElement(['1', '3']);
for (var i = 0; i < addressLength - 1; i++)
address += faker.random.alphaNumeric().toUpperCase();
return address;
}
}
module['exports'] = Finance;
},{}],42:[function(require,module,exports){
/**
*
* @namespace faker.hacker
*/
var Hacker = function (faker) {
var self = this;
/**
* abbreviation
*
* @method faker.hacker.abbreviation
*/
self.abbreviation = function () {
return faker.random.arrayElement(faker.definitions.hacker.abbreviation);
};
/**
* adjective
*
* @method faker.hacker.adjective
*/
self.adjective = function () {
return faker.random.arrayElement(faker.definitions.hacker.adjective);
};
/**
* noun
*
* @method faker.hacker.noun
*/
self.noun = function () {
return faker.random.arrayElement(faker.definitions.hacker.noun);
};
/**
* verb
*
* @method faker.hacker.verb
*/
self.verb = function () {
return faker.random.arrayElement(faker.definitions.hacker.verb);
};
/**
* ingverb
*
* @method faker.hacker.ingverb
*/
self.ingverb = function () {
return faker.random.arrayElement(faker.definitions.hacker.ingverb);
};
/**
* phrase
*
* @method faker.hacker.phrase
*/
self.phrase = function () {
var data = {
abbreviation: self.abbreviation,
adjective: self.adjective,
ingverb: self.ingverb,
noun: self.noun,
verb: self.verb
};
var phrase = faker.random.arrayElement([ "If we {{verb}} the {{noun}}, we can get to the {{abbreviation}} {{noun}} through the {{adjective}} {{abbreviation}} {{noun}}!",
"We need to {{verb}} the {{adjective}} {{abbreviation}} {{noun}}!",
"Try to {{verb}} the {{abbreviation}} {{noun}}, maybe it will {{verb}} the {{adjective}} {{noun}}!",
"You can't {{verb}} the {{noun}} without {{ingverb}} the {{adjective}} {{abbreviation}} {{noun}}!",
"Use the {{adjective}} {{abbreviation}} {{noun}}, then you can {{verb}} the {{adjective}} {{noun}}!",
"The {{abbreviation}} {{noun}} is down, {{verb}} the {{adjective}} {{noun}} so we can {{verb}} the {{abbreviation}} {{noun}}!",
"{{ingverb}} the {{noun}} won't do anything, we need to {{verb}} the {{adjective}} {{abbreviation}} {{noun}}!",
"I'll {{verb}} the {{adjective}} {{abbreviation}} {{noun}}, that should {{noun}} the {{abbreviation}} {{noun}}!"
]);
return faker.helpers.mustache(phrase, data);
};
return self;
};
module['exports'] = Hacker;
},{}],43:[function(require,module,exports){
/**
*
* @namespace faker.helpers
*/
var Helpers = function (faker) {
var self = this;
/**
* backword-compatibility
*
* @method faker.helpers.randomize
* @param {array} array
*/
self.randomize = function (array) {
array = array || ["a", "b", "c"];
return faker.random.arrayElement(array);
};
/**
* slugifies string
*
* @method faker.helpers.slugify
* @param {string} string
*/
self.slugify = function (string) {
string = string || "";
return string.replace(/ /g, '-').replace(/[^\w\.\-]+/g, '');
};
/**
* parses string for a symbol and replace it with a random number from 1-10
*
* @method faker.helpers.replaceSymbolWithNumber
* @param {string} string
* @param {string} symbol defaults to `"#"`
*/
self.replaceSymbolWithNumber = function (string, symbol) {
string = string || "";
// default symbol is '#'
if (symbol === undefined) {
symbol = '#';
}
var str = '';
for (var i = 0; i < string.length; i++) {
if (string.charAt(i) == symbol) {
str += faker.random.number(9);
} else {
str += string.charAt(i);
}
}
return str;
};
/**
* parses string for symbols (numbers or letters) and replaces them appropriately
*
* @method faker.helpers.replaceSymbols
* @param {string} string
*/
self.replaceSymbols = function (string) {
string = string || "";
var alpha = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
var str = '';
for (var i = 0; i < string.length; i++) {
if (string.charAt(i) == "#") {
str += faker.random.number(9);
} else if (string.charAt(i) == "?") {
str += faker.random.arrayElement(alpha);
} else {
str += string.charAt(i);
}
}
return str;
};
/**
* takes an array and returns it randomized
*
* @method faker.helpers.shuffle
* @param {array} o
*/
self.shuffle = function (o) {
o = o || ["a", "b", "c"];
for (var j, x, i = o.length-1; i; j = faker.random.number(i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
/**
* mustache
*
* @method faker.helpers.mustache
* @param {string} str
* @param {object} data
*/
self.mustache = function (str, data) {
if (typeof str === 'undefined') {
return '';
}
for(var p in data) {
var re = new RegExp('{{' + p + '}}', 'g')
str = str.replace(re, data[p]);
}
return str;
};
/**
* createCard
*
* @method faker.helpers.createCard
*/
self.createCard = function () {
return {
"name": faker.name.findName(),
"username": faker.internet.userName(),
"email": faker.internet.email(),
"address": {
"streetA": faker.address.streetName(),
"streetB": faker.address.streetAddress(),
"streetC": faker.address.streetAddress(true),
"streetD": faker.address.secondaryAddress(),
"city": faker.address.city(),
"state": faker.address.state(),
"country": faker.address.country(),
"zipcode": faker.address.zipCode(),
"geo": {
"lat": faker.address.latitude(),
"lng": faker.address.longitude()
}
},
"phone": faker.phone.phoneNumber(),
"website": faker.internet.domainName(),
"company": {
"name": faker.company.companyName(),
"catchPhrase": faker.company.catchPhrase(),
"bs": faker.company.bs()
},
"posts": [
{
"words": faker.lorem.words(),
"sentence": faker.lorem.sentence(),
"sentences": faker.lorem.sentences(),
"paragraph": faker.lorem.paragraph()
},
{
"words": faker.lorem.words(),
"sentence": faker.lorem.sentence(),
"sentences": faker.lorem.sentences(),
"paragraph": faker.lorem.paragraph()
},
{
"words": faker.lorem.words(),
"sentence": faker.lorem.sentence(),
"sentences": faker.lorem.sentences(),
"paragraph": faker.lorem.paragraph()
}
],
"accountHistory": [faker.helpers.createTransaction(), faker.helpers.createTransaction(), faker.helpers.createTransaction()]
};
};
/**
* contextualCard
*
* @method faker.helpers.contextualCard
*/
self.contextualCard = function () {
var name = faker.name.firstName(),
userName = faker.internet.userName(name);
return {
"name": name,
"username": userName,
"avatar": faker.internet.avatar(),
"email": faker.internet.email(userName),
"dob": faker.date.past(50, new Date("Sat Sep 20 1992 21:35:02 GMT+0200 (CEST)")),
"phone": faker.phone.phoneNumber(),
"address": {
"street": faker.address.streetName(true),
"suite": faker.address.secondaryAddress(),
"city": faker.address.city(),
"zipcode": faker.address.zipCode(),
"geo": {
"lat": faker.address.latitude(),
"lng": faker.address.longitude()
}
},
"website": faker.internet.domainName(),
"company": {
"name": faker.company.companyName(),
"catchPhrase": faker.company.catchPhrase(),
"bs": faker.company.bs()
}
};
};
/**
* userCard
*
* @method faker.helpers.userCard
*/
self.userCard = function () {
return {
"name": faker.name.findName(),
"username": faker.internet.userName(),
"email": faker.internet.email(),
"address": {
"street": faker.address.streetName(true),
"suite": faker.address.secondaryAddress(),
"city": faker.address.city(),
"zipcode": faker.address.zipCode(),
"geo": {
"lat": faker.address.latitude(),
"lng": faker.address.longitude()
}
},
"phone": faker.phone.phoneNumber(),
"website": faker.internet.domainName(),
"company": {
"name": faker.company.companyName(),
"catchPhrase": faker.company.catchPhrase(),
"bs": faker.company.bs()
}
};
};
/**
* createTransaction
*
* @method faker.helpers.createTransaction
*/
self.createTransaction = function(){
return {
"amount" : faker.finance.amount(),
"date" : new Date(2012, 1, 2), //TODO: add a ranged date method
"business": faker.company.companyName(),
"name": [faker.finance.accountName(), faker.finance.mask()].join(' '),
"type" : self.randomize(faker.definitions.finance.transaction_type),
"account" : faker.finance.account()
};
};
return self;
};
/*
String.prototype.capitalize = function () { //v1.0
return this.replace(/\w+/g, function (a) {
return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
});
};
*/
module['exports'] = Helpers;
},{}],44:[function(require,module,exports){
/**
*
* @namespace faker.image
*/
var Image = function (faker) {
var self = this;
/**
* image
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.image
*/
self.image = function (width, height, randomize) {
var categories = ["abstract", "animals", "business", "cats", "city", "food", "nightlife", "fashion", "people", "nature", "sports", "technics", "transport"];
return self[faker.random.arrayElement(categories)](width, height, randomize);
};
/**
* avatar
*
* @method faker.image.avatar
*/
self.avatar = function () {
return faker.internet.avatar();
};
/**
* imageUrl
*
* @param {number} width
* @param {number} height
* @param {string} category
* @param {boolean} randomize
* @method faker.image.imageUrl
*/
self.imageUrl = function (width, height, category, randomize) {
var width = width || 640;
var height = height || 480;
var url ='http://lorempixel.com/' + width + '/' + height;
if (typeof category !== 'undefined') {
url += '/' + category;
}
if (randomize) {
url += '?' + faker.random.number()
}
return url;
};
/**
* abstract
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.abstract
*/
self.abstract = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'abstract', randomize);
};
/**
* animals
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.animals
*/
self.animals = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'animals', randomize);
};
/**
* business
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.business
*/
self.business = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'business', randomize);
};
/**
* cats
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.cats
*/
self.cats = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'cats', randomize);
};
/**
* city
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.city
*/
self.city = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'city', randomize);
};
/**
* food
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.food
*/
self.food = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'food', randomize);
};
/**
* nightlife
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.nightlife
*/
self.nightlife = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'nightlife', randomize);
};
/**
* fashion
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.fashion
*/
self.fashion = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'fashion', randomize);
};
/**
* people
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.people
*/
self.people = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'people', randomize);
};
/**
* nature
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.nature
*/
self.nature = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'nature', randomize);
};
/**
* sports
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.sports
*/
self.sports = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'sports', randomize);
};
/**
* technics
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.technics
*/
self.technics = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'technics', randomize);
};
/**
* transport
*
* @param {number} width
* @param {number} height
* @param {boolean} randomize
* @method faker.image.transport
*/
self.transport = function (width, height, randomize) {
return faker.image.imageUrl(width, height, 'transport', randomize);
}
}
module["exports"] = Image;
},{}],45:[function(require,module,exports){
/*
this index.js file is used for including the faker library as a CommonJS module, instead of a bundle
you can include the faker library into your existing node.js application by requiring the entire /faker directory
var faker = require(./faker);
var randomName = faker.name.findName();
you can also simply include the "faker.js" file which is the auto-generated bundled version of the faker library
var faker = require(./customAppPath/faker);
var randomName = faker.name.findName();
if you plan on modifying the faker library you should be performing your changes in the /lib/ directory
*/
/**
*
* @namespace faker
*/
function Faker (opts) {
var self = this;
opts = opts || {};
// assign options
var locales = self.locales || opts.locales || {};
var locale = self.locale || opts.locale || "en";
var localeFallback = self.localeFallback || opts.localeFallback || "en";
self.locales = locales;
self.locale = locale;
self.localeFallback = localeFallback;
self.definitions = {};
var Fake = require('./fake');
self.fake = new Fake(self).fake;
var Random = require('./random');
self.random = new Random(self);
// self.random = require('./random');
var Helpers = require('./helpers');
self.helpers = new Helpers(self);
var Name = require('./name');
self.name = new Name(self);
// self.name = require('./name');
var Address = require('./address');
self.address = new Address(self);
var Company = require('./company');
self.company = new Company(self);
var Finance = require('./finance');
self.finance = new Finance(self);
var Image = require('./image');
self.image = new Image(self);
var Lorem = require('./lorem');
self.lorem = new Lorem(self);
var Hacker = require('./hacker');
self.hacker = new Hacker(self);
var Internet = require('./internet');
self.internet = new Internet(self);
var Phone = require('./phone_number');
self.phone = new Phone(self);
var _Date = require('./date');
self.date = new _Date(self);
var Commerce = require('./commerce');
self.commerce = new Commerce(self);
var System = require('./system');
self.system = new System(self);
var _definitions = {
"name": ["first_name", "last_name", "prefix", "suffix", "title", "male_first_name", "female_first_name", "male_middle_name", "female_middle_name", "male_last_name", "female_last_name"],
"address": ["city_prefix", "city_suffix", "street_suffix", "county", "country", "country_code", "state", "state_abbr", "street_prefix", "postcode"],
"company": ["adjective", "noun", "descriptor", "bs_adjective", "bs_noun", "bs_verb", "suffix"],
"lorem": ["words"],
"hacker": ["abbreviation", "adjective", "noun", "verb", "ingverb"],
"phone_number": ["formats"],
"finance": ["account_type", "transaction_type", "currency"],
"internet": ["avatar_uri", "domain_suffix", "free_email", "example_email", "password"],
"commerce": ["color", "department", "product_name", "price", "categories"],
"system": ["mimeTypes"],
"date": ["month", "weekday"],
"title": "",
"separator": ""
};
// Create a Getter for all definitions.foo.bar propetries
Object.keys(_definitions).forEach(function(d){
if (typeof self.definitions[d] === "undefined") {
self.definitions[d] = {};
}
if (typeof _definitions[d] === "string") {
self.definitions[d] = _definitions[d];
return;
}
_definitions[d].forEach(function(p){
Object.defineProperty(self.definitions[d], p, {
get: function () {
if (typeof self.locales[self.locale][d] === "undefined" || typeof self.locales[self.locale][d][p] === "undefined") {
// certain localization sets contain less data then others.
// in the case of a missing defintion, use the default localeFallback to substitute the missing set data
// throw new Error('unknown property ' + d + p)
return self.locales[localeFallback][d][p];
} else {
// return localized data
return self.locales[self.locale][d][p];
}
}
});
});
});
};
Faker.prototype.seed = function(value) {
var Random = require('./random');
this.seedValue = value;
this.random = new Random(this, this.seedValue);
}
module['exports'] = Faker;
},{"./address":36,"./commerce":37,"./company":38,"./date":39,"./fake":40,"./finance":41,"./hacker":42,"./helpers":43,"./image":44,"./internet":46,"./lorem":152,"./name":153,"./phone_number":154,"./random":155,"./system":156}],46:[function(require,module,exports){
var password_generator = require('../vendor/password-generator.js'),
random_ua = require('../vendor/user-agent');
/**
*
* @namespace faker.internet
*/
var Internet = function (faker) {
var self = this;
/**
* avatar
*
* @method faker.internet.avatar
*/
self.avatar = function () {
return faker.random.arrayElement(faker.definitions.internet.avatar_uri);
};
self.avatar.schema = {
"description": "Generates a URL for an avatar.",
"sampleResults": ["https://s3.amazonaws.com/uifaces/faces/twitter/igorgarybaldi/128.jpg"]
};
/**
* email
*
* @method faker.internet.email
* @param {string} firstName
* @param {string} lastName
* @param {string} provider
*/
self.email = function (firstName, lastName, provider) {
provider = provider || faker.random.arrayElement(faker.definitions.internet.free_email);
return faker.helpers.slugify(faker.internet.userName(firstName, lastName)) + "@" + provider;
};
self.email.schema = {
"description": "Generates a valid email address based on optional input criteria",
"sampleResults": ["[email protected]"],
"properties": {
"firstName": {
"type": "string",
"required": false,
"description": "The first name of the user"
},
"lastName": {
"type": "string",
"required": false,
"description": "The last name of the user"
},
"provider": {
"type": "string",
"required": false,
"description": "The domain of the user"
}
}
};
/**
* exampleEmail
*
* @method faker.internet.exampleEmail
* @param {string} firstName
* @param {string} lastName
*/
self.exampleEmail = function (firstName, lastName) {
var provider = faker.random.arrayElement(faker.definitions.internet.example_email);
return self.email(firstName, lastName, provider);
};
/**
* userName
*
* @method faker.internet.userName
* @param {string} firstName
* @param {string} lastName
*/
self.userName = function (firstName, lastName) {
var result;
firstName = firstName || faker.name.firstName();
lastName = lastName || faker.name.lastName();
switch (faker.random.number(2)) {
case 0:
result = firstName + faker.random.number(99);
break;
case 1:
result = firstName + faker.random.arrayElement([".", "_"]) + lastName;
break;
case 2:
result = firstName + faker.random.arrayElement([".", "_"]) + lastName + faker.random.number(99);
break;
}
result = result.toString().replace(/'/g, "");
result = result.replace(/ /g, "");
return result;
};
self.userName.schema = {
"description": "Generates a username based on one of several patterns. The pattern is chosen randomly.",
"sampleResults": [
"Kirstin39",
"Kirstin.Smith",
"Kirstin.Smith39",
"KirstinSmith",
"KirstinSmith39",
],
"properties": {
"firstName": {
"type": "string",
"required": false,
"description": "The first name of the user"
},
"lastName": {
"type": "string",
"required": false,
"description": "The last name of the user"
}
}
};
/**
* protocol
*
* @method faker.internet.protocol
*/
self.protocol = function () {
var protocols = ['http','https'];
return faker.random.arrayElement(protocols);
};
self.protocol.schema = {
"description": "Randomly generates http or https",
"sampleResults": ["https", "http"]
};
/**
* url
*
* @method faker.internet.url
*/
self.url = function () {
return faker.internet.protocol() + '://' + faker.internet.domainName();
};
self.url.schema = {
"description": "Generates a random URL. The URL could be secure or insecure.",
"sampleResults": [
"http://rashawn.name",
"https://rashawn.name"
]
};
/**
* domainName
*
* @method faker.internet.domainName
*/
self.domainName = function () {
return faker.internet.domainWord() + "." + faker.internet.domainSuffix();
};
self.domainName.schema = {
"description": "Generates a random domain name.",
"sampleResults": ["marvin.org"]
};
/**
* domainSuffix
*
* @method faker.internet.domainSuffix
*/
self.domainSuffix = function () {
return faker.random.arrayElement(faker.definitions.internet.domain_suffix);
};
self.domainSuffix.schema = {
"description": "Generates a random domain suffix.",
"sampleResults": ["net"]
};
/**
* domainWord
*
* @method faker.internet.domainWord
*/
self.domainWord = function () {
return faker.name.firstName().replace(/([\\~#&*{}/:<>?|\"'])/ig, '').toLowerCase();
};
self.domainWord.schema = {
"description": "Generates a random domain word.",
"sampleResults": ["alyce"]
};
/**
* ip
*
* @method faker.internet.ip
*/
self.ip = function () {
var randNum = function () {
return (faker.random.number(255)).toFixed(0);
};
var result = [];
for (var i = 0; i < 4; i++) {
result[i] = randNum();
}
return result.join(".");
};
self.ip.schema = {
"description": "Generates a random IP.",
"sampleResults": ["97.238.241.11"]
};
/**
* userAgent
*
* @method faker.internet.userAgent
*/
self.userAgent = function () {
return random_ua.generate();
};
self.userAgent.schema = {
"description": "Generates a random user agent.",
"sampleResults": ["Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_7_5 rv:6.0; SL) AppleWebKit/532.0.1 (KHTML, like Gecko) Version/7.1.6 Safari/532.0.1"]
};
/**
* color
*
* @method faker.internet.color
* @param {number} baseRed255
* @param {number} baseGreen255
* @param {number} baseBlue255
*/
self.color = function (baseRed255, baseGreen255, baseBlue255) {
baseRed255 = baseRed255 || 0;
baseGreen255 = baseGreen255 || 0;
baseBlue255 = baseBlue255 || 0;
// based on awesome response : http://stackoverflow.com/questions/43044/algorithm-to-randomly-generate-an-aesthetically-pleasing-color-palette
var red = Math.floor((faker.random.number(256) + baseRed255) / 2);
var green = Math.floor((faker.random.number(256) + baseGreen255) / 2);
var blue = Math.floor((faker.random.number(256) + baseBlue255) / 2);
var redStr = red.toString(16);
var greenStr = green.toString(16);
var blueStr = blue.toString(16);
return '#' +
(redStr.length === 1 ? '0' : '') + redStr +
(greenStr.length === 1 ? '0' : '') + greenStr +
(blueStr.length === 1 ? '0': '') + blueStr;
};
self.color.schema = {
"description": "Generates a random hexadecimal color.",
"sampleResults": ["#06267f"],
"properties": {
"baseRed255": {
"type": "number",
"required": false,
"description": "The red value. Valid values are 0 - 255."
},
"baseGreen255": {
"type": "number",
"required": false,
"description": "The green value. Valid values are 0 - 255."
},
"baseBlue255": {
"type": "number",
"required": false,
"description": "The blue value. Valid values are 0 - 255."
}
}
};
/**
* mac
*
* @method faker.internet.mac
*/
self.mac = function(){
var i, mac = "";
for (i=0; i < 12; i++) {
mac+= faker.random.number(15).toString(16);
if (i%2==1 && i != 11) {
mac+=":";
}
}
return mac;
};
self.mac.schema = {
"description": "Generates a random mac address.",
"sampleResults": ["78:06:cc:ae:b3:81"]
};
/**
* password
*
* @method faker.internet.password
* @param {number} len
* @param {boolean} memorable
* @param {string} pattern
* @param {string} prefix
*/
self.password = function (len, memorable, pattern, prefix) {
len = len || 15;
if (typeof memorable === "undefined") {
memorable = false;
}
return password_generator(len, memorable, pattern, prefix);
}
self.password.schema = {
"description": "Generates a random password.",
"sampleResults": [
"AM7zl6Mg",
"susejofe"
],
"properties": {
"length": {
"type": "number",
"required": false,
"description": "The number of characters in the password."
},
"memorable": {
"type": "boolean",
"required": false,
"description": "Whether a password should be easy to remember."
},
"pattern": {
"type": "regex",
"required": false,
"description": "A regex to match each character of the password against. This parameter will be negated if the memorable setting is turned on."
},
"prefix": {
"type": "string",
"required": false,
"description": "A value to prepend to the generated password. The prefix counts towards the length of the password."
}
}
};
};
module["exports"] = Internet;
},{"../vendor/password-generator.js":159,"../vendor/user-agent":160}],47:[function(require,module,exports){
module["exports"] = [
"#####",
"####",
"###"
];
},{}],48:[function(require,module,exports){
module["exports"] = [
"#{city_prefix} #{Name.first_name}#{city_suffix}",
"#{city_prefix} #{Name.first_name}",
"#{Name.first_name}#{city_suffix}",
"#{Name.last_name}#{city_suffix}"
];
},{}],49:[function(require,module,exports){
module["exports"] = [
"North",
"East",
"West",
"South",
"New",
"Lake",
"Port"
];
},{}],50:[function(require,module,exports){
module["exports"] = [
"town",
"ton",
"land",
"ville",
"berg",
"burgh",
"borough",
"bury",
"view",
"port",
"mouth",
"stad",
"furt",
"chester",
"mouth",
"fort",
"haven",
"side",
"shire"
];
},{}],51:[function(require,module,exports){
module["exports"] = [
"Afghanistan",
"Albania",
"Algeria",
"American Samoa",
"Andorra",
"Angola",
"Anguilla",
"Antarctica (the territory South of 60 deg S)",
"Antigua and Barbuda",
"Argentina",
"Armenia",
"Aruba",
"Australia",
"Austria",
"Azerbaijan",
"Bahamas",
"Bahrain",
"Bangladesh",
"Barbados",
"Belarus",
"Belgium",
"Belize",
"Benin",
"Bermuda",
"Bhutan",
"Bolivia",
"Bosnia and Herzegovina",
"Botswana",
"Bouvet Island (Bouvetoya)",
"Brazil",
"British Indian Ocean Territory (Chagos Archipelago)",
"Brunei Darussalam",
"Bulgaria",
"Burkina Faso",
"Burundi",
"Cambodia",
"Cameroon",
"Canada",
"Cape Verde",
"Cayman Islands",
"Central African Republic",
"Chad",
"Chile",
"China",
"Christmas Island",
"Cocos (Keeling) Islands",
"Colombia",
"Comoros",
"Congo",
"Congo",
"Cook Islands",
"Costa Rica",
"Cote d'Ivoire",
"Croatia",
"Cuba",
"Cyprus",
"Czech Republic",
"Denmark",
"Djibouti",
"Dominica",
"Dominican Republic",
"Ecuador",
"Egypt",
"El Salvador",
"Equatorial Guinea",
"Eritrea",
"Estonia",
"Ethiopia",
"Faroe Islands",
"Falkland Islands (Malvinas)",
"Fiji",
"Finland",
"France",
"French Guiana",
"French Polynesia",
"French Southern Territories",
"Gabon",
"Gambia",
"Georgia",
"Germany",
"Ghana",
"Gibraltar",
"Greece",
"Greenland",
"Grenada",
"Guadeloupe",
"Guam",
"Guatemala",
"Guernsey",
"Guinea",
"Guinea-Bissau",
"Guyana",
"Haiti",
"Heard Island and McDonald Islands",
"Holy See (Vatican City State)",
"Honduras",
"Hong Kong",
"Hungary",
"Iceland",
"India",
"Indonesia",
"Iran",
"Iraq",
"Ireland",
"Isle of Man",
"Israel",
"Italy",
"Jamaica",
"Japan",
"Jersey",
"Jordan",
"Kazakhstan",
"Kenya",
"Kiribati",
"Democratic People's Republic of Korea",
"Republic of Korea",
"Kuwait",
"Kyrgyz Republic",
"Lao People's Democratic Republic",
"Latvia",
"Lebanon",
"Lesotho",
"Liberia",
"Libyan Arab Jamahiriya",
"Liechtenstein",
"Lithuania",
"Luxembourg",
"Macao",
"Macedonia",
"Madagascar",
"Malawi",
"Malaysia",
"Maldives",
"Mali",
"Malta",
"Marshall Islands",
"Martinique",
"Mauritania",
"Mauritius",
"Mayotte",
"Mexico",
"Micronesia",
"Moldova",
"Monaco",
"Mongolia",
"Montenegro",
"Montserrat",
"Morocco",
"Mozambique",
"Myanmar",
"Namibia",
"Nauru",
"Nepal",
"Netherlands Antilles",
"Netherlands",
"New Caledonia",
"New Zealand",
"Nicaragua",
"Niger",
"Nigeria",
"Niue",
"Norfolk Island",
"Northern Mariana Islands",
"Norway",
"Oman",
"Pakistan",
"Palau",
"Palestinian Territory",
"Panama",
"Papua New Guinea",
"Paraguay",
"Peru",
"Philippines",
"Pitcairn Islands",
"Poland",
"Portugal",
"Puerto Rico",
"Qatar",
"Reunion",
"Romania",
"Russian Federation",
"Rwanda",
"Saint Barthelemy",
"Saint Helena",
"Saint Kitts and Nevis",
"Saint Lucia",
"Saint Martin",
"Saint Pierre and Miquelon",
"Saint Vincent and the Grenadines",
"Samoa",
"San Marino",
"Sao Tome and Principe",
"Saudi Arabia",
"Senegal",
"Serbia",
"Seychelles",
"Sierra Leone",
"Singapore",
"Slovakia (Slovak Republic)",
"Slovenia",
"Solomon Islands",
"Somalia",
"South Africa",
"South Georgia and the South Sandwich Islands",
"Spain",
"Sri Lanka",
"Sudan",
"Suriname",
"Svalbard & Jan Mayen Islands",
"Swaziland",
"Sweden",
"Switzerland",
"Syrian Arab Republic",
"Taiwan",
"Tajikistan",
"Tanzania",
"Thailand",
"Timor-Leste",
"Togo",
"Tokelau",
"Tonga",
"Trinidad and Tobago",
"Tunisia",
"Turkey",
"Turkmenistan",
"Turks and Caicos Islands",
"Tuvalu",
"Uganda",
"Ukraine",
"United Arab Emirates",
"United Kingdom",
"United States of America",
"United States Minor Outlying Islands",
"Uruguay",
"Uzbekistan",
"Vanuatu",
"Venezuela",
"Vietnam",
"Virgin Islands, British",
"Virgin Islands, U.S.",
"Wallis and Futuna",
"Western Sahara",
"Yemen",
"Zambia",
"Zimbabwe"
];
},{}],52:[function(require,module,exports){
module["exports"] = [
"AD",
"AE",
"AF",
"AG",
"AI",
"AL",
"AM",
"AO",
"AQ",
"AR",
"AS",
"AT",
"AU",
"AW",
"AX",
"AZ",
"BA",
"BB",
"BD",
"BE",
"BF",
"BG",
"BH",
"BI",
"BJ",
"BL",
"BM",
"BN",
"BO",
"BQ",
"BQ",
"BR",
"BS",
"BT",
"BV",
"BW",
"BY",
"BZ",
"CA",
"CC",
"CD",
"CF",
"CG",
"CH",
"CI",
"CK",
"CL",
"CM",
"CN",
"CO",
"CR",
"CU",
"CV",
"CW",
"CX",
"CY",
"CZ",
"DE",
"DJ",
"DK",
"DM",
"DO",
"DZ",
"EC",
"EE",
"EG",
"EH",
"ER",
"ES",
"ET",
"FI",
"FJ",
"FK",
"FM",
"FO",
"FR",
"GA",
"GB",
"GD",
"GE",
"GF",
"GG",
"GH",
"GI",
"GL",
"GM",
"GN",
"GP",
"GQ",
"GR",
"GS",
"GT",
"GU",
"GW",
"GY",
"HK",
"HM",
"HN",
"HR",
"HT",
"HU",
"ID",
"IE",
"IL",
"IM",
"IN",
"IO",
"IQ",
"IR",
"IS",
"IT",
"JE",
"JM",
"JO",
"JP",
"KE",
"KG",
"KH",
"KI",
"KM",
"KN",
"KP",
"KR",
"KW",
"KY",
"KZ",
"LA",
"LB",
"LC",
"LI",
"LK",
"LR",
"LS",
"LT",
"LU",
"LV",
"LY",
"MA",
"MC",
"MD",
"ME",
"MF",
"MG",
"MH",
"MK",
"ML",
"MM",
"MN",
"MO",
"MP",
"MQ",
"MR",
"MS",
"MT",
"MU",
"MV",
"MW",
"MX",
"MY",
"MZ",
"NA",
"NC",
"NE",
"NF",
"NG",
"NI",
"NL",
"NO",
"NP",
"NR",
"NU",
"NZ",
"OM",
"PA",
"PE",
"PF",
"PG",
"PH",
"PK",
"PL",
"PM",
"PN",
"PR",
"PS",
"PT",
"PW",
"PY",
"QA",
"RE",
"RO",
"RS",
"RU",
"RW",
"SA",
"SB",
"SC",
"SD",
"SE",
"SG",
"SH",
"SI",
"SJ",
"SK",
"SL",
"SM",
"SN",
"SO",
"SR",
"SS",
"ST",
"SV",
"SX",
"SY",
"SZ",
"TC",
"TD",
"TF",
"TG",
"TH",
"TJ",
"TK",
"TL",
"TM",
"TN",
"TO",
"TR",
"TT",
"TV",
"TW",
"TZ",
"UA",
"UG",
"UM",
"US",
"UY",
"UZ",
"VA",
"VC",
"VE",
"VG",
"VI",
"VN",
"VU",
"WF",
"WS",
"YE",
"YT",
"ZA",
"ZM",
"ZW"
];
},{}],53:[function(require,module,exports){
module["exports"] = [
"Avon",
"Bedfordshire",
"Berkshire",
"Borders",
"Buckinghamshire",
"Cambridgeshire"
];
},{}],54:[function(require,module,exports){
module["exports"] = [
"United States of America"
];
},{}],55:[function(require,module,exports){
var address = {};
module['exports'] = address;
address.city_prefix = require("./city_prefix");
address.city_suffix = require("./city_suffix");
address.county = require("./county");
address.country = require("./country");
address.country_code = require("./country_code");
address.building_number = require("./building_number");
address.street_suffix = require("./street_suffix");
address.secondary_address = require("./secondary_address");
address.postcode = require("./postcode");
address.postcode_by_state = require("./postcode_by_state");
address.state = require("./state");
address.state_abbr = require("./state_abbr");
address.time_zone = require("./time_zone");
address.city = require("./city");
address.street_name = require("./street_name");
address.street_address = require("./street_address");
address.default_country = require("./default_country");
},{"./building_number":47,"./city":48,"./city_prefix":49,"./city_suffix":50,"./country":51,"./country_code":52,"./county":53,"./default_country":54,"./postcode":56,"./postcode_by_state":57,"./secondary_address":58,"./state":59,"./state_abbr":60,"./street_address":61,"./street_name":62,"./street_suffix":63,"./time_zone":64}],56:[function(require,module,exports){
module["exports"] = [
"#####",
"#####-####"
];
},{}],57:[function(require,module,exports){
arguments[4][56][0].apply(exports,arguments)
},{"dup":56}],58:[function(require,module,exports){
module["exports"] = [
"Apt. ###",
"Suite ###"
];
},{}],59:[function(require,module,exports){
module["exports"] = [
"Alabama",
"Alaska",
"Arizona",
"Arkansas",
"California",
"Colorado",
"Connecticut",
"Delaware",
"Florida",
"Georgia",
"Hawaii",
"Idaho",
"Illinois",
"Indiana",
"Iowa",
"Kansas",
"Kentucky",
"Louisiana",
"Maine",
"Maryland",
"Massachusetts",
"Michigan",
"Minnesota",
"Mississippi",
"Missouri",
"Montana",
"Nebraska",
"Nevada",
"New Hampshire",
"New Jersey",
"New Mexico",
"New York",
"North Carolina",
"North Dakota",
"Ohio",
"Oklahoma",
"Oregon",
"Pennsylvania",
"Rhode Island",
"South Carolina",
"South Dakota",
"Tennessee",
"Texas",
"Utah",
"Vermont",
"Virginia",
"Washington",
"West Virginia",
"Wisconsin",
"Wyoming"
];
},{}],60:[function(require,module,exports){
module["exports"] = [
"AL",
"AK",
"AZ",
"AR",
"CA",
"CO",
"CT",
"DE",
"FL",
"GA",
"HI",
"ID",
"IL",
"IN",
"IA",
"KS",
"KY",
"LA",
"ME",
"MD",
"MA",
"MI",
"MN",
"MS",
"MO",
"MT",
"NE",
"NV",
"NH",
"NJ",
"NM",
"NY",
"NC",
"ND",
"OH",
"OK",
"OR",
"PA",
"RI",
"SC",
"SD",
"TN",
"TX",
"UT",
"VT",
"VA",
"WA",
"WV",
"WI",
"WY"
];
},{}],61:[function(require,module,exports){
module["exports"] = [
"#{building_number} #{street_name}"
];
},{}],62:[function(require,module,exports){
module["exports"] = [
"#{Name.first_name} #{street_suffix}",
"#{Name.last_name} #{street_suffix}"
];
},{}],63:[function(require,module,exports){
module["exports"] = [
"Alley",
"Avenue",
"Branch",
"Bridge",
"Brook",
"Brooks",
"Burg",
"Burgs",
"Bypass",
"Camp",
"Canyon",
"Cape",
"Causeway",
"Center",
"Centers",
"Circle",
"Circles",
"Cliff",
"Cliffs",
"Club",
"Common",
"Corner",
"Corners",
"Course",
"Court",
"Courts",
"Cove",
"Coves",
"Creek",
"Crescent",
"Crest",
"Crossing",
"Crossroad",
"Curve",
"Dale",
"Dam",
"Divide",
"Drive",
"Drive",
"Drives",
"Estate",
"Estates",
"Expressway",
"Extension",
"Extensions",
"Fall",
"Falls",
"Ferry",
"Field",
"Fields",
"Flat",
"Flats",
"Ford",
"Fords",
"Forest",
"Forge",
"Forges",
"Fork",
"Forks",
"Fort",
"Freeway",
"Garden",
"Gardens",
"Gateway",
"Glen",
"Glens",
"Green",
"Greens",
"Grove",
"Groves",
"Harbor",
"Harbors",
"Haven",
"Heights",
"Highway",
"Hill",
"Hills",
"Hollow",
"Inlet",
"Inlet",
"Island",
"Island",
"Islands",
"Islands",
"Isle",
"Isle",
"Junction",
"Junctions",
"Key",
"Keys",
"Knoll",
"Knolls",
"Lake",
"Lakes",
"Land",
"Landing",
"Lane",
"Light",
"Lights",
"Loaf",
"Lock",
"Locks",
"Locks",
"Lodge",
"Lodge",
"Loop",
"Mall",
"Manor",
"Manors",
"Meadow",
"Meadows",
"Mews",
"Mill",
"Mills",
"Mission",
"Mission",
"Motorway",
"Mount",
"Mountain",
"Mountain",
"Mountains",
"Mountains",
"Neck",
"Orchard",
"Oval",
"Overpass",
"Park",
"Parks",
"Parkway",
"Parkways",
"Pass",
"Passage",
"Path",
"Pike",
"Pine",
"Pines",
"Place",
"Plain",
"Plains",
"Plains",
"Plaza",
"Plaza",
"Point",
"Points",
"Port",
"Port",
"Ports",
"Ports",
"Prairie",
"Prairie",
"Radial",
"Ramp",
"Ranch",
"Rapid",
"Rapids",
"Rest",
"Ridge",
"Ridges",
"River",
"Road",
"Road",
"Roads",
"Roads",
"Route",
"Row",
"Rue",
"Run",
"Shoal",
"Shoals",
"Shore",
"Shores",
"Skyway",
"Spring",
"Springs",
"Springs",
"Spur",
"Spurs",
"Square",
"Square",
"Squares",
"Squares",
"Station",
"Station",
"Stravenue",
"Stravenue",
"Stream",
"Stream",
"Street",
"Street",
"Streets",
"Summit",
"Summit",
"Terrace",
"Throughway",
"Trace",
"Track",
"Trafficway",
"Trail",
"Trail",
"Tunnel",
"Tunnel",
"Turnpike",
"Turnpike",
"Underpass",
"Union",
"Unions",
"Valley",
"Valleys",
"Via",
"Viaduct",
"View",
"Views",
"Village",
"Village",
"Villages",
"Ville",
"Vista",
"Vista",
"Walk",
"Walks",
"Wall",
"Way",
"Ways",
"Well",
"Wells"
];
},{}],64:[function(require,module,exports){
module["exports"] = [
"Pacific/Midway",
"Pacific/Pago_Pago",
"Pacific/Honolulu",
"America/Juneau",
"America/Los_Angeles",
"America/Tijuana",
"America/Denver",
"America/Phoenix",
"America/Chihuahua",
"America/Mazatlan",
"America/Chicago",
"America/Regina",
"America/Mexico_City",
"America/Mexico_City",
"America/Monterrey",
"America/Guatemala",
"America/New_York",
"America/Indiana/Indianapolis",
"America/Bogota",
"America/Lima",
"America/Lima",
"America/Halifax",
"America/Caracas",
"America/La_Paz",
"America/Santiago",
"America/St_Johns",
"America/Sao_Paulo",
"America/Argentina/Buenos_Aires",
"America/Guyana",
"America/Godthab",
"Atlantic/South_Georgia",
"Atlantic/Azores",
"Atlantic/Cape_Verde",
"Europe/Dublin",
"Europe/London",
"Europe/Lisbon",
"Europe/London",
"Africa/Casablanca",
"Africa/Monrovia",
"Etc/UTC",
"Europe/Belgrade",
"Europe/Bratislava",
"Europe/Budapest",
"Europe/Ljubljana",
"Europe/Prague",
"Europe/Sarajevo",
"Europe/Skopje",
"Europe/Warsaw",
"Europe/Zagreb",
"Europe/Brussels",
"Europe/Copenhagen",
"Europe/Madrid",
"Europe/Paris",
"Europe/Amsterdam",
"Europe/Berlin",
"Europe/Berlin",
"Europe/Rome",
"Europe/Stockholm",
"Europe/Vienna",
"Africa/Algiers",
"Europe/Bucharest",
"Africa/Cairo",
"Europe/Helsinki",
"Europe/Kiev",
"Europe/Riga",
"Europe/Sofia",
"Europe/Tallinn",
"Europe/Vilnius",
"Europe/Athens",
"Europe/Istanbul",
"Europe/Minsk",
"Asia/Jerusalem",
"Africa/Harare",
"Africa/Johannesburg",
"Europe/Moscow",
"Europe/Moscow",
"Europe/Moscow",
"Asia/Kuwait",
"Asia/Riyadh",
"Africa/Nairobi",
"Asia/Baghdad",
"Asia/Tehran",
"Asia/Muscat",
"Asia/Muscat",
"Asia/Baku",
"Asia/Tbilisi",
"Asia/Yerevan",
"Asia/Kabul",
"Asia/Yekaterinburg",
"Asia/Karachi",
"Asia/Karachi",
"Asia/Tashkent",
"Asia/Kolkata",
"Asia/Kolkata",
"Asia/Kolkata",
"Asia/Kolkata",
"Asia/Kathmandu",
"Asia/Dhaka",
"Asia/Dhaka",
"Asia/Colombo",
"Asia/Almaty",
"Asia/Novosibirsk",
"Asia/Rangoon",
"Asia/Bangkok",
"Asia/Bangkok",
"Asia/Jakarta",
"Asia/Krasnoyarsk",
"Asia/Shanghai",
"Asia/Chongqing",
"Asia/Hong_Kong",
"Asia/Urumqi",
"Asia/Kuala_Lumpur",
"Asia/Singapore",
"Asia/Taipei",
"Australia/Perth",
"Asia/Irkutsk",
"Asia/Ulaanbaatar",
"Asia/Seoul",
"Asia/Tokyo",
"Asia/Tokyo",
"Asia/Tokyo",
"Asia/Yakutsk",
"Australia/Darwin",
"Australia/Adelaide",
"Australia/Melbourne",
"Australia/Melbourne",
"Australia/Sydney",
"Australia/Brisbane",
"Australia/Hobart",
"Asia/Vladivostok",
"Pacific/Guam",
"Pacific/Port_Moresby",
"Asia/Magadan",
"Asia/Magadan",
"Pacific/Noumea",
"Pacific/Fiji",
"Asia/Kamchatka",
"Pacific/Majuro",
"Pacific/Auckland",
"Pacific/Auckland",
"Pacific/Tongatapu",
"Pacific/Fakaofo",
"Pacific/Apia"
];
},{}],65:[function(require,module,exports){
module["exports"] = [
"#{Name.name}",
"#{Company.name}"
];
},{}],66:[function(require,module,exports){
var app = {};
module['exports'] = app;
app.name = require("./name");
app.version = require("./version");
app.author = require("./author");
},{"./author":65,"./name":67,"./version":68}],67:[function(require,module,exports){
module["exports"] = [
"Redhold",
"Treeflex",
"Trippledex",
"Kanlam",
"Bigtax",
"Daltfresh",
"Toughjoyfax",
"Mat Lam Tam",
"Otcom",
"Tres-Zap",
"Y-Solowarm",
"Tresom",
"Voltsillam",
"Biodex",
"Greenlam",
"Viva",
"Matsoft",
"Temp",
"Zoolab",
"Subin",
"Rank",
"Job",
"Stringtough",
"Tin",
"It",
"Home Ing",
"Zamit",
"Sonsing",
"Konklab",
"Alpha",
"Latlux",
"Voyatouch",
"Alphazap",
"Holdlamis",
"Zaam-Dox",
"Sub-Ex",
"Quo Lux",
"Bamity",
"Ventosanzap",
"Lotstring",
"Hatity",
"Tempsoft",
"Overhold",
"Fixflex",
"Konklux",
"Zontrax",
"Tampflex",
"Span",
"Namfix",
"Transcof",
"Stim",
"Fix San",
"Sonair",
"Stronghold",
"Fintone",
"Y-find",
"Opela",
"Lotlux",
"Ronstring",
"Zathin",
"Duobam",
"Keylex"
];
},{}],68:[function(require,module,exports){
module["exports"] = [
"0.#.#",
"0.##",
"#.##",
"#.#",
"#.#.#"
];
},{}],69:[function(require,module,exports){
module["exports"] = [
"2011-10-12",
"2012-11-12",
"2015-11-11",
"2013-9-12"
];
},{}],70:[function(require,module,exports){
module["exports"] = [
"1234-2121-1221-1211",
"1212-1221-1121-1234",
"1211-1221-1234-2201",
"1228-1221-1221-1431"
];
},{}],71:[function(require,module,exports){
module["exports"] = [
"visa",
"mastercard",
"americanexpress",
"discover"
];
},{}],72:[function(require,module,exports){
var business = {};
module['exports'] = business;
business.credit_card_numbers = require("./credit_card_numbers");
business.credit_card_expiry_dates = require("./credit_card_expiry_dates");
business.credit_card_types = require("./credit_card_types");
},{"./credit_card_expiry_dates":69,"./credit_card_numbers":70,"./credit_card_types":71}],73:[function(require,module,exports){
module["exports"] = [
"###-###-####",
"(###) ###-####",
"1-###-###-####",
"###.###.####"
];
},{}],74:[function(require,module,exports){
var cell_phone = {};
module['exports'] = cell_phone;
cell_phone.formats = require("./formats");
},{"./formats":73}],75:[function(require,module,exports){
module["exports"] = [
"red",
"green",
"blue",
"yellow",
"purple",
"mint green",
"teal",
"white",
"black",
"orange",
"pink",
"grey",
"maroon",
"violet",
"turquoise",
"tan",
"sky blue",
"salmon",
"plum",
"orchid",
"olive",
"magenta",
"lime",
"ivory",
"indigo",
"gold",
"fuchsia",
"cyan",
"azure",
"lavender",
"silver"
];
},{}],76:[function(require,module,exports){
module["exports"] = [
"Books",
"Movies",
"Music",
"Games",
"Electronics",
"Computers",
"Home",
"Garden",
"Tools",
"Grocery",
"Health",
"Beauty",
"Toys",
"Kids",
"Baby",
"Clothing",
"Shoes",
"Jewelery",
"Sports",
"Outdoors",
"Automotive",
"Industrial"
];
},{}],77:[function(require,module,exports){
var commerce = {};
module['exports'] = commerce;
commerce.color = require("./color");
commerce.department = require("./department");
commerce.product_name = require("./product_name");
},{"./color":75,"./department":76,"./product_name":78}],78:[function(require,module,exports){
module["exports"] = {
"adjective": [
"Small",
"Ergonomic",
"Rustic",
"Intelligent",
"Gorgeous",
"Incredible",
"Fantastic",
"Practical",
"Sleek",
"Awesome",
"Generic",
"Handcrafted",
"Handmade",
"Licensed",
"Refined",
"Unbranded",
"Tasty"
],
"material": [
"Steel",
"Wooden",
"Concrete",
"Plastic",
"Cotton",
"Granite",
"Rubber",
"Metal",
"Soft",
"Fresh",
"Frozen"
],
"product": [
"Chair",
"Car",
"Computer",
"Keyboard",
"Mouse",
"Bike",
"Ball",
"Gloves",
"Pants",
"Shirt",
"Table",
"Shoes",
"Hat",
"Towels",
"Soap",
"Tuna",
"Chicken",
"Fish",
"Cheese",
"Bacon",
"Pizza",
"Salad",
"Sausages",
"Chips"
]
};
},{}],79:[function(require,module,exports){
module["exports"] = [
"Adaptive",
"Advanced",
"Ameliorated",
"Assimilated",
"Automated",
"Balanced",
"Business-focused",
"Centralized",
"Cloned",
"Compatible",
"Configurable",
"Cross-group",
"Cross-platform",
"Customer-focused",
"Customizable",
"Decentralized",
"De-engineered",
"Devolved",
"Digitized",
"Distributed",
"Diverse",
"Down-sized",
"Enhanced",
"Enterprise-wide",
"Ergonomic",
"Exclusive",
"Expanded",
"Extended",
"Face to face",
"Focused",
"Front-line",
"Fully-configurable",
"Function-based",
"Fundamental",
"Future-proofed",
"Grass-roots",
"Horizontal",
"Implemented",
"Innovative",
"Integrated",
"Intuitive",
"Inverse",
"Managed",
"Mandatory",
"Monitored",
"Multi-channelled",
"Multi-lateral",
"Multi-layered",
"Multi-tiered",
"Networked",
"Object-based",
"Open-architected",
"Open-source",
"Operative",
"Optimized",
"Optional",
"Organic",
"Organized",
"Persevering",
"Persistent",
"Phased",
"Polarised",
"Pre-emptive",
"Proactive",
"Profit-focused",
"Profound",
"Programmable",
"Progressive",
"Public-key",
"Quality-focused",
"Reactive",
"Realigned",
"Re-contextualized",
"Re-engineered",
"Reduced",
"Reverse-engineered",
"Right-sized",
"Robust",
"Seamless",
"Secured",
"Self-enabling",
"Sharable",
"Stand-alone",
"Streamlined",
"Switchable",
"Synchronised",
"Synergistic",
"Synergized",
"Team-oriented",
"Total",
"Triple-buffered",
"Universal",
"Up-sized",
"Upgradable",
"User-centric",
"User-friendly",
"Versatile",
"Virtual",
"Visionary",
"Vision-oriented"
];
},{}],80:[function(require,module,exports){
module["exports"] = [
"clicks-and-mortar",
"value-added",
"vertical",
"proactive",
"robust",
"revolutionary",
"scalable",
"leading-edge",
"innovative",
"intuitive",
"strategic",
"e-business",
"mission-critical",
"sticky",
"one-to-one",
"24/7",
"end-to-end",
"global",
"B2B",
"B2C",
"granular",
"frictionless",
"virtual",
"viral",
"dynamic",
"24/365",
"best-of-breed",
"killer",
"magnetic",
"bleeding-edge",
"web-enabled",
"interactive",
"dot-com",
"sexy",
"back-end",
"real-time",
"efficient",
"front-end",
"distributed",
"seamless",
"extensible",
"turn-key",
"world-class",
"open-source",
"cross-platform",
"cross-media",
"synergistic",
"bricks-and-clicks",
"out-of-the-box",
"enterprise",
"integrated",
"impactful",
"wireless",
"transparent",
"next-generation",
"cutting-edge",
"user-centric",
"visionary",
"customized",
"ubiquitous",
"plug-and-play",
"collaborative",
"compelling",
"holistic",
"rich"
];
},{}],81:[function(require,module,exports){
module["exports"] = [
"synergies",
"web-readiness",
"paradigms",
"markets",
"partnerships",
"infrastructures",
"platforms",
"initiatives",
"channels",
"eyeballs",
"communities",
"ROI",
"solutions",
"e-tailers",
"e-services",
"action-items",
"portals",
"niches",
"technologies",
"content",
"vortals",
"supply-chains",
"convergence",
"relationships",
"architectures",
"interfaces",
"e-markets",
"e-commerce",
"systems",
"bandwidth",
"infomediaries",
"models",
"mindshare",
"deliverables",
"users",
"schemas",
"networks",
"applications",
"metrics",
"e-business",
"functionalities",
"experiences",
"web services",
"methodologies"
];
},{}],82:[function(require,module,exports){
module["exports"] = [
"implement",
"utilize",
"integrate",
"streamline",
"optimize",
"evolve",
"transform",
"embrace",
"enable",
"orchestrate",
"leverage",
"reinvent",
"aggregate",
"architect",
"enhance",
"incentivize",
"morph",
"empower",
"envisioneer",
"monetize",
"harness",
"facilitate",
"seize",
"disintermediate",
"synergize",
"strategize",
"deploy",
"brand",
"grow",
"target",
"syndicate",
"synthesize",
"deliver",
"mesh",
"incubate",
"engage",
"maximize",
"benchmark",
"expedite",
"reintermediate",
"whiteboard",
"visualize",
"repurpose",
"innovate",
"scale",
"unleash",
"drive",
"extend",
"engineer",
"revolutionize",
"generate",
"exploit",
"transition",
"e-enable",
"iterate",
"cultivate",
"matrix",
"productize",
"redefine",
"recontextualize"
];
},{}],83:[function(require,module,exports){
module["exports"] = [
"24 hour",
"24/7",
"3rd generation",
"4th generation",
"5th generation",
"6th generation",
"actuating",
"analyzing",
"asymmetric",
"asynchronous",
"attitude-oriented",
"background",
"bandwidth-monitored",
"bi-directional",
"bifurcated",
"bottom-line",
"clear-thinking",
"client-driven",
"client-server",
"coherent",
"cohesive",
"composite",
"context-sensitive",
"contextually-based",
"content-based",
"dedicated",
"demand-driven",
"didactic",
"directional",
"discrete",
"disintermediate",
"dynamic",
"eco-centric",
"empowering",
"encompassing",
"even-keeled",
"executive",
"explicit",
"exuding",
"fault-tolerant",
"foreground",
"fresh-thinking",
"full-range",
"global",
"grid-enabled",
"heuristic",
"high-level",
"holistic",
"homogeneous",
"human-resource",
"hybrid",
"impactful",
"incremental",
"intangible",
"interactive",
"intermediate",
"leading edge",
"local",
"logistical",
"maximized",
"methodical",
"mission-critical",
"mobile",
"modular",
"motivating",
"multimedia",
"multi-state",
"multi-tasking",
"national",
"needs-based",
"neutral",
"next generation",
"non-volatile",
"object-oriented",
"optimal",
"optimizing",
"radical",
"real-time",
"reciprocal",
"regional",
"responsive",
"scalable",
"secondary",
"solution-oriented",
"stable",
"static",
"systematic",
"systemic",
"system-worthy",
"tangible",
"tertiary",
"transitional",
"uniform",
"upward-trending",
"user-facing",
"value-added",
"web-enabled",
"well-modulated",
"zero administration",
"zero defect",
"zero tolerance"
];
},{}],84:[function(require,module,exports){
var company = {};
module['exports'] = company;
company.suffix = require("./suffix");
company.adjective = require("./adjective");
company.descriptor = require("./descriptor");
company.noun = require("./noun");
company.bs_verb = require("./bs_verb");
company.bs_adjective = require("./bs_adjective");
company.bs_noun = require("./bs_noun");
company.name = require("./name");
},{"./adjective":79,"./bs_adjective":80,"./bs_noun":81,"./bs_verb":82,"./descriptor":83,"./name":85,"./noun":86,"./suffix":87}],85:[function(require,module,exports){
module["exports"] = [
"#{Name.last_name} #{suffix}",
"#{Name.last_name}-#{Name.last_name}",
"#{Name.last_name}, #{Name.last_name} and #{Name.last_name}"
];
},{}],86:[function(require,module,exports){
module["exports"] = [
"ability",
"access",
"adapter",
"algorithm",
"alliance",
"analyzer",
"application",
"approach",
"architecture",
"archive",
"artificial intelligence",
"array",
"attitude",
"benchmark",
"budgetary management",
"capability",
"capacity",
"challenge",
"circuit",
"collaboration",
"complexity",
"concept",
"conglomeration",
"contingency",
"core",
"customer loyalty",
"database",
"data-warehouse",
"definition",
"emulation",
"encoding",
"encryption",
"extranet",
"firmware",
"flexibility",
"focus group",
"forecast",
"frame",
"framework",
"function",
"functionalities",
"Graphic Interface",
"groupware",
"Graphical User Interface",
"hardware",
"help-desk",
"hierarchy",
"hub",
"implementation",
"info-mediaries",
"infrastructure",
"initiative",
"installation",
"instruction set",
"interface",
"internet solution",
"intranet",
"knowledge user",
"knowledge base",
"local area network",
"leverage",
"matrices",
"matrix",
"methodology",
"middleware",
"migration",
"model",
"moderator",
"monitoring",
"moratorium",
"neural-net",
"open architecture",
"open system",
"orchestration",
"paradigm",
"parallelism",
"policy",
"portal",
"pricing structure",
"process improvement",
"product",
"productivity",
"project",
"projection",
"protocol",
"secured line",
"service-desk",
"software",
"solution",
"standardization",
"strategy",
"structure",
"success",
"superstructure",
"support",
"synergy",
"system engine",
"task-force",
"throughput",
"time-frame",
"toolset",
"utilisation",
"website",
"workforce"
];
},{}],87:[function(require,module,exports){
module["exports"] = [
"Inc",
"and Sons",
"LLC",
"Group"
];
},{}],88:[function(require,module,exports){
module["exports"] = [
"/34##-######-####L/",
"/37##-######-####L/"
];
},{}],89:[function(require,module,exports){
module["exports"] = [
"/30[0-5]#-######-###L/",
"/368#-######-###L/"
];
},{}],90:[function(require,module,exports){
module["exports"] = [
"/6011-####-####-###L/",
"/65##-####-####-###L/",
"/64[4-9]#-####-####-###L/",
"/6011-62##-####-####-###L/",
"/65##-62##-####-####-###L/",
"/64[4-9]#-62##-####-####-###L/"
];
},{}],91:[function(require,module,exports){
var credit_card = {};
module['exports'] = credit_card;
credit_card.visa = require("./visa");
credit_card.mastercard = require("./mastercard");
credit_card.discover = require("./discover");
credit_card.american_express = require("./american_express");
credit_card.diners_club = require("./diners_club");
credit_card.jcb = require("./jcb");
credit_card.switch = require("./switch");
credit_card.solo = require("./solo");
credit_card.maestro = require("./maestro");
credit_card.laser = require("./laser");
},{"./american_express":88,"./diners_club":89,"./discover":90,"./jcb":92,"./laser":93,"./maestro":94,"./mastercard":95,"./solo":96,"./switch":97,"./visa":98}],92:[function(require,module,exports){
module["exports"] = [
"/3528-####-####-###L/",
"/3529-####-####-###L/",
"/35[3-8]#-####-####-###L/"
];
},{}],93:[function(require,module,exports){
module["exports"] = [
"/6304###########L/",
"/6706###########L/",
"/6771###########L/",
"/6709###########L/",
"/6304#########{5,6}L/",
"/6706#########{5,6}L/",
"/6771#########{5,6}L/",
"/6709#########{5,6}L/"
];
},{}],94:[function(require,module,exports){
module["exports"] = [
"/50#{9,16}L/",
"/5[6-8]#{9,16}L/",
"/56##{9,16}L/"
];
},{}],95:[function(require,module,exports){
module["exports"] = [
"/5[1-5]##-####-####-###L/",
"/6771-89##-####-###L/"
];
},{}],96:[function(require,module,exports){
module["exports"] = [
"/6767-####-####-###L/",
"/6767-####-####-####-#L/",
"/6767-####-####-####-##L/"
];
},{}],97:[function(require,module,exports){
module["exports"] = [
"/6759-####-####-###L/",
"/6759-####-####-####-#L/",
"/6759-####-####-####-##L/"
];
},{}],98:[function(require,module,exports){
module["exports"] = [
"/4###########L/",
"/4###-####-####-###L/"
];
},{}],99:[function(require,module,exports){
var date = {};
module["exports"] = date;
date.month = require("./month");
date.weekday = require("./weekday");
},{"./month":100,"./weekday":101}],100:[function(require,module,exports){
// Source: http://unicode.org/cldr/trac/browser/tags/release-27/common/main/en.xml#L1799
module["exports"] = {
wide: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
// Property "wide_context" is optional, if not set then "wide" will be used instead
// It is used to specify a word in context, which may differ from a stand-alone word
wide_context: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
abbr: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
// Property "abbr_context" is optional, if not set then "abbr" will be used instead
// It is used to specify a word in context, which may differ from a stand-alone word
abbr_context: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
]
};
},{}],101:[function(require,module,exports){
// Source: http://unicode.org/cldr/trac/browser/tags/release-27/common/main/en.xml#L1847
module["exports"] = {
wide: [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
// Property "wide_context" is optional, if not set then "wide" will be used instead
// It is used to specify a word in context, which may differ from a stand-alone word
wide_context: [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
abbr: [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
// Property "abbr_context" is optional, if not set then "abbr" will be used instead
// It is used to specify a word in context, which may differ from a stand-alone word
abbr_context: [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
]
};
},{}],102:[function(require,module,exports){
module["exports"] = [
"Checking",
"Savings",
"Money Market",
"Investment",
"Home Loan",
"Credit Card",
"Auto Loan",
"Personal Loan"
];
},{}],103:[function(require,module,exports){
module["exports"] = {
"UAE Dirham": {
"code": "AED",
"symbol": ""
},
"Afghani": {
"code": "AFN",
"symbol": "؋"
},
"Lek": {
"code": "ALL",
"symbol": "Lek"
},
"Armenian Dram": {
"code": "AMD",
"symbol": ""
},
"Netherlands Antillian Guilder": {
"code": "ANG",
"symbol": "ƒ"
},
"Kwanza": {
"code": "AOA",
"symbol": ""
},
"Argentine Peso": {
"code": "ARS",
"symbol": "$"
},
"Australian Dollar": {
"code": "AUD",
"symbol": "$"
},
"Aruban Guilder": {
"code": "AWG",
"symbol": "ƒ"
},
"Azerbaijanian Manat": {
"code": "AZN",
"symbol": "ман"
},
"Convertible Marks": {
"code": "BAM",
"symbol": "KM"
},
"Barbados Dollar": {
"code": "BBD",
"symbol": "$"
},
"Taka": {
"code": "BDT",
"symbol": ""
},
"Bulgarian Lev": {
"code": "BGN",
"symbol": "лв"
},
"Bahraini Dinar": {
"code": "BHD",
"symbol": ""
},
"Burundi Franc": {
"code": "BIF",
"symbol": ""
},
"Bermudian Dollar (customarily known as Bermuda Dollar)": {
"code": "BMD",
"symbol": "$"
},
"Brunei Dollar": {
"code": "BND",
"symbol": "$"
},
"Boliviano Mvdol": {
"code": "BOB BOV",
"symbol": "$b"
},
"Brazilian Real": {
"code": "BRL",
"symbol": "R$"
},
"Bahamian Dollar": {
"code": "BSD",
"symbol": "$"
},
"Pula": {
"code": "BWP",
"symbol": "P"
},
"Belarussian Ruble": {
"code": "BYR",
"symbol": "p."
},
"Belize Dollar": {
"code": "BZD",
"symbol": "BZ$"
},
"Canadian Dollar": {
"code": "CAD",
"symbol": "$"
},
"Congolese Franc": {
"code": "CDF",
"symbol": ""
},
"Swiss Franc": {
"code": "CHF",
"symbol": "CHF"
},
"Chilean Peso Unidades de fomento": {
"code": "CLP CLF",
"symbol": "$"
},
"Yuan Renminbi": {
"code": "CNY",
"symbol": "¥"
},
"Colombian Peso Unidad de Valor Real": {
"code": "COP COU",
"symbol": "$"
},
"Costa Rican Colon": {
"code": "CRC",
"symbol": "₡"
},
"Cuban Peso Peso Convertible": {
"code": "CUP CUC",
"symbol": "₱"
},
"Cape Verde Escudo": {
"code": "CVE",
"symbol": ""
},
"Czech Koruna": {
"code": "CZK",
"symbol": "Kč"
},
"Djibouti Franc": {
"code": "DJF",
"symbol": ""
},
"Danish Krone": {
"code": "DKK",
"symbol": "kr"
},
"Dominican Peso": {
"code": "DOP",
"symbol": "RD$"
},
"Algerian Dinar": {
"code": "DZD",
"symbol": ""
},
"Kroon": {
"code": "EEK",
"symbol": ""
},
"Egyptian Pound": {
"code": "EGP",
"symbol": "£"
},
"Nakfa": {
"code": "ERN",
"symbol": ""
},
"Ethiopian Birr": {
"code": "ETB",
"symbol": ""
},
"Euro": {
"code": "EUR",
"symbol": "€"
},
"Fiji Dollar": {
"code": "FJD",
"symbol": "$"
},
"Falkland Islands Pound": {
"code": "FKP",
"symbol": "£"
},
"Pound Sterling": {
"code": "GBP",
"symbol": "£"
},
"Lari": {
"code": "GEL",
"symbol": ""
},
"Cedi": {
"code": "GHS",
"symbol": ""
},
"Gibraltar Pound": {
"code": "GIP",
"symbol": "£"
},
"Dalasi": {
"code": "GMD",
"symbol": ""
},
"Guinea Franc": {
"code": "GNF",
"symbol": ""
},
"Quetzal": {
"code": "GTQ",
"symbol": "Q"
},
"Guyana Dollar": {
"code": "GYD",
"symbol": "$"
},
"Hong Kong Dollar": {
"code": "HKD",
"symbol": "$"
},
"Lempira": {
"code": "HNL",
"symbol": "L"
},
"Croatian Kuna": {
"code": "HRK",
"symbol": "kn"
},
"Gourde US Dollar": {
"code": "HTG USD",
"symbol": ""
},
"Forint": {
"code": "HUF",
"symbol": "Ft"
},
"Rupiah": {
"code": "IDR",
"symbol": "Rp"
},
"New Israeli Sheqel": {
"code": "ILS",
"symbol": "₪"
},
"Indian Rupee": {
"code": "INR",
"symbol": ""
},
"Indian Rupee Ngultrum": {
"code": "INR BTN",
"symbol": ""
},
"Iraqi Dinar": {
"code": "IQD",
"symbol": ""
},
"Iranian Rial": {
"code": "IRR",
"symbol": "﷼"
},
"Iceland Krona": {
"code": "ISK",
"symbol": "kr"
},
"Jamaican Dollar": {
"code": "JMD",
"symbol": "J$"
},
"Jordanian Dinar": {
"code": "JOD",
"symbol": ""
},
"Yen": {
"code": "JPY",
"symbol": "¥"
},
"Kenyan Shilling": {
"code": "KES",
"symbol": ""
},
"Som": {
"code": "KGS",
"symbol": "лв"
},
"Riel": {
"code": "KHR",
"symbol": "៛"
},
"Comoro Franc": {
"code": "KMF",
"symbol": ""
},
"North Korean Won": {
"code": "KPW",
"symbol": "₩"
},
"Won": {
"code": "KRW",
"symbol": "₩"
},
"Kuwaiti Dinar": {
"code": "KWD",
"symbol": ""
},
"Cayman Islands Dollar": {
"code": "KYD",
"symbol": "$"
},
"Tenge": {
"code": "KZT",
"symbol": "лв"
},
"Kip": {
"code": "LAK",
"symbol": "₭"
},
"Lebanese Pound": {
"code": "LBP",
"symbol": "£"
},
"Sri Lanka Rupee": {
"code": "LKR",
"symbol": "₨"
},
"Liberian Dollar": {
"code": "LRD",
"symbol": "$"
},
"Lithuanian Litas": {
"code": "LTL",
"symbol": "Lt"
},
"Latvian Lats": {
"code": "LVL",
"symbol": "Ls"
},
"Libyan Dinar": {
"code": "LYD",
"symbol": ""
},
"Moroccan Dirham": {
"code": "MAD",
"symbol": ""
},
"Moldovan Leu": {
"code": "MDL",
"symbol": ""
},
"Malagasy Ariary": {
"code": "MGA",
"symbol": ""
},
"Denar": {
"code": "MKD",
"symbol": "ден"
},
"Kyat": {
"code": "MMK",
"symbol": ""
},
"Tugrik": {
"code": "MNT",
"symbol": "₮"
},
"Pataca": {
"code": "MOP",
"symbol": ""
},
"Ouguiya": {
"code": "MRO",
"symbol": ""
},
"Mauritius Rupee": {
"code": "MUR",
"symbol": "₨"
},
"Rufiyaa": {
"code": "MVR",
"symbol": ""
},
"Kwacha": {
"code": "MWK",
"symbol": ""
},
"Mexican Peso Mexican Unidad de Inversion (UDI)": {
"code": "MXN MXV",
"symbol": "$"
},
"Malaysian Ringgit": {
"code": "MYR",
"symbol": "RM"
},
"Metical": {
"code": "MZN",
"symbol": "MT"
},
"Naira": {
"code": "NGN",
"symbol": "₦"
},
"Cordoba Oro": {
"code": "NIO",
"symbol": "C$"
},
"Norwegian Krone": {
"code": "NOK",
"symbol": "kr"
},
"Nepalese Rupee": {
"code": "NPR",
"symbol": "₨"
},
"New Zealand Dollar": {
"code": "NZD",
"symbol": "$"
},
"Rial Omani": {
"code": "OMR",
"symbol": "﷼"
},
"Balboa US Dollar": {
"code": "PAB USD",
"symbol": "B/."
},
"Nuevo Sol": {
"code": "PEN",
"symbol": "S/."
},
"Kina": {
"code": "PGK",
"symbol": ""
},
"Philippine Peso": {
"code": "PHP",
"symbol": "Php"
},
"Pakistan Rupee": {
"code": "PKR",
"symbol": "₨"
},
"Zloty": {
"code": "PLN",
"symbol": "zł"
},
"Guarani": {
"code": "PYG",
"symbol": "Gs"
},
"Qatari Rial": {
"code": "QAR",
"symbol": "﷼"
},
"New Leu": {
"code": "RON",
"symbol": "lei"
},
"Serbian Dinar": {
"code": "RSD",
"symbol": "Дин."
},
"Russian Ruble": {
"code": "RUB",
"symbol": "руб"
},
"Rwanda Franc": {
"code": "RWF",
"symbol": ""
},
"Saudi Riyal": {
"code": "SAR",
"symbol": "﷼"
},
"Solomon Islands Dollar": {
"code": "SBD",
"symbol": "$"
},
"Seychelles Rupee": {
"code": "SCR",
"symbol": "₨"
},
"Sudanese Pound": {
"code": "SDG",
"symbol": ""
},
"Swedish Krona": {
"code": "SEK",
"symbol": "kr"
},
"Singapore Dollar": {
"code": "SGD",
"symbol": "$"
},
"Saint Helena Pound": {
"code": "SHP",
"symbol": "£"
},
"Leone": {
"code": "SLL",
"symbol": ""
},
"Somali Shilling": {
"code": "SOS",
"symbol": "S"
},
"Surinam Dollar": {
"code": "SRD",
"symbol": "$"
},
"Dobra": {
"code": "STD",
"symbol": ""
},
"El Salvador Colon US Dollar": {
"code": "SVC USD",
"symbol": "$"
},
"Syrian Pound": {
"code": "SYP",
"symbol": "£"
},
"Lilangeni": {
"code": "SZL",
"symbol": ""
},
"Baht": {
"code": "THB",
"symbol": "฿"
},
"Somoni": {
"code": "TJS",
"symbol": ""
},
"Manat": {
"code": "TMT",
"symbol": ""
},
"Tunisian Dinar": {
"code": "TND",
"symbol": ""
},
"Pa'anga": {
"code": "TOP",
"symbol": ""
},
"Turkish Lira": {
"code": "TRY",
"symbol": "TL"
},
"Trinidad and Tobago Dollar": {
"code": "TTD",
"symbol": "TT$"
},
"New Taiwan Dollar": {
"code": "TWD",
"symbol": "NT$"
},
"Tanzanian Shilling": {
"code": "TZS",
"symbol": ""
},
"Hryvnia": {
"code": "UAH",
"symbol": "₴"
},
"Uganda Shilling": {
"code": "UGX",
"symbol": ""
},
"US Dollar": {
"code": "USD",
"symbol": "$"
},
"Peso Uruguayo Uruguay Peso en Unidades Indexadas": {
"code": "UYU UYI",
"symbol": "$U"
},
"Uzbekistan Sum": {
"code": "UZS",
"symbol": "лв"
},
"Bolivar Fuerte": {
"code": "VEF",
"symbol": "Bs"
},
"Dong": {
"code": "VND",
"symbol": "₫"
},
"Vatu": {
"code": "VUV",
"symbol": ""
},
"Tala": {
"code": "WST",
"symbol": ""
},
"CFA Franc BEAC": {
"code": "XAF",
"symbol": ""
},
"Silver": {
"code": "XAG",
"symbol": ""
},
"Gold": {
"code": "XAU",
"symbol": ""
},
"Bond Markets Units European Composite Unit (EURCO)": {
"code": "XBA",
"symbol": ""
},
"European Monetary Unit (E.M.U.-6)": {
"code": "XBB",
"symbol": ""
},
"European Unit of Account 9(E.U.A.-9)": {
"code": "XBC",
"symbol": ""
},
"European Unit of Account 17(E.U.A.-17)": {
"code": "XBD",
"symbol": ""
},
"East Caribbean Dollar": {
"code": "XCD",
"symbol": "$"
},
"SDR": {
"code": "XDR",
"symbol": ""
},
"UIC-Franc": {
"code": "XFU",
"symbol": ""
},
"CFA Franc BCEAO": {
"code": "XOF",
"symbol": ""
},
"Palladium": {
"code": "XPD",
"symbol": ""
},
"CFP Franc": {
"code": "XPF",
"symbol": ""
},
"Platinum": {
"code": "XPT",
"symbol": ""
},
"Codes specifically reserved for testing purposes": {
"code": "XTS",
"symbol": ""
},
"Yemeni Rial": {
"code": "YER",
"symbol": "﷼"
},
"Rand": {
"code": "ZAR",
"symbol": "R"
},
"Rand Loti": {
"code": "ZAR LSL",
"symbol": ""
},
"Rand Namibia Dollar": {
"code": "ZAR NAD",
"symbol": ""
},
"Zambian Kwacha": {
"code": "ZMK",
"symbol": ""
},
"Zimbabwe Dollar": {
"code": "ZWL",
"symbol": ""
}
};
},{}],104:[function(require,module,exports){
var finance = {};
module['exports'] = finance;
finance.account_type = require("./account_type");
finance.transaction_type = require("./transaction_type");
finance.currency = require("./currency");
},{"./account_type":102,"./currency":103,"./transaction_type":105}],105:[function(require,module,exports){
module["exports"] = [
"deposit",
"withdrawal",
"payment",
"invoice"
];
},{}],106:[function(require,module,exports){
module["exports"] = [
"TCP",
"HTTP",
"SDD",
"RAM",
"GB",
"CSS",
"SSL",
"AGP",
"SQL",
"FTP",
"PCI",
"AI",
"ADP",
"RSS",
"XML",
"EXE",
"COM",
"HDD",
"THX",
"SMTP",
"SMS",
"USB",
"PNG",
"SAS",
"IB",
"SCSI",
"JSON",
"XSS",
"JBOD"
];
},{}],107:[function(require,module,exports){
module["exports"] = [
"auxiliary",
"primary",
"back-end",
"digital",
"open-source",
"virtual",
"cross-platform",
"redundant",
"online",
"haptic",
"multi-byte",
"bluetooth",
"wireless",
"1080p",
"neural",
"optical",
"solid state",
"mobile"
];
},{}],108:[function(require,module,exports){
var hacker = {};
module['exports'] = hacker;
hacker.abbreviation = require("./abbreviation");
hacker.adjective = require("./adjective");
hacker.noun = require("./noun");
hacker.verb = require("./verb");
hacker.ingverb = require("./ingverb");
},{"./abbreviation":106,"./adjective":107,"./ingverb":109,"./noun":110,"./verb":111}],109:[function(require,module,exports){
module["exports"] = [
"backing up",
"bypassing",
"hacking",
"overriding",
"compressing",
"copying",
"navigating",
"indexing",
"connecting",
"generating",
"quantifying",
"calculating",
"synthesizing",
"transmitting",
"programming",
"parsing"
];
},{}],110:[function(require,module,exports){
module["exports"] = [
"driver",
"protocol",
"bandwidth",
"panel",
"microchip",
"program",
"port",
"card",
"array",
"interface",
"system",
"sensor",
"firewall",
"hard drive",
"pixel",
"alarm",
"feed",
"monitor",
"application",
"transmitter",
"bus",
"circuit",
"capacitor",
"matrix"
];
},{}],111:[function(require,module,exports){
module["exports"] = [
"back up",
"bypass",
"hack",
"override",
"compress",
"copy",
"navigate",
"index",
"connect",
"generate",
"quantify",
"calculate",
"synthesize",
"input",
"transmit",
"program",
"reboot",
"parse"
];
},{}],112:[function(require,module,exports){
var en = {};
module['exports'] = en;
en.title = "English";
en.separator = " & ";
en.address = require("./address");
en.credit_card = require("./credit_card");
en.company = require("./company");
en.internet = require("./internet");
en.lorem = require("./lorem");
en.name = require("./name");
en.phone_number = require("./phone_number");
en.cell_phone = require("./cell_phone");
en.business = require("./business");
en.commerce = require("./commerce");
en.team = require("./team");
en.hacker = require("./hacker");
en.app = require("./app");
en.finance = require("./finance");
en.date = require("./date");
en.system = require("./system");
},{"./address":55,"./app":66,"./business":72,"./cell_phone":74,"./commerce":77,"./company":84,"./credit_card":91,"./date":99,"./finance":104,"./hacker":108,"./internet":117,"./lorem":118,"./name":122,"./phone_number":129,"./system":130,"./team":133}],113:[function(require,module,exports){
module["exports"] = [
"https://s3.amazonaws.com/uifaces/faces/twitter/jarjan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mahdif/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sprayaga/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ruzinav/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Skyhartman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/moscoz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kurafire/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/91bilal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/igorgarybaldi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/malykhinv/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joelhelin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kushsolitary/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/coreyweb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/snowshade/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/areus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/holdenweb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/heyimjuani/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/envex/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/unterdreht/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/collegeman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/peejfancher/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andyisonline/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ultragex/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fuck_you_two/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adellecharles/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ateneupopular/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ahmetalpbalkan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Stievius/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kerem/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/osvaldas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/angelceballos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thierrykoblentz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/peterlandt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/catarino/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/weglov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brandclay/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/flame_kaizar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ahmetsulek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nicolasfolliot/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jayrobinson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victorerixon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kolage/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michzen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/markjenkins/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nicolai_larsen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/noxdzine/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alagoon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/idiot/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mizko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chadengle/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mutlu82/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/simobenso/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vocino/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/guiiipontes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/soyjavi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joshaustin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tomaslau/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/VinThomas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ManikRathee/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/langate/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cemshid/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/leemunroe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_shahedk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/enda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/BillSKenney/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/divya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joshhemsley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sindresorhus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/soffes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/9lessons/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/linux29/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Chakintosh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anaami/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joreira/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shadeed9/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scottkclark/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jedbridges/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/salleedesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marakasina/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ariil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/BrianPurkiss/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelmartinho/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bublienko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/devankoshal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ZacharyZorbas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/timmillwood/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joshuasortino/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/damenleeturks/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tomas_janousek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/herrhaase/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/RussellBishop/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brajeshwar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nachtmeister/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cbracco/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bermonpainter/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abdullindenis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/isacosta/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/suprb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yalozhkin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chandlervdw/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamgarth/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_victa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/commadelimited/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/roybarberuk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/axel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vladarbatov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ffbel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/syropian/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ankitind/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/traneblow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/flashmurphy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ChrisFarina78/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/baliomega/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/saschamt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jm_denis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anoff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kennyadr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chatyrko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dingyi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mds/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/terryxlife/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aaroni/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kinday/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/prrstn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/eduardostuart/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dhilipsiva/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/GavicoInd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/baires/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rohixx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/blakesimkins/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/leeiio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tjrus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/uberschizo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kylefoundry/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/claudioguglieri/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ripplemdk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/exentrich/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jakemoore/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joaoedumedeiros/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/poormini/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tereshenkov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/keryilmaz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/haydn_woods/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rude/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/llun/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sgaurav_baghel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jamiebrittain/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/badlittleduck/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pifagor/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/agromov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/benefritz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/erwanhesry/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/diesellaws/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremiaha/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/koridhandy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chaensel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andrewcohen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/smaczny/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gonzalorobaina/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nandini_m/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sydlawrence/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cdharrison/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tgerken/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lewisainslie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/charliecwaite/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/robbschiller/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/flexrs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mattdetails/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/raquelwilson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/karsh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mrmartineau/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/opnsrce/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hgharrygo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maximseshuk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/uxalex/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/samihah/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chanpory/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sharvin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/josemarques/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jefffis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/krystalfister/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lokesh_coder/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thedamianhdez/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dpmachado/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/funwatercat/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/timothycd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ivanfilipovbg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/picard102/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marcobarbosa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/krasnoukhov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/g3d/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ademilter/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rickdt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/operatino/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bungiwan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hugomano/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/logorado/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dc_user/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/horaciobella/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/SlaapMe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/teeragit/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iqonicd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ilya_pestov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andrewarrow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ssiskind/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/HenryHoffman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rdsaunders/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adamsxu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/curiousoffice/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/themadray/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michigangraham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kohette/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nickfratter/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/runningskull/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madysondesigns/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brenton_clarke/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jennyshen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bradenhamm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kurtinc/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/amanruzaini/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/coreyhaggard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Karimmove/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aaronalfred/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wtrsld/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jitachi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/therealmarvin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pmeissner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ooomz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chacky14/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jesseddy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thinmatt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shanehudson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/akmur/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/IsaryAmairani/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arthurholcombe1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andychipster/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/boxmodel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ehsandiary/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/LucasPerdidao/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shalt0ni/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/swaplord/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kaelifa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/plbabin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/guillemboti/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arindam_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/renbyrd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thiagovernetti/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jmillspaysbills/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mikemai2awesome/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jervo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mekal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sta1ex/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/robergd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/felipecsl/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andrea211087/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/garand/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dhooyenga/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abovefunction/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pcridesagain/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/randomlies/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/BryanHorsey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/heykenneth/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dahparra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/allthingssmitty/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danvernon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/beweinreich/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/increase/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/falvarad/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alxndrustinov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/souuf/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/orkuncaylar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/AM_Kn2/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gearpixels/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bassamology/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vimarethomas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kosmar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/SULiik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mrjamesnoble/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/silvanmuhlemann/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shaneIxD/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nacho/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yigitpinarbasi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/buzzusborne/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aaronkwhite/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rmlewisuk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/giancarlon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nbirckel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/d_nny_m_cher/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sdidonato/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/atariboy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abotap/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/karalek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/psdesignuk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ludwiczakpawel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nemanjaivanovic/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/baluli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ahmadajmi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vovkasolovev/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/samgrover/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/derienzo777/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jonathansimmons/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nelsonjoyce/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/S0ufi4n3/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xtopherpaul/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oaktreemedia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nateschulte/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/findingjenny/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/namankreative/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/antonyzotov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/we_social/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/leehambley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/solid_color/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abelcabans/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mbilderbach/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kkusaa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jordyvdboom/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlosgavina/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pechkinator/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vc27/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rdbannon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/croakx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/suribbles/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kerihenare/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/catadeleon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gcmorley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/duivvv/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/saschadroste/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victorDubugras/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wintopia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mattbilotti/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/taylorling/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/megdraws/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/meln1ks/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mahmoudmetwally/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Silveredge9/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/derekebradley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/happypeter1983/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/travis_arnold/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/artem_kostenko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adobi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/daykiine/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alek_djuric/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scips/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/miguelmendes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/justinrhee/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alsobrooks/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fronx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mcflydesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/santi_urso/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/allfordesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stayuber/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bertboerland/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marosholly/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adamnac/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cynthiasavard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/muringa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danro/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hiemil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jackiesaik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zacsnider/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iduuck/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/antjanus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aroon_sharma/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dshster/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thehacker/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelbrooksjr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryanmclaughlin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/clubb3rry/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/taybenlor/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xripunov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/myastro/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adityasutomo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/digitalmaverick/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hjartstrorn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/itolmach/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vaughanmoffitt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abdots/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/isnifer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sergeysafonov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scrapdnb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chrismj83/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vitorleal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sokaniwaal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zaki3d/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/illyzoren/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mocabyte/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/osmanince/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/djsherman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davidhemphill/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/waghner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/necodymiconer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/praveen_vijaya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fabbrucci/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cliffseal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/travishines/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kuldarkalvik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Elt_n/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/phillapier/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/okseanjay/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/id835559/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kudretkeskin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anjhero/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/duck4fuck/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scott_riley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/noufalibrahim/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/h1brd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/borges_marcos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/devinhalladay/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ciaranr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stefooo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mikebeecham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tonymillion/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joshuaraichur/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/irae/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/petrangr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dmitriychuta/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/charliegann/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arashmanteghi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ainsleywagon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/svenlen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/faisalabid/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/beshur/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlyson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dutchnadia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/teddyzetterlund/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/samuelkraft/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aoimedia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/toddrew/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/codepoet_ru/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/artvavs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/benoitboucart/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jomarmen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kolmarlopez/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/creartinc/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/homka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gaborenton/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/robinclediere/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maximsorokin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/plasticine/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/j2deme/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/peachananr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kapaluccio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/de_ascanio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rikas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dawidwu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/angelcreative/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rpatey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/popey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rehatkathuria/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/the_purplebunny/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/1markiz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ajaxy_ru/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brenmurrell/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dudestein/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oskarlevinson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victorstuber/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nehfy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vicivadeline/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/leandrovaranda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scottgallant/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victor_haydin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sawrb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryhanhassan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/amayvs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/a_brixen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/karolkrakowiak_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/herkulano/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/geran7/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cggaurav/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chris_witko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lososina/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/polarity/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mattlat/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brandonburke/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/constantx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/teylorfeliz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/craigelimeliah/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rachelreveley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/reabo101/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rahmeen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ky/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rickyyean/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/j04ntoh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/spbroma/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sebashton/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jpenico/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/francis_vega/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oktayelipek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kikillo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fabbianz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/larrygerard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/BroumiYoussef/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/0therplanet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mbilalsiddique1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ionuss/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/grrr_nl/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/liminha/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rawdiggie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryandownie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sethlouey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pixage/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arpitnj/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/switmer777/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/josevnclch/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kanickairaj/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/puzik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tbakdesigns/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/besbujupi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/supjoey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lowie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/linkibol/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/balintorosz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/imcoding/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/agustincruiz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gusoto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thomasschrijer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/superoutman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kalmerrautam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gabrielizalo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gojeanyn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davidbaldie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_vojto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/laurengray/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jydesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mymyboy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nellleo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marciotoledo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ninjad3m0/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/to_soham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hasslunsford/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/muridrahhal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/levisan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/grahamkennery/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lepetitogre/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/antongenkin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nessoila/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/amandabuzard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/safrankov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cocolero/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dss49/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/matt3224/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bluesix/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/quailandquasar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/AlbertoCococi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lepinski/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sementiy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mhudobivnik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thibaut_re/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/olgary/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shojberg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mtolokonnikov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bereto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/naupintos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wegotvices/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xadhix/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/macxim/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rodnylobos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madcampos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madebyvadim/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bartoszdawydzik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/supervova/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/markretzloff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vonachoo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/darylws/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stevedesigner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mylesb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/herbigt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/depaulawagner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/geshan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gizmeedevil1991/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_scottburgess/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lisovsky/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davidsasda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/artd_sign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/YoungCutlass/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mgonto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/itstotallyamy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victorquinn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/osmond/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oksanafrewer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zauerkraut/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamkeithmason/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nitinhayaran/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lmjabreu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mandalareopens/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thinkleft/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ponchomendivil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/juamperro/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brunodesign1206/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/caseycavanagh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/luxe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dotgridline/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/spedwig/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madewulf/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mattsapii/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/helderleal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chrisstumph/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jayphen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nsamoylov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chrisvanderkooi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/justme_timothyg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/otozk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/prinzadi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gu5taf/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cyril_gaillard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/d_kobelyatsky/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/daniloc/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nwdsha/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/romanbulah/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/skkirilov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dvdwinden/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dannol/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thekevinjones/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jwalter14/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/timgthomas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/buddhasource/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/uxpiper/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thatonetommy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/diansigitp/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adrienths/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/klimmka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gkaam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/derekcramer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jennyyo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nerrsoft/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xalionmalik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/edhenderson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/keyuri85/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/roxanejammet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kimcool/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/edkf/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/matkins/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alessandroribe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jacksonlatka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lebronjennan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kostaspt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/karlkanall/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/moynihan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danpliego/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/saulihirvi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wesleytrankin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fjaguero/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bowbrick/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mashaaaaal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yassiryahya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dparrelli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fotomagin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aka_james/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/denisepires/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iqbalperkasa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/martinansty/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jarsen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/r_oy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/justinrob/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gabrielrosser/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/malgordon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlfairclough/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelabehsera/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pierrestoffe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/enjoythetau/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/loganjlambert/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rpeezy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/coreyginnivan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michalhron/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/msveet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lingeswaran/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kolsvein/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/peter576/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/reideiredale/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joeymurdah/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/raphaelnikson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mvdheuvel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maxlinderman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jimmuirhead/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/begreative/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/frankiefreesbie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/robturlinckx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Talbi_ConSept/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/longlivemyword/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vanchesz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maiklam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hermanobrother/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rez___a/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gregsqueeb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/greenbes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_ragzor/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anthonysukow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fluidbrush/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dactrtr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jehnglynn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bergmartin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hugocornejo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_kkga/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dzantievm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sawalazar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sovesove/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jonsgotwood/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/byryan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vytautas_a/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mizhgan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cicerobr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nilshelmersson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/d33pthought/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davecraige/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nckjrvs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alexandermayes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jcubic/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/craigrcoles/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bagawarman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rob_thomas10/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cofla/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/maikelk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rtgibbons/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/russell_baylis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mhesslow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/codysanfilippo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/webtanya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madebybrenton/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dcalonaci/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/perfectflow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jjsiii/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/saarabpreet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kumarrajan12123/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamsteffen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/themikenagle/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ceekaytweet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/larrybolt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/conspirator/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dallasbpeters/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/n3dmax/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/terpimost/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kirillz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/byrnecore/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/j_drake_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/calebjoyce/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/russoedu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hoangloi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tobysaxon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gofrasdesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dimaposnyy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tjisousa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/okandungel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/billyroshan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oskamaya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/motionthinks/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/knilob/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ashocka18/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marrimo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bartjo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/omnizya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ernestsemerda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andreas_pr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/edgarchris99/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thomasgeisen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gseguin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joannefournier/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/demersdesigns/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adammarsbar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nasirwd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/n_tassone/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/javorszky/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/themrdave/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yecidsm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nicollerich/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/canapud/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nicoleglynn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/judzhin_miles/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/designervzm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kianoshp/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/evandrix/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alterchuca/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dhrubo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ma_tiax/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ssbb_me/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dorphern/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mauriolg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bruno_mart/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mactopus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/the_winslet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joemdesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/Shriiiiimp/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jacobbennett/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nfedoroff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamglimy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/allagringaus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aiiaiiaii/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/olaolusoga/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/buryaknick/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wim1k/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nicklacke/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/a1chapone/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/steynviljoen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/strikewan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryankirkman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andrewabogado/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/doooon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jagan123/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ariffsetiawan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/elenadissi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mwarkentin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thierrymeier_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/r_garcia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dmackerman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/borantula/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/konus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/spacewood_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryuchi311/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/evanshajed/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tristanlegros/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shoaib253/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aislinnkelly/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/okcoker/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/timpetricola/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sunshinedgirl/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chadami/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aleclarsoniv/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nomidesigns/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/petebernardo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scottiedude/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/millinet/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/imsoper/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/imammuht/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/benjamin_knight/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nepdud/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joki4/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lanceguyatt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bboy1895/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/amywebbb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rweve/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/haruintesettden/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ricburton/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nelshd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/batsirai/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/primozcigler/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jffgrdnr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/8d3k/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/geneseleznev/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/al_li/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/souperphly/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mslarkina/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/2fockus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cdavis565/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xiel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/turkutuuli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/uxward/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lebinoclard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gauravjassal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davidmerrique/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mdsisto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andrewofficer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kojourin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dnirmal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kevka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mr_shiznit/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aluisio_azevedo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cloudstudio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danvierich/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alexivanichkin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fran_mchamy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/perretmagali/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/betraydan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cadikkara/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/matbeedotcom/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremyworboys/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bpartridge/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelkoper/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/silv3rgvn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alevizio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/johnsmithagency/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lawlbwoy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vitor376/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/desastrozo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thimo_cz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jasonmarkjones/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lhausermann/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xravil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/guischmitt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vigobronx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/panghal0/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/miguelkooreman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/surgeonist/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/christianoliff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/caspergrl/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamkarna/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ipavelek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pierre_nel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/y2graphic/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sterlingrules/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/elbuscainfo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bennyjien/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stushona/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/estebanuribe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/embrcecreations/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danillos/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/elliotlewis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/charlesrpratt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vladyn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/emmeffess/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlosblanco_eu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/leonfedotov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rangafangs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chris_frees/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tgormtx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bryan_topham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jpscribbles/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mighty55/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carbontwelve/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/isaacfifth/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/iamjdeleon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/snowwrite/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/barputro/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/drewbyreese/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sachacorazzi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bistrianiosip/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/magoo04/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pehamondello/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yayteejay/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/a_harris88/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/algunsanabria/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zforrester/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ovall/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlosjgsousa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/geobikas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ah_lice/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/looneydoodle/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nerdgr8/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ddggccaa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zackeeler/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/normanbox/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/el_fuertisimo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ismail_biltagi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/juangomezw/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jnmnrd/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/patrickcoombe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ryanjohnson_me/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/markolschesky/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeffgolenski/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kvasnic/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lindseyzilla/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gauchomatt/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/afusinatto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kevinoh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/okansurreel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adamawesomeface/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/emileboudeling/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arishi_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/juanmamartinez/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wikiziner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danthms/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mkginfo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/terrorpixel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/curiousonaut/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/prheemo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelcolenso/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/foczzi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/martip07/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thaodang17/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/johncafazza/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/robinlayfield/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/franciscoamk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/abdulhyeuk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marklamb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/edobene/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andresenfredrik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mikaeljorhult/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chrisslowik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vinciarts/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/meelford/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/elliotnolten/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yehudab/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vijaykarthik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bfrohs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/josep_martins/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/attacks/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sur4dye/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tumski/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/instalox/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mangosango/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/paulfarino/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kazaky999/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kiwiupover/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nvkznemo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tom_even/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ratbus/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/woodsman001/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joshmedeski/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thewillbeard/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/psaikali/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joe_black/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aleinadsays/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marcusgorillius/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hota_v/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jghyllebert/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shinze/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/janpalounek/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremiespoken/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/her_ruu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dansowter/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/felipeapiress/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/magugzbrand2d/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/posterjob/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nathalie_fs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bobbytwoshoes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dreizle/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremymouton/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/elisabethkjaer/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/notbadart/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mohanrohith/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jlsolerdeltoro/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/itskawsar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/slowspock/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/zvchkelly/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wiljanslofstra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/craighenneberry/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/trubeatto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/juaumlol/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/samscouto/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/BenouarradeM/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gipsy_raf/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/netonet_il/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/arkokoley/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/itsajimithing/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/smalonso/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/victordeanda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_dwite_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/richardgarretts/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gregrwilkinson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anatolinicolae/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lu4sh1i/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stefanotirloni/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ostirbu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/darcystonge/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/naitanamoreno/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/michaelcomiskey/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/adhiardana/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marcomano_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/davidcazalis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/falconerie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gregkilian/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bcrad/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bolzanmarco/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/low_res/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vlajki/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/petar_prog/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jonkspr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/akmalfikri/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mfacchinello/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/atanism/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/harry_sistalam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/murrayswift/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bobwassermann/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gavr1l0/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/madshensel/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mr_subtle/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/deviljho_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/salimianoff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joetruesdell/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/twittypork/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/airskylar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dnezkumar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dgajjar/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cherif_b/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/salvafc/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/louis_currie/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/deeenright/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cybind/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/eyronn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vickyshits/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sweetdelisa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/cboller1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andresdjasso/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/melvindidit/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andysolomon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thaisselenator_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lvovenok/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/giuliusa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/belyaev_rs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/overcloacked/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kamal_chaneman/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/incubo82/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hellofeverrrr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mhaligowski/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sunlandictwin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bu7921/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/andytlaw/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremery/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/finchjke/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/manigm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/umurgdk/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/scottfeltham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ganserene/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mutu_krish/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jodytaggart/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ntfblog/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tanveerrao/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hfalucas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alxleroydeval/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kucingbelang4/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bargaorobalo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/colgruv/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stalewine/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kylefrost/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/baumannzone/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/angelcolberg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sachingawas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jjshaw14/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ramanathan_pdy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/johndezember/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nilshoenson/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brandonmorreale/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nutzumi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/brandonflatsoda/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sergeyalmone/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/klefue/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kirangopal/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/baumann_alex/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/matthewkay_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jay_wilburn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shesgared/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/apriendeau/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/johnriordan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wake_gs/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aleksitappura/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/emsgulam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xilantra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/imomenui/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sircalebgrove/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/newbrushes/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hsinyo23/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/m4rio/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/katiemdaly/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/s4f1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ecommerceil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marlinjayakody/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/swooshycueb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sangdth/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/coderdiaz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bluefx_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vivekprvr/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sasha_shestakov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/eugeneeweb/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dgclegg/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/n1ght_coder/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dixchen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/blakehawksworth/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/trueblood_33/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hai_ninh_nguyen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marclgonzales/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/yesmeck/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stephcoue/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/doronmalki/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ruehldesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/anasnakawa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kijanmaharjan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/wearesavas/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stefvdham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tweetubhai/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alecarpentier/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/fiterik/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/antonyryndya/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/d00maz/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/theonlyzeke/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/missaaamy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/carlosm/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/manekenthe/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/reetajayendra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jeremyshimko/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/justinrgraham/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/stefanozoffoli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/overra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mrebay007/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/shvelo96/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/pyronite/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/thedjpetersen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/rtyukmaev/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_williamguerra/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/albertaugustin/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vikashpathak18/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kevinjohndayy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vj_demien/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/colirpixoil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/goddardlewis/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/laasli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jqiuss/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/heycamtaylor/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nastya_mane/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mastermindesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ccinojasso1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/nyancecom/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sandywoodruff/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/bighanddesign/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sbtransparent/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aviddayentonbay/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/richwild/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kaysix_dizzy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/tur8le/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/seyedhossein1/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/privetwagner/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/emmandenn/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dev_essentials/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jmfsocial/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_yardenoon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mateaodviteza/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/weavermedia/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mufaddal_mw/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hafeeskhan/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ashernatali/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sulaqo/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/eddiechen/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/josecarlospsh/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vm_f/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/enricocicconi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/danmartin70/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/gmourier/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/donjain/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mrxloka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/_pedropinho/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/eitarafa/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/oscarowusu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ralph_lam/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/panchajanyag/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/woodydotmx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/jerrybai1907/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/marshallchen_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/xamorep/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aio___/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/chaabane_wail/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/txcx/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/akashsharma39/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/falling_soul/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sainraja/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mugukamil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/johannesneu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/markwienands/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/karthipanraj/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/balakayuriy/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/alan_zhang_/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/layerssss/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/kaspernordkvist/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/mirfanqureshi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/hanna_smi/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/VMilescu/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/aeon56/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/m_kalibry/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/sreejithexp/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dicesales/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/dhoot_amit/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/smenov/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/lonesomelemon/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vladimirdevic/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/joelcipriano/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/haligaliharun/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/buleswapnil/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/serefka/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/ifarafonow/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/vikasvinfotech/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/urrutimeoli/128.jpg",
"https://s3.amazonaws.com/uifaces/faces/twitter/areandacom/128.jpg"
];
},{}],114:[function(require,module,exports){
module["exports"] = [
"com",
"biz",
"info",
"name",
"net",
"org"
];
},{}],115:[function(require,module,exports){
module["exports"] = [
"example.org",
"example.com",
"example.net"
];
},{}],116:[function(require,module,exports){
module["exports"] = [
"gmail.com",
"yahoo.com",
"hotmail.com"
];
},{}],117:[function(require,module,exports){
var internet = {};
module['exports'] = internet;
internet.free_email = require("./free_email");
internet.example_email = require("./example_email");
internet.domain_suffix = require("./domain_suffix");
internet.avatar_uri = require("./avatar_uri");
},{"./avatar_uri":113,"./domain_suffix":114,"./example_email":115,"./free_email":116}],118:[function(require,module,exports){
var lorem = {};
module['exports'] = lorem;
lorem.words = require("./words");
lorem.supplemental = require("./supplemental");
},{"./supplemental":119,"./words":120}],119:[function(require,module,exports){
module["exports"] = [
"abbas",
"abduco",
"abeo",
"abscido",
"absconditus",
"absens",
"absorbeo",
"absque",
"abstergo",
"absum",
"abundans",
"abutor",
"accedo",
"accendo",
"acceptus",
"accipio",
"accommodo",
"accusator",
"acer",
"acerbitas",
"acervus",
"acidus",
"acies",
"acquiro",
"acsi",
"adamo",
"adaugeo",
"addo",
"adduco",
"ademptio",
"adeo",
"adeptio",
"adfectus",
"adfero",
"adficio",
"adflicto",
"adhaero",
"adhuc",
"adicio",
"adimpleo",
"adinventitias",
"adipiscor",
"adiuvo",
"administratio",
"admiratio",
"admitto",
"admoneo",
"admoveo",
"adnuo",
"adopto",
"adsidue",
"adstringo",
"adsuesco",
"adsum",
"adulatio",
"adulescens",
"adultus",
"aduro",
"advenio",
"adversus",
"advoco",
"aedificium",
"aeger",
"aegre",
"aegrotatio",
"aegrus",
"aeneus",
"aequitas",
"aequus",
"aer",
"aestas",
"aestivus",
"aestus",
"aetas",
"aeternus",
"ager",
"aggero",
"aggredior",
"agnitio",
"agnosco",
"ago",
"ait",
"aiunt",
"alienus",
"alii",
"alioqui",
"aliqua",
"alius",
"allatus",
"alo",
"alter",
"altus",
"alveus",
"amaritudo",
"ambitus",
"ambulo",
"amicitia",
"amiculum",
"amissio",
"amita",
"amitto",
"amo",
"amor",
"amoveo",
"amplexus",
"amplitudo",
"amplus",
"ancilla",
"angelus",
"angulus",
"angustus",
"animadverto",
"animi",
"animus",
"annus",
"anser",
"ante",
"antea",
"antepono",
"antiquus",
"aperio",
"aperte",
"apostolus",
"apparatus",
"appello",
"appono",
"appositus",
"approbo",
"apto",
"aptus",
"apud",
"aqua",
"ara",
"aranea",
"arbitro",
"arbor",
"arbustum",
"arca",
"arceo",
"arcesso",
"arcus",
"argentum",
"argumentum",
"arguo",
"arma",
"armarium",
"armo",
"aro",
"ars",
"articulus",
"artificiose",
"arto",
"arx",
"ascisco",
"ascit",
"asper",
"aspicio",
"asporto",
"assentator",
"astrum",
"atavus",
"ater",
"atqui",
"atrocitas",
"atrox",
"attero",
"attollo",
"attonbitus",
"auctor",
"auctus",
"audacia",
"audax",
"audentia",
"audeo",
"audio",
"auditor",
"aufero",
"aureus",
"auris",
"aurum",
"aut",
"autem",
"autus",
"auxilium",
"avaritia",
"avarus",
"aveho",
"averto",
"avoco",
"baiulus",
"balbus",
"barba",
"bardus",
"basium",
"beatus",
"bellicus",
"bellum",
"bene",
"beneficium",
"benevolentia",
"benigne",
"bestia",
"bibo",
"bis",
"blandior",
"bonus",
"bos",
"brevis",
"cado",
"caecus",
"caelestis",
"caelum",
"calamitas",
"calcar",
"calco",
"calculus",
"callide",
"campana",
"candidus",
"canis",
"canonicus",
"canto",
"capillus",
"capio",
"capitulus",
"capto",
"caput",
"carbo",
"carcer",
"careo",
"caries",
"cariosus",
"caritas",
"carmen",
"carpo",
"carus",
"casso",
"caste",
"casus",
"catena",
"caterva",
"cattus",
"cauda",
"causa",
"caute",
"caveo",
"cavus",
"cedo",
"celebrer",
"celer",
"celo",
"cena",
"cenaculum",
"ceno",
"censura",
"centum",
"cerno",
"cernuus",
"certe",
"certo",
"certus",
"cervus",
"cetera",
"charisma",
"chirographum",
"cibo",
"cibus",
"cicuta",
"cilicium",
"cimentarius",
"ciminatio",
"cinis",
"circumvenio",
"cito",
"civis",
"civitas",
"clam",
"clamo",
"claro",
"clarus",
"claudeo",
"claustrum",
"clementia",
"clibanus",
"coadunatio",
"coaegresco",
"coepi",
"coerceo",
"cogito",
"cognatus",
"cognomen",
"cogo",
"cohaero",
"cohibeo",
"cohors",
"colligo",
"colloco",
"collum",
"colo",
"color",
"coma",
"combibo",
"comburo",
"comedo",
"comes",
"cometes",
"comis",
"comitatus",
"commemoro",
"comminor",
"commodo",
"communis",
"comparo",
"compello",
"complectus",
"compono",
"comprehendo",
"comptus",
"conatus",
"concedo",
"concido",
"conculco",
"condico",
"conduco",
"confero",
"confido",
"conforto",
"confugo",
"congregatio",
"conicio",
"coniecto",
"conitor",
"coniuratio",
"conor",
"conqueror",
"conscendo",
"conservo",
"considero",
"conspergo",
"constans",
"consuasor",
"contabesco",
"contego",
"contigo",
"contra",
"conturbo",
"conventus",
"convoco",
"copia",
"copiose",
"cornu",
"corona",
"corpus",
"correptius",
"corrigo",
"corroboro",
"corrumpo",
"coruscus",
"cotidie",
"crapula",
"cras",
"crastinus",
"creator",
"creber",
"crebro",
"credo",
"creo",
"creptio",
"crepusculum",
"cresco",
"creta",
"cribro",
"crinis",
"cruciamentum",
"crudelis",
"cruentus",
"crur",
"crustulum",
"crux",
"cubicularis",
"cubitum",
"cubo",
"cui",
"cuius",
"culpa",
"culpo",
"cultellus",
"cultura",
"cum",
"cunabula",
"cunae",
"cunctatio",
"cupiditas",
"cupio",
"cuppedia",
"cupressus",
"cur",
"cura",
"curatio",
"curia",
"curiositas",
"curis",
"curo",
"curriculum",
"currus",
"cursim",
"curso",
"cursus",
"curto",
"curtus",
"curvo",
"curvus",
"custodia",
"damnatio",
"damno",
"dapifer",
"debeo",
"debilito",
"decens",
"decerno",
"decet",
"decimus",
"decipio",
"decor",
"decretum",
"decumbo",
"dedecor",
"dedico",
"deduco",
"defaeco",
"defendo",
"defero",
"defessus",
"defetiscor",
"deficio",
"defigo",
"defleo",
"defluo",
"defungo",
"degenero",
"degero",
"degusto",
"deinde",
"delectatio",
"delego",
"deleo",
"delibero",
"delicate",
"delinquo",
"deludo",
"demens",
"demergo",
"demitto",
"demo",
"demonstro",
"demoror",
"demulceo",
"demum",
"denego",
"denique",
"dens",
"denuncio",
"denuo",
"deorsum",
"depereo",
"depono",
"depopulo",
"deporto",
"depraedor",
"deprecator",
"deprimo",
"depromo",
"depulso",
"deputo",
"derelinquo",
"derideo",
"deripio",
"desidero",
"desino",
"desipio",
"desolo",
"desparatus",
"despecto",
"despirmatio",
"infit",
"inflammatio",
"paens",
"patior",
"patria",
"patrocinor",
"patruus",
"pauci",
"paulatim",
"pauper",
"pax",
"peccatus",
"pecco",
"pecto",
"pectus",
"pecunia",
"pecus",
"peior",
"pel",
"ocer",
"socius",
"sodalitas",
"sol",
"soleo",
"solio",
"solitudo",
"solium",
"sollers",
"sollicito",
"solum",
"solus",
"solutio",
"solvo",
"somniculosus",
"somnus",
"sonitus",
"sono",
"sophismata",
"sopor",
"sordeo",
"sortitus",
"spargo",
"speciosus",
"spectaculum",
"speculum",
"sperno",
"spero",
"spes",
"spiculum",
"spiritus",
"spoliatio",
"sponte",
"stabilis",
"statim",
"statua",
"stella",
"stillicidium",
"stipes",
"stips",
"sto",
"strenuus",
"strues",
"studio",
"stultus",
"suadeo",
"suasoria",
"sub",
"subito",
"subiungo",
"sublime",
"subnecto",
"subseco",
"substantia",
"subvenio",
"succedo",
"succurro",
"sufficio",
"suffoco",
"suffragium",
"suggero",
"sui",
"sulum",
"sum",
"summa",
"summisse",
"summopere",
"sumo",
"sumptus",
"supellex",
"super",
"suppellex",
"supplanto",
"suppono",
"supra",
"surculus",
"surgo",
"sursum",
"suscipio",
"suspendo",
"sustineo",
"suus",
"synagoga",
"tabella",
"tabernus",
"tabesco",
"tabgo",
"tabula",
"taceo",
"tactus",
"taedium",
"talio",
"talis",
"talus",
"tam",
"tamdiu",
"tamen",
"tametsi",
"tamisium",
"tamquam",
"tandem",
"tantillus",
"tantum",
"tardus",
"tego",
"temeritas",
"temperantia",
"templum",
"temptatio",
"tempus",
"tenax",
"tendo",
"teneo",
"tener",
"tenuis",
"tenus",
"tepesco",
"tepidus",
"ter",
"terebro",
"teres",
"terga",
"tergeo",
"tergiversatio",
"tergo",
"tergum",
"termes",
"terminatio",
"tero",
"terra",
"terreo",
"territo",
"terror",
"tersus",
"tertius",
"testimonium",
"texo",
"textilis",
"textor",
"textus",
"thalassinus",
"theatrum",
"theca",
"thema",
"theologus",
"thermae",
"thesaurus",
"thesis",
"thorax",
"thymbra",
"thymum",
"tibi",
"timidus",
"timor",
"titulus",
"tolero",
"tollo",
"tondeo",
"tonsor",
"torqueo",
"torrens",
"tot",
"totidem",
"toties",
"totus",
"tracto",
"trado",
"traho",
"trans",
"tredecim",
"tremo",
"trepide",
"tres",
"tribuo",
"tricesimus",
"triduana",
"triginta",
"tripudio",
"tristis",
"triumphus",
"trucido",
"truculenter",
"tubineus",
"tui",
"tum",
"tumultus",
"tunc",
"turba",
"turbo",
"turpe",
"turpis",
"tutamen",
"tutis",
"tyrannus",
"uberrime",
"ubi",
"ulciscor",
"ullus",
"ulterius",
"ultio",
"ultra",
"umbra",
"umerus",
"umquam",
"una",
"unde",
"undique",
"universe",
"unus",
"urbanus",
"urbs",
"uredo",
"usitas",
"usque",
"ustilo",
"ustulo",
"usus",
"uter",
"uterque",
"utilis",
"utique",
"utor",
"utpote",
"utrimque",
"utroque",
"utrum",
"uxor",
"vaco",
"vacuus",
"vado",
"vae",
"valde",
"valens",
"valeo",
"valetudo",
"validus",
"vallum",
"vapulus",
"varietas",
"varius",
"vehemens",
"vel",
"velociter",
"velum",
"velut",
"venia",
"venio",
"ventito",
"ventosus",
"ventus",
"venustas",
"ver",
"verbera",
"verbum",
"vere",
"verecundia",
"vereor",
"vergo",
"veritas",
"vero",
"versus",
"verto",
"verumtamen",
"verus",
"vesco",
"vesica",
"vesper",
"vespillo",
"vester",
"vestigium",
"vestrum",
"vetus",
"via",
"vicinus",
"vicissitudo",
"victoria",
"victus",
"videlicet",
"video",
"viduata",
"viduo",
"vigilo",
"vigor",
"vilicus",
"vilis",
"vilitas",
"villa",
"vinco",
"vinculum",
"vindico",
"vinitor",
"vinum",
"vir",
"virga",
"virgo",
"viridis",
"viriliter",
"virtus",
"vis",
"viscus",
"vita",
"vitiosus",
"vitium",
"vito",
"vivo",
"vix",
"vobis",
"vociferor",
"voco",
"volaticus",
"volo",
"volubilis",
"voluntarius",
"volup",
"volutabrum",
"volva",
"vomer",
"vomica",
"vomito",
"vorago",
"vorax",
"voro",
"vos",
"votum",
"voveo",
"vox",
"vulariter",
"vulgaris",
"vulgivagus",
"vulgo",
"vulgus",
"vulnero",
"vulnus",
"vulpes",
"vulticulus",
"vultuosus",
"xiphias"
];
},{}],120:[function(require,module,exports){
module["exports"] = [
"alias",
"consequatur",
"aut",
"perferendis",
"sit",
"voluptatem",
"accusantium",
"doloremque",
"aperiam",
"eaque",
"ipsa",
"quae",
"ab",
"illo",
"inventore",
"veritatis",
"et",
"quasi",
"architecto",
"beatae",
"vitae",
"dicta",
"sunt",
"explicabo",
"aspernatur",
"aut",
"odit",
"aut",
"fugit",
"sed",
"quia",
"consequuntur",
"magni",
"dolores",
"eos",
"qui",
"ratione",
"voluptatem",
"sequi",
"nesciunt",
"neque",
"dolorem",
"ipsum",
"quia",
"dolor",
"sit",
"amet",
"consectetur",
"adipisci",
"velit",
"sed",
"quia",
"non",
"numquam",
"eius",
"modi",
"tempora",
"incidunt",
"ut",
"labore",
"et",
"dolore",
"magnam",
"aliquam",
"quaerat",
"voluptatem",
"ut",
"enim",
"ad",
"minima",
"veniam",
"quis",
"nostrum",
"exercitationem",
"ullam",
"corporis",
"nemo",
"enim",
"ipsam",
"voluptatem",
"quia",
"voluptas",
"sit",
"suscipit",
"laboriosam",
"nisi",
"ut",
"aliquid",
"ex",
"ea",
"commodi",
"consequatur",
"quis",
"autem",
"vel",
"eum",
"iure",
"reprehenderit",
"qui",
"in",
"ea",
"voluptate",
"velit",
"esse",
"quam",
"nihil",
"molestiae",
"et",
"iusto",
"odio",
"dignissimos",
"ducimus",
"qui",
"blanditiis",
"praesentium",
"laudantium",
"totam",
"rem",
"voluptatum",
"deleniti",
"atque",
"corrupti",
"quos",
"dolores",
"et",
"quas",
"molestias",
"excepturi",
"sint",
"occaecati",
"cupiditate",
"non",
"provident",
"sed",
"ut",
"perspiciatis",
"unde",
"omnis",
"iste",
"natus",
"error",
"similique",
"sunt",
"in",
"culpa",
"qui",
"officia",
"deserunt",
"mollitia",
"animi",
"id",
"est",
"laborum",
"et",
"dolorum",
"fuga",
"et",
"harum",
"quidem",
"rerum",
"facilis",
"est",
"et",
"expedita",
"distinctio",
"nam",
"libero",
"tempore",
"cum",
"soluta",
"nobis",
"est",
"eligendi",
"optio",
"cumque",
"nihil",
"impedit",
"quo",
"porro",
"quisquam",
"est",
"qui",
"minus",
"id",
"quod",
"maxime",
"placeat",
"facere",
"possimus",
"omnis",
"voluptas",
"assumenda",
"est",
"omnis",
"dolor",
"repellendus",
"temporibus",
"autem",
"quibusdam",
"et",
"aut",
"consequatur",
"vel",
"illum",
"qui",
"dolorem",
"eum",
"fugiat",
"quo",
"voluptas",
"nulla",
"pariatur",
"at",
"vero",
"eos",
"et",
"accusamus",
"officiis",
"debitis",
"aut",
"rerum",
"necessitatibus",
"saepe",
"eveniet",
"ut",
"et",
"voluptates",
"repudiandae",
"sint",
"et",
"molestiae",
"non",
"recusandae",
"itaque",
"earum",
"rerum",
"hic",
"tenetur",
"a",
"sapiente",
"delectus",
"ut",
"aut",
"reiciendis",
"voluptatibus",
"maiores",
"doloribus",
"asperiores",
"repellat"
];
},{}],121:[function(require,module,exports){
module["exports"] = [
"Aaliyah",
"Aaron",
"Abagail",
"Abbey",
"Abbie",
"Abbigail",
"Abby",
"Abdiel",
"Abdul",
"Abdullah",
"Abe",
"Abel",
"Abelardo",
"Abigail",
"Abigale",
"Abigayle",
"Abner",
"Abraham",
"Ada",
"Adah",
"Adalberto",
"Adaline",
"Adam",
"Adan",
"Addie",
"Addison",
"Adela",
"Adelbert",
"Adele",
"Adelia",
"Adeline",
"Adell",
"Adella",
"Adelle",
"Aditya",
"Adolf",
"Adolfo",
"Adolph",
"Adolphus",
"Adonis",
"Adrain",
"Adrian",
"Adriana",
"Adrianna",
"Adriel",
"Adrien",
"Adrienne",
"Afton",
"Aglae",
"Agnes",
"Agustin",
"Agustina",
"Ahmad",
"Ahmed",
"Aida",
"Aidan",
"Aiden",
"Aileen",
"Aimee",
"Aisha",
"Aiyana",
"Akeem",
"Al",
"Alaina",
"Alan",
"Alana",
"Alanis",
"Alanna",
"Alayna",
"Alba",
"Albert",
"Alberta",
"Albertha",
"Alberto",
"Albin",
"Albina",
"Alda",
"Alden",
"Alec",
"Aleen",
"Alejandra",
"Alejandrin",
"Alek",
"Alena",
"Alene",
"Alessandra",
"Alessandro",
"Alessia",
"Aletha",
"Alex",
"Alexa",
"Alexander",
"Alexandra",
"Alexandre",
"Alexandrea",
"Alexandria",
"Alexandrine",
"Alexandro",
"Alexane",
"Alexanne",
"Alexie",
"Alexis",
"Alexys",
"Alexzander",
"Alf",
"Alfonso",
"Alfonzo",
"Alford",
"Alfred",
"Alfreda",
"Alfredo",
"Ali",
"Alia",
"Alice",
"Alicia",
"Alisa",
"Alisha",
"Alison",
"Alivia",
"Aliya",
"Aliyah",
"Aliza",
"Alize",
"Allan",
"Allen",
"Allene",
"Allie",
"Allison",
"Ally",
"Alphonso",
"Alta",
"Althea",
"Alva",
"Alvah",
"Alvena",
"Alvera",
"Alverta",
"Alvina",
"Alvis",
"Alyce",
"Alycia",
"Alysa",
"Alysha",
"Alyson",
"Alysson",
"Amalia",
"Amanda",
"Amani",
"Amara",
"Amari",
"Amaya",
"Amber",
"Ambrose",
"Amelia",
"Amelie",
"Amely",
"America",
"Americo",
"Amie",
"Amina",
"Amir",
"Amira",
"Amiya",
"Amos",
"Amparo",
"Amy",
"Amya",
"Ana",
"Anabel",
"Anabelle",
"Anahi",
"Anais",
"Anastacio",
"Anastasia",
"Anderson",
"Andre",
"Andreane",
"Andreanne",
"Andres",
"Andrew",
"Andy",
"Angel",
"Angela",
"Angelica",
"Angelina",
"Angeline",
"Angelita",
"Angelo",
"Angie",
"Angus",
"Anibal",
"Anika",
"Anissa",
"Anita",
"Aniya",
"Aniyah",
"Anjali",
"Anna",
"Annabel",
"Annabell",
"Annabelle",
"Annalise",
"Annamae",
"Annamarie",
"Anne",
"Annetta",
"Annette",
"Annie",
"Ansel",
"Ansley",
"Anthony",
"Antoinette",
"Antone",
"Antonetta",
"Antonette",
"Antonia",
"Antonietta",
"Antonina",
"Antonio",
"Antwan",
"Antwon",
"Anya",
"April",
"Ara",
"Araceli",
"Aracely",
"Arch",
"Archibald",
"Ardella",
"Arden",
"Ardith",
"Arely",
"Ari",
"Ariane",
"Arianna",
"Aric",
"Ariel",
"Arielle",
"Arjun",
"Arlene",
"Arlie",
"Arlo",
"Armand",
"Armando",
"Armani",
"Arnaldo",
"Arne",
"Arno",
"Arnold",
"Arnoldo",
"Arnulfo",
"Aron",
"Art",
"Arthur",
"Arturo",
"Arvel",
"Arvid",
"Arvilla",
"Aryanna",
"Asa",
"Asha",
"Ashlee",
"Ashleigh",
"Ashley",
"Ashly",
"Ashlynn",
"Ashton",
"Ashtyn",
"Asia",
"Assunta",
"Astrid",
"Athena",
"Aubree",
"Aubrey",
"Audie",
"Audra",
"Audreanne",
"Audrey",
"August",
"Augusta",
"Augustine",
"Augustus",
"Aurelia",
"Aurelie",
"Aurelio",
"Aurore",
"Austen",
"Austin",
"Austyn",
"Autumn",
"Ava",
"Avery",
"Avis",
"Axel",
"Ayana",
"Ayden",
"Ayla",
"Aylin",
"Baby",
"Bailee",
"Bailey",
"Barbara",
"Barney",
"Baron",
"Barrett",
"Barry",
"Bart",
"Bartholome",
"Barton",
"Baylee",
"Beatrice",
"Beau",
"Beaulah",
"Bell",
"Bella",
"Belle",
"Ben",
"Benedict",
"Benjamin",
"Bennett",
"Bennie",
"Benny",
"Benton",
"Berenice",
"Bernadette",
"Bernadine",
"Bernard",
"Bernardo",
"Berneice",
"Bernhard",
"Bernice",
"Bernie",
"Berniece",
"Bernita",
"Berry",
"Bert",
"Berta",
"Bertha",
"Bertram",
"Bertrand",
"Beryl",
"Bessie",
"Beth",
"Bethany",
"Bethel",
"Betsy",
"Bette",
"Bettie",
"Betty",
"Bettye",
"Beulah",
"Beverly",
"Bianka",
"Bill",
"Billie",
"Billy",
"Birdie",
"Blair",
"Blaise",
"Blake",
"Blanca",
"Blanche",
"Blaze",
"Bo",
"Bobbie",
"Bobby",
"Bonita",
"Bonnie",
"Boris",
"Boyd",
"Brad",
"Braden",
"Bradford",
"Bradley",
"Bradly",
"Brady",
"Braeden",
"Brain",
"Brandi",
"Brando",
"Brandon",
"Brandt",
"Brandy",
"Brandyn",
"Brannon",
"Branson",
"Brant",
"Braulio",
"Braxton",
"Brayan",
"Breana",
"Breanna",
"Breanne",
"Brenda",
"Brendan",
"Brenden",
"Brendon",
"Brenna",
"Brennan",
"Brennon",
"Brent",
"Bret",
"Brett",
"Bria",
"Brian",
"Briana",
"Brianne",
"Brice",
"Bridget",
"Bridgette",
"Bridie",
"Brielle",
"Brigitte",
"Brionna",
"Brisa",
"Britney",
"Brittany",
"Brock",
"Broderick",
"Brody",
"Brook",
"Brooke",
"Brooklyn",
"Brooks",
"Brown",
"Bruce",
"Bryana",
"Bryce",
"Brycen",
"Bryon",
"Buck",
"Bud",
"Buddy",
"Buford",
"Bulah",
"Burdette",
"Burley",
"Burnice",
"Buster",
"Cade",
"Caden",
"Caesar",
"Caitlyn",
"Cale",
"Caleb",
"Caleigh",
"Cali",
"Calista",
"Callie",
"Camden",
"Cameron",
"Camila",
"Camilla",
"Camille",
"Camren",
"Camron",
"Camryn",
"Camylle",
"Candace",
"Candelario",
"Candice",
"Candida",
"Candido",
"Cara",
"Carey",
"Carissa",
"Carlee",
"Carleton",
"Carley",
"Carli",
"Carlie",
"Carlo",
"Carlos",
"Carlotta",
"Carmel",
"Carmela",
"Carmella",
"Carmelo",
"Carmen",
"Carmine",
"Carol",
"Carolanne",
"Carole",
"Carolina",
"Caroline",
"Carolyn",
"Carolyne",
"Carrie",
"Carroll",
"Carson",
"Carter",
"Cary",
"Casandra",
"Casey",
"Casimer",
"Casimir",
"Casper",
"Cassandra",
"Cassandre",
"Cassidy",
"Cassie",
"Catalina",
"Caterina",
"Catharine",
"Catherine",
"Cathrine",
"Cathryn",
"Cathy",
"Cayla",
"Ceasar",
"Cecelia",
"Cecil",
"Cecile",
"Cecilia",
"Cedrick",
"Celestine",
"Celestino",
"Celia",
"Celine",
"Cesar",
"Chad",
"Chadd",
"Chadrick",
"Chaim",
"Chance",
"Chandler",
"Chanel",
"Chanelle",
"Charity",
"Charlene",
"Charles",
"Charley",
"Charlie",
"Charlotte",
"Chase",
"Chasity",
"Chauncey",
"Chaya",
"Chaz",
"Chelsea",
"Chelsey",
"Chelsie",
"Chesley",
"Chester",
"Chet",
"Cheyanne",
"Cheyenne",
"Chloe",
"Chris",
"Christ",
"Christa",
"Christelle",
"Christian",
"Christiana",
"Christina",
"Christine",
"Christop",
"Christophe",
"Christopher",
"Christy",
"Chyna",
"Ciara",
"Cicero",
"Cielo",
"Cierra",
"Cindy",
"Citlalli",
"Clair",
"Claire",
"Clara",
"Clarabelle",
"Clare",
"Clarissa",
"Clark",
"Claud",
"Claude",
"Claudia",
"Claudie",
"Claudine",
"Clay",
"Clemens",
"Clement",
"Clementina",
"Clementine",
"Clemmie",
"Cleo",
"Cleora",
"Cleta",
"Cletus",
"Cleve",
"Cleveland",
"Clifford",
"Clifton",
"Clint",
"Clinton",
"Clotilde",
"Clovis",
"Cloyd",
"Clyde",
"Coby",
"Cody",
"Colby",
"Cole",
"Coleman",
"Colin",
"Colleen",
"Collin",
"Colt",
"Colten",
"Colton",
"Columbus",
"Concepcion",
"Conner",
"Connie",
"Connor",
"Conor",
"Conrad",
"Constance",
"Constantin",
"Consuelo",
"Cooper",
"Cora",
"Coralie",
"Corbin",
"Cordelia",
"Cordell",
"Cordia",
"Cordie",
"Corene",
"Corine",
"Cornelius",
"Cornell",
"Corrine",
"Cortez",
"Cortney",
"Cory",
"Coty",
"Courtney",
"Coy",
"Craig",
"Crawford",
"Creola",
"Cristal",
"Cristian",
"Cristina",
"Cristobal",
"Cristopher",
"Cruz",
"Crystal",
"Crystel",
"Cullen",
"Curt",
"Curtis",
"Cydney",
"Cynthia",
"Cyril",
"Cyrus",
"Dagmar",
"Dahlia",
"Daija",
"Daisha",
"Daisy",
"Dakota",
"Dale",
"Dallas",
"Dallin",
"Dalton",
"Damaris",
"Dameon",
"Damian",
"Damien",
"Damion",
"Damon",
"Dan",
"Dana",
"Dandre",
"Dane",
"D'angelo",
"Dangelo",
"Danial",
"Daniela",
"Daniella",
"Danielle",
"Danika",
"Dannie",
"Danny",
"Dante",
"Danyka",
"Daphne",
"Daphnee",
"Daphney",
"Darby",
"Daren",
"Darian",
"Dariana",
"Darien",
"Dario",
"Darion",
"Darius",
"Darlene",
"Daron",
"Darrel",
"Darrell",
"Darren",
"Darrick",
"Darrin",
"Darrion",
"Darron",
"Darryl",
"Darwin",
"Daryl",
"Dashawn",
"Dasia",
"Dave",
"David",
"Davin",
"Davion",
"Davon",
"Davonte",
"Dawn",
"Dawson",
"Dax",
"Dayana",
"Dayna",
"Dayne",
"Dayton",
"Dean",
"Deangelo",
"Deanna",
"Deborah",
"Declan",
"Dedric",
"Dedrick",
"Dee",
"Deion",
"Deja",
"Dejah",
"Dejon",
"Dejuan",
"Delaney",
"Delbert",
"Delfina",
"Delia",
"Delilah",
"Dell",
"Della",
"Delmer",
"Delores",
"Delpha",
"Delphia",
"Delphine",
"Delta",
"Demarco",
"Demarcus",
"Demario",
"Demetris",
"Demetrius",
"Demond",
"Dena",
"Denis",
"Dennis",
"Deon",
"Deondre",
"Deontae",
"Deonte",
"Dereck",
"Derek",
"Derick",
"Deron",
"Derrick",
"Deshaun",
"Deshawn",
"Desiree",
"Desmond",
"Dessie",
"Destany",
"Destin",
"Destinee",
"Destiney",
"Destini",
"Destiny",
"Devan",
"Devante",
"Deven",
"Devin",
"Devon",
"Devonte",
"Devyn",
"Dewayne",
"Dewitt",
"Dexter",
"Diamond",
"Diana",
"Dianna",
"Diego",
"Dillan",
"Dillon",
"Dimitri",
"Dina",
"Dino",
"Dion",
"Dixie",
"Dock",
"Dolly",
"Dolores",
"Domenic",
"Domenica",
"Domenick",
"Domenico",
"Domingo",
"Dominic",
"Dominique",
"Don",
"Donald",
"Donato",
"Donavon",
"Donna",
"Donnell",
"Donnie",
"Donny",
"Dora",
"Dorcas",
"Dorian",
"Doris",
"Dorothea",
"Dorothy",
"Dorris",
"Dortha",
"Dorthy",
"Doug",
"Douglas",
"Dovie",
"Doyle",
"Drake",
"Drew",
"Duane",
"Dudley",
"Dulce",
"Duncan",
"Durward",
"Dustin",
"Dusty",
"Dwight",
"Dylan",
"Earl",
"Earlene",
"Earline",
"Earnest",
"Earnestine",
"Easter",
"Easton",
"Ebba",
"Ebony",
"Ed",
"Eda",
"Edd",
"Eddie",
"Eden",
"Edgar",
"Edgardo",
"Edison",
"Edmond",
"Edmund",
"Edna",
"Eduardo",
"Edward",
"Edwardo",
"Edwin",
"Edwina",
"Edyth",
"Edythe",
"Effie",
"Efrain",
"Efren",
"Eileen",
"Einar",
"Eino",
"Eladio",
"Elaina",
"Elbert",
"Elda",
"Eldon",
"Eldora",
"Eldred",
"Eldridge",
"Eleanora",
"Eleanore",
"Eleazar",
"Electa",
"Elena",
"Elenor",
"Elenora",
"Eleonore",
"Elfrieda",
"Eli",
"Elian",
"Eliane",
"Elias",
"Eliezer",
"Elijah",
"Elinor",
"Elinore",
"Elisa",
"Elisabeth",
"Elise",
"Eliseo",
"Elisha",
"Elissa",
"Eliza",
"Elizabeth",
"Ella",
"Ellen",
"Ellie",
"Elliot",
"Elliott",
"Ellis",
"Ellsworth",
"Elmer",
"Elmira",
"Elmo",
"Elmore",
"Elna",
"Elnora",
"Elody",
"Eloisa",
"Eloise",
"Elouise",
"Eloy",
"Elroy",
"Elsa",
"Else",
"Elsie",
"Elta",
"Elton",
"Elva",
"Elvera",
"Elvie",
"Elvis",
"Elwin",
"Elwyn",
"Elyse",
"Elyssa",
"Elza",
"Emanuel",
"Emelia",
"Emelie",
"Emely",
"Emerald",
"Emerson",
"Emery",
"Emie",
"Emil",
"Emile",
"Emilia",
"Emiliano",
"Emilie",
"Emilio",
"Emily",
"Emma",
"Emmalee",
"Emmanuel",
"Emmanuelle",
"Emmet",
"Emmett",
"Emmie",
"Emmitt",
"Emmy",
"Emory",
"Ena",
"Enid",
"Enoch",
"Enola",
"Enos",
"Enrico",
"Enrique",
"Ephraim",
"Era",
"Eriberto",
"Eric",
"Erica",
"Erich",
"Erick",
"Ericka",
"Erik",
"Erika",
"Erin",
"Erling",
"Erna",
"Ernest",
"Ernestina",
"Ernestine",
"Ernesto",
"Ernie",
"Ervin",
"Erwin",
"Eryn",
"Esmeralda",
"Esperanza",
"Esta",
"Esteban",
"Estefania",
"Estel",
"Estell",
"Estella",
"Estelle",
"Estevan",
"Esther",
"Estrella",
"Etha",
"Ethan",
"Ethel",
"Ethelyn",
"Ethyl",
"Ettie",
"Eudora",
"Eugene",
"Eugenia",
"Eula",
"Eulah",
"Eulalia",
"Euna",
"Eunice",
"Eusebio",
"Eva",
"Evalyn",
"Evan",
"Evangeline",
"Evans",
"Eve",
"Eveline",
"Evelyn",
"Everardo",
"Everett",
"Everette",
"Evert",
"Evie",
"Ewald",
"Ewell",
"Ezekiel",
"Ezequiel",
"Ezra",
"Fabian",
"Fabiola",
"Fae",
"Fannie",
"Fanny",
"Fatima",
"Faustino",
"Fausto",
"Favian",
"Fay",
"Faye",
"Federico",
"Felicia",
"Felicita",
"Felicity",
"Felipa",
"Felipe",
"Felix",
"Felton",
"Fermin",
"Fern",
"Fernando",
"Ferne",
"Fidel",
"Filiberto",
"Filomena",
"Finn",
"Fiona",
"Flavie",
"Flavio",
"Fleta",
"Fletcher",
"Flo",
"Florence",
"Florencio",
"Florian",
"Florida",
"Florine",
"Flossie",
"Floy",
"Floyd",
"Ford",
"Forest",
"Forrest",
"Foster",
"Frances",
"Francesca",
"Francesco",
"Francis",
"Francisca",
"Francisco",
"Franco",
"Frank",
"Frankie",
"Franz",
"Fred",
"Freda",
"Freddie",
"Freddy",
"Frederic",
"Frederick",
"Frederik",
"Frederique",
"Fredrick",
"Fredy",
"Freeda",
"Freeman",
"Freida",
"Frida",
"Frieda",
"Friedrich",
"Fritz",
"Furman",
"Gabe",
"Gabriel",
"Gabriella",
"Gabrielle",
"Gaetano",
"Gage",
"Gail",
"Gardner",
"Garett",
"Garfield",
"Garland",
"Garnet",
"Garnett",
"Garret",
"Garrett",
"Garrick",
"Garrison",
"Garry",
"Garth",
"Gaston",
"Gavin",
"Gay",
"Gayle",
"Gaylord",
"Gene",
"General",
"Genesis",
"Genevieve",
"Gennaro",
"Genoveva",
"Geo",
"Geoffrey",
"George",
"Georgette",
"Georgiana",
"Georgianna",
"Geovanni",
"Geovanny",
"Geovany",
"Gerald",
"Geraldine",
"Gerard",
"Gerardo",
"Gerda",
"Gerhard",
"Germaine",
"German",
"Gerry",
"Gerson",
"Gertrude",
"Gia",
"Gianni",
"Gideon",
"Gilbert",
"Gilberto",
"Gilda",
"Giles",
"Gillian",
"Gina",
"Gino",
"Giovani",
"Giovanna",
"Giovanni",
"Giovanny",
"Gisselle",
"Giuseppe",
"Gladyce",
"Gladys",
"Glen",
"Glenda",
"Glenna",
"Glennie",
"Gloria",
"Godfrey",
"Golda",
"Golden",
"Gonzalo",
"Gordon",
"Grace",
"Gracie",
"Graciela",
"Grady",
"Graham",
"Grant",
"Granville",
"Grayce",
"Grayson",
"Green",
"Greg",
"Gregg",
"Gregoria",
"Gregorio",
"Gregory",
"Greta",
"Gretchen",
"Greyson",
"Griffin",
"Grover",
"Guadalupe",
"Gudrun",
"Guido",
"Guillermo",
"Guiseppe",
"Gunnar",
"Gunner",
"Gus",
"Gussie",
"Gust",
"Gustave",
"Guy",
"Gwen",
"Gwendolyn",
"Hadley",
"Hailee",
"Hailey",
"Hailie",
"Hal",
"Haleigh",
"Haley",
"Halie",
"Halle",
"Hallie",
"Hank",
"Hanna",
"Hannah",
"Hans",
"Hardy",
"Harley",
"Harmon",
"Harmony",
"Harold",
"Harrison",
"Harry",
"Harvey",
"Haskell",
"Hassan",
"Hassie",
"Hattie",
"Haven",
"Hayden",
"Haylee",
"Hayley",
"Haylie",
"Hazel",
"Hazle",
"Heath",
"Heather",
"Heaven",
"Heber",
"Hector",
"Heidi",
"Helen",
"Helena",
"Helene",
"Helga",
"Hellen",
"Helmer",
"Heloise",
"Henderson",
"Henri",
"Henriette",
"Henry",
"Herbert",
"Herman",
"Hermann",
"Hermina",
"Herminia",
"Herminio",
"Hershel",
"Herta",
"Hertha",
"Hester",
"Hettie",
"Hilario",
"Hilbert",
"Hilda",
"Hildegard",
"Hillard",
"Hillary",
"Hilma",
"Hilton",
"Hipolito",
"Hiram",
"Hobart",
"Holden",
"Hollie",
"Hollis",
"Holly",
"Hope",
"Horace",
"Horacio",
"Hortense",
"Hosea",
"Houston",
"Howard",
"Howell",
"Hoyt",
"Hubert",
"Hudson",
"Hugh",
"Hulda",
"Humberto",
"Hunter",
"Hyman",
"Ian",
"Ibrahim",
"Icie",
"Ida",
"Idell",
"Idella",
"Ignacio",
"Ignatius",
"Ike",
"Ila",
"Ilene",
"Iliana",
"Ima",
"Imani",
"Imelda",
"Immanuel",
"Imogene",
"Ines",
"Irma",
"Irving",
"Irwin",
"Isaac",
"Isabel",
"Isabell",
"Isabella",
"Isabelle",
"Isac",
"Isadore",
"Isai",
"Isaiah",
"Isaias",
"Isidro",
"Ismael",
"Isobel",
"Isom",
"Israel",
"Issac",
"Itzel",
"Iva",
"Ivah",
"Ivory",
"Ivy",
"Izabella",
"Izaiah",
"Jabari",
"Jace",
"Jacey",
"Jacinthe",
"Jacinto",
"Jack",
"Jackeline",
"Jackie",
"Jacklyn",
"Jackson",
"Jacky",
"Jaclyn",
"Jacquelyn",
"Jacques",
"Jacynthe",
"Jada",
"Jade",
"Jaden",
"Jadon",
"Jadyn",
"Jaeden",
"Jaida",
"Jaiden",
"Jailyn",
"Jaime",
"Jairo",
"Jakayla",
"Jake",
"Jakob",
"Jaleel",
"Jalen",
"Jalon",
"Jalyn",
"Jamaal",
"Jamal",
"Jamar",
"Jamarcus",
"Jamel",
"Jameson",
"Jamey",
"Jamie",
"Jamil",
"Jamir",
"Jamison",
"Jammie",
"Jan",
"Jana",
"Janae",
"Jane",
"Janelle",
"Janessa",
"Janet",
"Janice",
"Janick",
"Janie",
"Janis",
"Janiya",
"Jannie",
"Jany",
"Jaquan",
"Jaquelin",
"Jaqueline",
"Jared",
"Jaren",
"Jarod",
"Jaron",
"Jarred",
"Jarrell",
"Jarret",
"Jarrett",
"Jarrod",
"Jarvis",
"Jasen",
"Jasmin",
"Jason",
"Jasper",
"Jaunita",
"Javier",
"Javon",
"Javonte",
"Jay",
"Jayce",
"Jaycee",
"Jayda",
"Jayde",
"Jayden",
"Jaydon",
"Jaylan",
"Jaylen",
"Jaylin",
"Jaylon",
"Jayme",
"Jayne",
"Jayson",
"Jazlyn",
"Jazmin",
"Jazmyn",
"Jazmyne",
"Jean",
"Jeanette",
"Jeanie",
"Jeanne",
"Jed",
"Jedediah",
"Jedidiah",
"Jeff",
"Jefferey",
"Jeffery",
"Jeffrey",
"Jeffry",
"Jena",
"Jenifer",
"Jennie",
"Jennifer",
"Jennings",
"Jennyfer",
"Jensen",
"Jerad",
"Jerald",
"Jeramie",
"Jeramy",
"Jerel",
"Jeremie",
"Jeremy",
"Jermain",
"Jermaine",
"Jermey",
"Jerod",
"Jerome",
"Jeromy",
"Jerrell",
"Jerrod",
"Jerrold",
"Jerry",
"Jess",
"Jesse",
"Jessica",
"Jessie",
"Jessika",
"Jessy",
"Jessyca",
"Jesus",
"Jett",
"Jettie",
"Jevon",
"Jewel",
"Jewell",
"Jillian",
"Jimmie",
"Jimmy",
"Jo",
"Joan",
"Joana",
"Joanie",
"Joanne",
"Joannie",
"Joanny",
"Joany",
"Joaquin",
"Jocelyn",
"Jodie",
"Jody",
"Joe",
"Joel",
"Joelle",
"Joesph",
"Joey",
"Johan",
"Johann",
"Johanna",
"Johathan",
"John",
"Johnathan",
"Johnathon",
"Johnnie",
"Johnny",
"Johnpaul",
"Johnson",
"Jolie",
"Jon",
"Jonas",
"Jonatan",
"Jonathan",
"Jonathon",
"Jordan",
"Jordane",
"Jordi",
"Jordon",
"Jordy",
"Jordyn",
"Jorge",
"Jose",
"Josefa",
"Josefina",
"Joseph",
"Josephine",
"Josh",
"Joshua",
"Joshuah",
"Josiah",
"Josiane",
"Josianne",
"Josie",
"Josue",
"Jovan",
"Jovani",
"Jovanny",
"Jovany",
"Joy",
"Joyce",
"Juana",
"Juanita",
"Judah",
"Judd",
"Jude",
"Judge",
"Judson",
"Judy",
"Jules",
"Julia",
"Julian",
"Juliana",
"Julianne",
"Julie",
"Julien",
"Juliet",
"Julio",
"Julius",
"June",
"Junior",
"Junius",
"Justen",
"Justice",
"Justina",
"Justine",
"Juston",
"Justus",
"Justyn",
"Juvenal",
"Juwan",
"Kacey",
"Kaci",
"Kacie",
"Kade",
"Kaden",
"Kadin",
"Kaela",
"Kaelyn",
"Kaia",
"Kailee",
"Kailey",
"Kailyn",
"Kaitlin",
"Kaitlyn",
"Kale",
"Kaleb",
"Kaleigh",
"Kaley",
"Kali",
"Kallie",
"Kameron",
"Kamille",
"Kamren",
"Kamron",
"Kamryn",
"Kane",
"Kara",
"Kareem",
"Karelle",
"Karen",
"Kari",
"Kariane",
"Karianne",
"Karina",
"Karine",
"Karl",
"Karlee",
"Karley",
"Karli",
"Karlie",
"Karolann",
"Karson",
"Kasandra",
"Kasey",
"Kassandra",
"Katarina",
"Katelin",
"Katelyn",
"Katelynn",
"Katharina",
"Katherine",
"Katheryn",
"Kathleen",
"Kathlyn",
"Kathryn",
"Kathryne",
"Katlyn",
"Katlynn",
"Katrina",
"Katrine",
"Kattie",
"Kavon",
"Kay",
"Kaya",
"Kaycee",
"Kayden",
"Kayla",
"Kaylah",
"Kaylee",
"Kayleigh",
"Kayley",
"Kayli",
"Kaylie",
"Kaylin",
"Keagan",
"Keanu",
"Keara",
"Keaton",
"Keegan",
"Keeley",
"Keely",
"Keenan",
"Keira",
"Keith",
"Kellen",
"Kelley",
"Kelli",
"Kellie",
"Kelly",
"Kelsi",
"Kelsie",
"Kelton",
"Kelvin",
"Ken",
"Kendall",
"Kendra",
"Kendrick",
"Kenna",
"Kennedi",
"Kennedy",
"Kenneth",
"Kennith",
"Kenny",
"Kenton",
"Kenya",
"Kenyatta",
"Kenyon",
"Keon",
"Keshaun",
"Keshawn",
"Keven",
"Kevin",
"Kevon",
"Keyon",
"Keyshawn",
"Khalid",
"Khalil",
"Kian",
"Kiana",
"Kianna",
"Kiara",
"Kiarra",
"Kiel",
"Kiera",
"Kieran",
"Kiley",
"Kim",
"Kimberly",
"King",
"Kip",
"Kira",
"Kirk",
"Kirsten",
"Kirstin",
"Kitty",
"Kobe",
"Koby",
"Kody",
"Kolby",
"Kole",
"Korbin",
"Korey",
"Kory",
"Kraig",
"Kris",
"Krista",
"Kristian",
"Kristin",
"Kristina",
"Kristofer",
"Kristoffer",
"Kristopher",
"Kristy",
"Krystal",
"Krystel",
"Krystina",
"Kurt",
"Kurtis",
"Kyla",
"Kyle",
"Kylee",
"Kyleigh",
"Kyler",
"Kylie",
"Kyra",
"Lacey",
"Lacy",
"Ladarius",
"Lafayette",
"Laila",
"Laisha",
"Lamar",
"Lambert",
"Lamont",
"Lance",
"Landen",
"Lane",
"Laney",
"Larissa",
"Laron",
"Larry",
"Larue",
"Laura",
"Laurel",
"Lauren",
"Laurence",
"Lauretta",
"Lauriane",
"Laurianne",
"Laurie",
"Laurine",
"Laury",
"Lauryn",
"Lavada",
"Lavern",
"Laverna",
"Laverne",
"Lavina",
"Lavinia",
"Lavon",
"Lavonne",
"Lawrence",
"Lawson",
"Layla",
"Layne",
"Lazaro",
"Lea",
"Leann",
"Leanna",
"Leanne",
"Leatha",
"Leda",
"Lee",
"Leif",
"Leila",
"Leilani",
"Lela",
"Lelah",
"Leland",
"Lelia",
"Lempi",
"Lemuel",
"Lenna",
"Lennie",
"Lenny",
"Lenora",
"Lenore",
"Leo",
"Leola",
"Leon",
"Leonard",
"Leonardo",
"Leone",
"Leonel",
"Leonie",
"Leonor",
"Leonora",
"Leopold",
"Leopoldo",
"Leora",
"Lera",
"Lesley",
"Leslie",
"Lesly",
"Lessie",
"Lester",
"Leta",
"Letha",
"Letitia",
"Levi",
"Lew",
"Lewis",
"Lexi",
"Lexie",
"Lexus",
"Lia",
"Liam",
"Liana",
"Libbie",
"Libby",
"Lila",
"Lilian",
"Liliana",
"Liliane",
"Lilla",
"Lillian",
"Lilliana",
"Lillie",
"Lilly",
"Lily",
"Lilyan",
"Lina",
"Lincoln",
"Linda",
"Lindsay",
"Lindsey",
"Linnea",
"Linnie",
"Linwood",
"Lionel",
"Lisa",
"Lisandro",
"Lisette",
"Litzy",
"Liza",
"Lizeth",
"Lizzie",
"Llewellyn",
"Lloyd",
"Logan",
"Lois",
"Lola",
"Lolita",
"Loma",
"Lon",
"London",
"Lonie",
"Lonnie",
"Lonny",
"Lonzo",
"Lora",
"Loraine",
"Loren",
"Lorena",
"Lorenz",
"Lorenza",
"Lorenzo",
"Lori",
"Lorine",
"Lorna",
"Lottie",
"Lou",
"Louie",
"Louisa",
"Lourdes",
"Louvenia",
"Lowell",
"Loy",
"Loyal",
"Loyce",
"Lucas",
"Luciano",
"Lucie",
"Lucienne",
"Lucile",
"Lucinda",
"Lucio",
"Lucious",
"Lucius",
"Lucy",
"Ludie",
"Ludwig",
"Lue",
"Luella",
"Luigi",
"Luis",
"Luisa",
"Lukas",
"Lula",
"Lulu",
"Luna",
"Lupe",
"Lura",
"Lurline",
"Luther",
"Luz",
"Lyda",
"Lydia",
"Lyla",
"Lynn",
"Lyric",
"Lysanne",
"Mabel",
"Mabelle",
"Mable",
"Mac",
"Macey",
"Maci",
"Macie",
"Mack",
"Mackenzie",
"Macy",
"Madaline",
"Madalyn",
"Maddison",
"Madeline",
"Madelyn",
"Madelynn",
"Madge",
"Madie",
"Madilyn",
"Madisen",
"Madison",
"Madisyn",
"Madonna",
"Madyson",
"Mae",
"Maegan",
"Maeve",
"Mafalda",
"Magali",
"Magdalen",
"Magdalena",
"Maggie",
"Magnolia",
"Magnus",
"Maia",
"Maida",
"Maiya",
"Major",
"Makayla",
"Makenna",
"Makenzie",
"Malachi",
"Malcolm",
"Malika",
"Malinda",
"Mallie",
"Mallory",
"Malvina",
"Mandy",
"Manley",
"Manuel",
"Manuela",
"Mara",
"Marc",
"Marcel",
"Marcelina",
"Marcelino",
"Marcella",
"Marcelle",
"Marcellus",
"Marcelo",
"Marcia",
"Marco",
"Marcos",
"Marcus",
"Margaret",
"Margarete",
"Margarett",
"Margaretta",
"Margarette",
"Margarita",
"Marge",
"Margie",
"Margot",
"Margret",
"Marguerite",
"Maria",
"Mariah",
"Mariam",
"Marian",
"Mariana",
"Mariane",
"Marianna",
"Marianne",
"Mariano",
"Maribel",
"Marie",
"Mariela",
"Marielle",
"Marietta",
"Marilie",
"Marilou",
"Marilyne",
"Marina",
"Mario",
"Marion",
"Marisa",
"Marisol",
"Maritza",
"Marjolaine",
"Marjorie",
"Marjory",
"Mark",
"Markus",
"Marlee",
"Marlen",
"Marlene",
"Marley",
"Marlin",
"Marlon",
"Marques",
"Marquis",
"Marquise",
"Marshall",
"Marta",
"Martin",
"Martina",
"Martine",
"Marty",
"Marvin",
"Mary",
"Maryam",
"Maryjane",
"Maryse",
"Mason",
"Mateo",
"Mathew",
"Mathias",
"Mathilde",
"Matilda",
"Matilde",
"Matt",
"Matteo",
"Mattie",
"Maud",
"Maude",
"Maudie",
"Maureen",
"Maurice",
"Mauricio",
"Maurine",
"Maverick",
"Mavis",
"Max",
"Maxie",
"Maxime",
"Maximilian",
"Maximillia",
"Maximillian",
"Maximo",
"Maximus",
"Maxine",
"Maxwell",
"May",
"Maya",
"Maybell",
"Maybelle",
"Maye",
"Maymie",
"Maynard",
"Mayra",
"Mazie",
"Mckayla",
"Mckenna",
"Mckenzie",
"Meagan",
"Meaghan",
"Meda",
"Megane",
"Meggie",
"Meghan",
"Mekhi",
"Melany",
"Melba",
"Melisa",
"Melissa",
"Mellie",
"Melody",
"Melvin",
"Melvina",
"Melyna",
"Melyssa",
"Mercedes",
"Meredith",
"Merl",
"Merle",
"Merlin",
"Merritt",
"Mertie",
"Mervin",
"Meta",
"Mia",
"Micaela",
"Micah",
"Michael",
"Michaela",
"Michale",
"Micheal",
"Michel",
"Michele",
"Michelle",
"Miguel",
"Mikayla",
"Mike",
"Mikel",
"Milan",
"Miles",
"Milford",
"Miller",
"Millie",
"Milo",
"Milton",
"Mina",
"Minerva",
"Minnie",
"Miracle",
"Mireille",
"Mireya",
"Misael",
"Missouri",
"Misty",
"Mitchel",
"Mitchell",
"Mittie",
"Modesta",
"Modesto",
"Mohamed",
"Mohammad",
"Mohammed",
"Moises",
"Mollie",
"Molly",
"Mona",
"Monica",
"Monique",
"Monroe",
"Monserrat",
"Monserrate",
"Montana",
"Monte",
"Monty",
"Morgan",
"Moriah",
"Morris",
"Mortimer",
"Morton",
"Mose",
"Moses",
"Moshe",
"Mossie",
"Mozell",
"Mozelle",
"Muhammad",
"Muriel",
"Murl",
"Murphy",
"Murray",
"Mustafa",
"Mya",
"Myah",
"Mylene",
"Myles",
"Myra",
"Myriam",
"Myrl",
"Myrna",
"Myron",
"Myrtice",
"Myrtie",
"Myrtis",
"Myrtle",
"Nadia",
"Nakia",
"Name",
"Nannie",
"Naomi",
"Naomie",
"Napoleon",
"Narciso",
"Nash",
"Nasir",
"Nat",
"Natalia",
"Natalie",
"Natasha",
"Nathan",
"Nathanael",
"Nathanial",
"Nathaniel",
"Nathen",
"Nayeli",
"Neal",
"Ned",
"Nedra",
"Neha",
"Neil",
"Nelda",
"Nella",
"Nelle",
"Nellie",
"Nels",
"Nelson",
"Neoma",
"Nestor",
"Nettie",
"Neva",
"Newell",
"Newton",
"Nia",
"Nicholas",
"Nicholaus",
"Nichole",
"Nick",
"Nicklaus",
"Nickolas",
"Nico",
"Nicola",
"Nicolas",
"Nicole",
"Nicolette",
"Nigel",
"Nikita",
"Nikki",
"Nikko",
"Niko",
"Nikolas",
"Nils",
"Nina",
"Noah",
"Noble",
"Noe",
"Noel",
"Noelia",
"Noemi",
"Noemie",
"Noemy",
"Nola",
"Nolan",
"Nona",
"Nora",
"Norbert",
"Norberto",
"Norene",
"Norma",
"Norris",
"Norval",
"Norwood",
"Nova",
"Novella",
"Nya",
"Nyah",
"Nyasia",
"Obie",
"Oceane",
"Ocie",
"Octavia",
"Oda",
"Odell",
"Odessa",
"Odie",
"Ofelia",
"Okey",
"Ola",
"Olaf",
"Ole",
"Olen",
"Oleta",
"Olga",
"Olin",
"Oliver",
"Ollie",
"Oma",
"Omari",
"Omer",
"Ona",
"Onie",
"Opal",
"Ophelia",
"Ora",
"Oral",
"Oran",
"Oren",
"Orie",
"Orin",
"Orion",
"Orland",
"Orlando",
"Orlo",
"Orpha",
"Orrin",
"Orval",
"Orville",
"Osbaldo",
"Osborne",
"Oscar",
"Osvaldo",
"Oswald",
"Oswaldo",
"Otha",
"Otho",
"Otilia",
"Otis",
"Ottilie",
"Ottis",
"Otto",
"Ova",
"Owen",
"Ozella",
"Pablo",
"Paige",
"Palma",
"Pamela",
"Pansy",
"Paolo",
"Paris",
"Parker",
"Pascale",
"Pasquale",
"Pat",
"Patience",
"Patricia",
"Patrick",
"Patsy",
"Pattie",
"Paul",
"Paula",
"Pauline",
"Paxton",
"Payton",
"Pearl",
"Pearlie",
"Pearline",
"Pedro",
"Peggie",
"Penelope",
"Percival",
"Percy",
"Perry",
"Pete",
"Peter",
"Petra",
"Peyton",
"Philip",
"Phoebe",
"Phyllis",
"Pierce",
"Pierre",
"Pietro",
"Pink",
"Pinkie",
"Piper",
"Polly",
"Porter",
"Precious",
"Presley",
"Preston",
"Price",
"Prince",
"Princess",
"Priscilla",
"Providenci",
"Prudence",
"Queen",
"Queenie",
"Quentin",
"Quincy",
"Quinn",
"Quinten",
"Quinton",
"Rachael",
"Rachel",
"Rachelle",
"Rae",
"Raegan",
"Rafael",
"Rafaela",
"Raheem",
"Rahsaan",
"Rahul",
"Raina",
"Raleigh",
"Ralph",
"Ramiro",
"Ramon",
"Ramona",
"Randal",
"Randall",
"Randi",
"Randy",
"Ransom",
"Raoul",
"Raphael",
"Raphaelle",
"Raquel",
"Rashad",
"Rashawn",
"Rasheed",
"Raul",
"Raven",
"Ray",
"Raymond",
"Raymundo",
"Reagan",
"Reanna",
"Reba",
"Rebeca",
"Rebecca",
"Rebeka",
"Rebekah",
"Reece",
"Reed",
"Reese",
"Regan",
"Reggie",
"Reginald",
"Reid",
"Reilly",
"Reina",
"Reinhold",
"Remington",
"Rene",
"Renee",
"Ressie",
"Reta",
"Retha",
"Retta",
"Reuben",
"Reva",
"Rex",
"Rey",
"Reyes",
"Reymundo",
"Reyna",
"Reynold",
"Rhea",
"Rhett",
"Rhianna",
"Rhiannon",
"Rhoda",
"Ricardo",
"Richard",
"Richie",
"Richmond",
"Rick",
"Rickey",
"Rickie",
"Ricky",
"Rico",
"Rigoberto",
"Riley",
"Rita",
"River",
"Robb",
"Robbie",
"Robert",
"Roberta",
"Roberto",
"Robin",
"Robyn",
"Rocio",
"Rocky",
"Rod",
"Roderick",
"Rodger",
"Rodolfo",
"Rodrick",
"Rodrigo",
"Roel",
"Rogelio",
"Roger",
"Rogers",
"Rolando",
"Rollin",
"Roma",
"Romaine",
"Roman",
"Ron",
"Ronaldo",
"Ronny",
"Roosevelt",
"Rory",
"Rosa",
"Rosalee",
"Rosalia",
"Rosalind",
"Rosalinda",
"Rosalyn",
"Rosamond",
"Rosanna",
"Rosario",
"Roscoe",
"Rose",
"Rosella",
"Roselyn",
"Rosemarie",
"Rosemary",
"Rosendo",
"Rosetta",
"Rosie",
"Rosina",
"Roslyn",
"Ross",
"Rossie",
"Rowan",
"Rowena",
"Rowland",
"Roxane",
"Roxanne",
"Roy",
"Royal",
"Royce",
"Rozella",
"Ruben",
"Rubie",
"Ruby",
"Rubye",
"Rudolph",
"Rudy",
"Rupert",
"Russ",
"Russel",
"Russell",
"Rusty",
"Ruth",
"Ruthe",
"Ruthie",
"Ryan",
"Ryann",
"Ryder",
"Rylan",
"Rylee",
"Ryleigh",
"Ryley",
"Sabina",
"Sabrina",
"Sabryna",
"Sadie",
"Sadye",
"Sage",
"Saige",
"Sallie",
"Sally",
"Salma",
"Salvador",
"Salvatore",
"Sam",
"Samanta",
"Samantha",
"Samara",
"Samir",
"Sammie",
"Sammy",
"Samson",
"Sandra",
"Sandrine",
"Sandy",
"Sanford",
"Santa",
"Santiago",
"Santina",
"Santino",
"Santos",
"Sarah",
"Sarai",
"Sarina",
"Sasha",
"Saul",
"Savanah",
"Savanna",
"Savannah",
"Savion",
"Scarlett",
"Schuyler",
"Scot",
"Scottie",
"Scotty",
"Seamus",
"Sean",
"Sebastian",
"Sedrick",
"Selena",
"Selina",
"Selmer",
"Serena",
"Serenity",
"Seth",
"Shad",
"Shaina",
"Shakira",
"Shana",
"Shane",
"Shanel",
"Shanelle",
"Shania",
"Shanie",
"Shaniya",
"Shanna",
"Shannon",
"Shanny",
"Shanon",
"Shany",
"Sharon",
"Shaun",
"Shawn",
"Shawna",
"Shaylee",
"Shayna",
"Shayne",
"Shea",
"Sheila",
"Sheldon",
"Shemar",
"Sheridan",
"Sherman",
"Sherwood",
"Shirley",
"Shyann",
"Shyanne",
"Sibyl",
"Sid",
"Sidney",
"Sienna",
"Sierra",
"Sigmund",
"Sigrid",
"Sigurd",
"Silas",
"Sim",
"Simeon",
"Simone",
"Sincere",
"Sister",
"Skye",
"Skyla",
"Skylar",
"Sofia",
"Soledad",
"Solon",
"Sonia",
"Sonny",
"Sonya",
"Sophia",
"Sophie",
"Spencer",
"Stacey",
"Stacy",
"Stan",
"Stanford",
"Stanley",
"Stanton",
"Stefan",
"Stefanie",
"Stella",
"Stephan",
"Stephania",
"Stephanie",
"Stephany",
"Stephen",
"Stephon",
"Sterling",
"Steve",
"Stevie",
"Stewart",
"Stone",
"Stuart",
"Summer",
"Sunny",
"Susan",
"Susana",
"Susanna",
"Susie",
"Suzanne",
"Sven",
"Syble",
"Sydnee",
"Sydney",
"Sydni",
"Sydnie",
"Sylvan",
"Sylvester",
"Sylvia",
"Tabitha",
"Tad",
"Talia",
"Talon",
"Tamara",
"Tamia",
"Tania",
"Tanner",
"Tanya",
"Tara",
"Taryn",
"Tate",
"Tatum",
"Tatyana",
"Taurean",
"Tavares",
"Taya",
"Taylor",
"Teagan",
"Ted",
"Telly",
"Terence",
"Teresa",
"Terrance",
"Terrell",
"Terrence",
"Terrill",
"Terry",
"Tess",
"Tessie",
"Tevin",
"Thad",
"Thaddeus",
"Thalia",
"Thea",
"Thelma",
"Theo",
"Theodora",
"Theodore",
"Theresa",
"Therese",
"Theresia",
"Theron",
"Thomas",
"Thora",
"Thurman",
"Tia",
"Tiana",
"Tianna",
"Tiara",
"Tierra",
"Tiffany",
"Tillman",
"Timmothy",
"Timmy",
"Timothy",
"Tina",
"Tito",
"Titus",
"Tobin",
"Toby",
"Tod",
"Tom",
"Tomas",
"Tomasa",
"Tommie",
"Toney",
"Toni",
"Tony",
"Torey",
"Torrance",
"Torrey",
"Toy",
"Trace",
"Tracey",
"Tracy",
"Travis",
"Travon",
"Tre",
"Tremaine",
"Tremayne",
"Trent",
"Trenton",
"Tressa",
"Tressie",
"Treva",
"Trever",
"Trevion",
"Trevor",
"Trey",
"Trinity",
"Trisha",
"Tristian",
"Tristin",
"Triston",
"Troy",
"Trudie",
"Trycia",
"Trystan",
"Turner",
"Twila",
"Tyler",
"Tyra",
"Tyree",
"Tyreek",
"Tyrel",
"Tyrell",
"Tyrese",
"Tyrique",
"Tyshawn",
"Tyson",
"Ubaldo",
"Ulices",
"Ulises",
"Una",
"Unique",
"Urban",
"Uriah",
"Uriel",
"Ursula",
"Vada",
"Valentin",
"Valentina",
"Valentine",
"Valerie",
"Vallie",
"Van",
"Vance",
"Vanessa",
"Vaughn",
"Veda",
"Velda",
"Vella",
"Velma",
"Velva",
"Vena",
"Verda",
"Verdie",
"Vergie",
"Verla",
"Verlie",
"Vern",
"Verna",
"Verner",
"Vernice",
"Vernie",
"Vernon",
"Verona",
"Veronica",
"Vesta",
"Vicenta",
"Vicente",
"Vickie",
"Vicky",
"Victor",
"Victoria",
"Vida",
"Vidal",
"Vilma",
"Vince",
"Vincent",
"Vincenza",
"Vincenzo",
"Vinnie",
"Viola",
"Violet",
"Violette",
"Virgie",
"Virgil",
"Virginia",
"Virginie",
"Vita",
"Vito",
"Viva",
"Vivian",
"Viviane",
"Vivianne",
"Vivien",
"Vivienne",
"Vladimir",
"Wade",
"Waino",
"Waldo",
"Walker",
"Wallace",
"Walter",
"Walton",
"Wanda",
"Ward",
"Warren",
"Watson",
"Wava",
"Waylon",
"Wayne",
"Webster",
"Weldon",
"Wellington",
"Wendell",
"Wendy",
"Werner",
"Westley",
"Weston",
"Whitney",
"Wilber",
"Wilbert",
"Wilburn",
"Wiley",
"Wilford",
"Wilfred",
"Wilfredo",
"Wilfrid",
"Wilhelm",
"Wilhelmine",
"Will",
"Willa",
"Willard",
"William",
"Willie",
"Willis",
"Willow",
"Willy",
"Wilma",
"Wilmer",
"Wilson",
"Wilton",
"Winfield",
"Winifred",
"Winnifred",
"Winona",
"Winston",
"Woodrow",
"Wyatt",
"Wyman",
"Xander",
"Xavier",
"Xzavier",
"Yadira",
"Yasmeen",
"Yasmin",
"Yasmine",
"Yazmin",
"Yesenia",
"Yessenia",
"Yolanda",
"Yoshiko",
"Yvette",
"Yvonne",
"Zachariah",
"Zachary",
"Zachery",
"Zack",
"Zackary",
"Zackery",
"Zakary",
"Zander",
"Zane",
"Zaria",
"Zechariah",
"Zelda",
"Zella",
"Zelma",
"Zena",
"Zetta",
"Zion",
"Zita",
"Zoe",
"Zoey",
"Zoie",
"Zoila",
"Zola",
"Zora",
"Zula"
];
},{}],122:[function(require,module,exports){
var name = {};
module['exports'] = name;
name.first_name = require("./first_name");
name.last_name = require("./last_name");
name.prefix = require("./prefix");
name.suffix = require("./suffix");
name.title = require("./title");
name.name = require("./name");
},{"./first_name":121,"./last_name":123,"./name":124,"./prefix":125,"./suffix":126,"./title":127}],123:[function(require,module,exports){
module["exports"] = [
"Abbott",
"Abernathy",
"Abshire",
"Adams",
"Altenwerth",
"Anderson",
"Ankunding",
"Armstrong",
"Auer",
"Aufderhar",
"Bahringer",
"Bailey",
"Balistreri",
"Barrows",
"Bartell",
"Bartoletti",
"Barton",
"Bashirian",
"Batz",
"Bauch",
"Baumbach",
"Bayer",
"Beahan",
"Beatty",
"Bechtelar",
"Becker",
"Bednar",
"Beer",
"Beier",
"Berge",
"Bergnaum",
"Bergstrom",
"Bernhard",
"Bernier",
"Bins",
"Blanda",
"Blick",
"Block",
"Bode",
"Boehm",
"Bogan",
"Bogisich",
"Borer",
"Bosco",
"Botsford",
"Boyer",
"Boyle",
"Bradtke",
"Brakus",
"Braun",
"Breitenberg",
"Brekke",
"Brown",
"Bruen",
"Buckridge",
"Carroll",
"Carter",
"Cartwright",
"Casper",
"Cassin",
"Champlin",
"Christiansen",
"Cole",
"Collier",
"Collins",
"Conn",
"Connelly",
"Conroy",
"Considine",
"Corkery",
"Cormier",
"Corwin",
"Cremin",
"Crist",
"Crona",
"Cronin",
"Crooks",
"Cruickshank",
"Cummerata",
"Cummings",
"Dach",
"D'Amore",
"Daniel",
"Dare",
"Daugherty",
"Davis",
"Deckow",
"Denesik",
"Dibbert",
"Dickens",
"Dicki",
"Dickinson",
"Dietrich",
"Donnelly",
"Dooley",
"Douglas",
"Doyle",
"DuBuque",
"Durgan",
"Ebert",
"Effertz",
"Eichmann",
"Emard",
"Emmerich",
"Erdman",
"Ernser",
"Fadel",
"Fahey",
"Farrell",
"Fay",
"Feeney",
"Feest",
"Feil",
"Ferry",
"Fisher",
"Flatley",
"Frami",
"Franecki",
"Friesen",
"Fritsch",
"Funk",
"Gaylord",
"Gerhold",
"Gerlach",
"Gibson",
"Gislason",
"Gleason",
"Gleichner",
"Glover",
"Goldner",
"Goodwin",
"Gorczany",
"Gottlieb",
"Goyette",
"Grady",
"Graham",
"Grant",
"Green",
"Greenfelder",
"Greenholt",
"Grimes",
"Gulgowski",
"Gusikowski",
"Gutkowski",
"Gutmann",
"Haag",
"Hackett",
"Hagenes",
"Hahn",
"Haley",
"Halvorson",
"Hamill",
"Hammes",
"Hand",
"Hane",
"Hansen",
"Harber",
"Harris",
"Hartmann",
"Harvey",
"Hauck",
"Hayes",
"Heaney",
"Heathcote",
"Hegmann",
"Heidenreich",
"Heller",
"Herman",
"Hermann",
"Hermiston",
"Herzog",
"Hessel",
"Hettinger",
"Hickle",
"Hilll",
"Hills",
"Hilpert",
"Hintz",
"Hirthe",
"Hodkiewicz",
"Hoeger",
"Homenick",
"Hoppe",
"Howe",
"Howell",
"Hudson",
"Huel",
"Huels",
"Hyatt",
"Jacobi",
"Jacobs",
"Jacobson",
"Jakubowski",
"Jaskolski",
"Jast",
"Jenkins",
"Jerde",
"Johns",
"Johnson",
"Johnston",
"Jones",
"Kassulke",
"Kautzer",
"Keebler",
"Keeling",
"Kemmer",
"Kerluke",
"Kertzmann",
"Kessler",
"Kiehn",
"Kihn",
"Kilback",
"King",
"Kirlin",
"Klein",
"Kling",
"Klocko",
"Koch",
"Koelpin",
"Koepp",
"Kohler",
"Konopelski",
"Koss",
"Kovacek",
"Kozey",
"Krajcik",
"Kreiger",
"Kris",
"Kshlerin",
"Kub",
"Kuhic",
"Kuhlman",
"Kuhn",
"Kulas",
"Kunde",
"Kunze",
"Kuphal",
"Kutch",
"Kuvalis",
"Labadie",
"Lakin",
"Lang",
"Langosh",
"Langworth",
"Larkin",
"Larson",
"Leannon",
"Lebsack",
"Ledner",
"Leffler",
"Legros",
"Lehner",
"Lemke",
"Lesch",
"Leuschke",
"Lind",
"Lindgren",
"Littel",
"Little",
"Lockman",
"Lowe",
"Lubowitz",
"Lueilwitz",
"Luettgen",
"Lynch",
"Macejkovic",
"MacGyver",
"Maggio",
"Mann",
"Mante",
"Marks",
"Marquardt",
"Marvin",
"Mayer",
"Mayert",
"McClure",
"McCullough",
"McDermott",
"McGlynn",
"McKenzie",
"McLaughlin",
"Medhurst",
"Mertz",
"Metz",
"Miller",
"Mills",
"Mitchell",
"Moen",
"Mohr",
"Monahan",
"Moore",
"Morar",
"Morissette",
"Mosciski",
"Mraz",
"Mueller",
"Muller",
"Murazik",
"Murphy",
"Murray",
"Nader",
"Nicolas",
"Nienow",
"Nikolaus",
"Nitzsche",
"Nolan",
"Oberbrunner",
"O'Connell",
"O'Conner",
"O'Hara",
"O'Keefe",
"O'Kon",
"Okuneva",
"Olson",
"Ondricka",
"O'Reilly",
"Orn",
"Ortiz",
"Osinski",
"Pacocha",
"Padberg",
"Pagac",
"Parisian",
"Parker",
"Paucek",
"Pfannerstill",
"Pfeffer",
"Pollich",
"Pouros",
"Powlowski",
"Predovic",
"Price",
"Prohaska",
"Prosacco",
"Purdy",
"Quigley",
"Quitzon",
"Rath",
"Ratke",
"Rau",
"Raynor",
"Reichel",
"Reichert",
"Reilly",
"Reinger",
"Rempel",
"Renner",
"Reynolds",
"Rice",
"Rippin",
"Ritchie",
"Robel",
"Roberts",
"Rodriguez",
"Rogahn",
"Rohan",
"Rolfson",
"Romaguera",
"Roob",
"Rosenbaum",
"Rowe",
"Ruecker",
"Runolfsdottir",
"Runolfsson",
"Runte",
"Russel",
"Rutherford",
"Ryan",
"Sanford",
"Satterfield",
"Sauer",
"Sawayn",
"Schaden",
"Schaefer",
"Schamberger",
"Schiller",
"Schimmel",
"Schinner",
"Schmeler",
"Schmidt",
"Schmitt",
"Schneider",
"Schoen",
"Schowalter",
"Schroeder",
"Schulist",
"Schultz",
"Schumm",
"Schuppe",
"Schuster",
"Senger",
"Shanahan",
"Shields",
"Simonis",
"Sipes",
"Skiles",
"Smith",
"Smitham",
"Spencer",
"Spinka",
"Sporer",
"Stamm",
"Stanton",
"Stark",
"Stehr",
"Steuber",
"Stiedemann",
"Stokes",
"Stoltenberg",
"Stracke",
"Streich",
"Stroman",
"Strosin",
"Swaniawski",
"Swift",
"Terry",
"Thiel",
"Thompson",
"Tillman",
"Torp",
"Torphy",
"Towne",
"Toy",
"Trantow",
"Tremblay",
"Treutel",
"Tromp",
"Turcotte",
"Turner",
"Ullrich",
"Upton",
"Vandervort",
"Veum",
"Volkman",
"Von",
"VonRueden",
"Waelchi",
"Walker",
"Walsh",
"Walter",
"Ward",
"Waters",
"Watsica",
"Weber",
"Wehner",
"Weimann",
"Weissnat",
"Welch",
"West",
"White",
"Wiegand",
"Wilderman",
"Wilkinson",
"Will",
"Williamson",
"Willms",
"Windler",
"Wintheiser",
"Wisoky",
"Wisozk",
"Witting",
"Wiza",
"Wolf",
"Wolff",
"Wuckert",
"Wunsch",
"Wyman",
"Yost",
"Yundt",
"Zboncak",
"Zemlak",
"Ziemann",
"Zieme",
"Zulauf"
];
},{}],124:[function(require,module,exports){
module["exports"] = [
"#{prefix} #{first_name} #{last_name}",
"#{first_name} #{last_name} #{suffix}",
"#{first_name} #{last_name}",
"#{first_name} #{last_name}",
"#{first_name} #{last_name}",
"#{first_name} #{last_name}"
];
},{}],125:[function(require,module,exports){
module["exports"] = [
"Mr.",
"Mrs.",
"Ms.",
"Miss",
"Dr."
];
},{}],126:[function(require,module,exports){
module["exports"] = [
"Jr.",
"Sr.",
"I",
"II",
"III",
"IV",
"V",
"MD",
"DDS",
"PhD",
"DVM"
];
},{}],127:[function(require,module,exports){
module["exports"] = {
"descriptor": [
"Lead",
"Senior",
"Direct",
"Corporate",
"Dynamic",
"Future",
"Product",
"National",
"Regional",
"District",
"Central",
"Global",
"Customer",
"Investor",
"Dynamic",
"International",
"Legacy",
"Forward",
"Internal",
"Human",
"Chief",
"Principal"
],
"level": [
"Solutions",
"Program",
"Brand",
"Security",
"Research",
"Marketing",
"Directives",
"Implementation",
"Integration",
"Functionality",
"Response",
"Paradigm",
"Tactics",
"Identity",
"Markets",
"Group",
"Division",
"Applications",
"Optimization",
"Operations",
"Infrastructure",
"Intranet",
"Communications",
"Web",
"Branding",
"Quality",
"Assurance",
"Mobility",
"Accounts",
"Data",
"Creative",
"Configuration",
"Accountability",
"Interactions",
"Factors",
"Usability",
"Metrics"
],
"job": [
"Supervisor",
"Associate",
"Executive",
"Liason",
"Officer",
"Manager",
"Engineer",
"Specialist",
"Director",
"Coordinator",
"Administrator",
"Architect",
"Analyst",
"Designer",
"Planner",
"Orchestrator",
"Technician",
"Developer",
"Producer",
"Consultant",
"Assistant",
"Facilitator",
"Agent",
"Representative",
"Strategist"
]
};
},{}],128:[function(require,module,exports){
module["exports"] = [
"###-###-####",
"(###) ###-####",
"1-###-###-####",
"###.###.####",
"###-###-####",
"(###) ###-####",
"1-###-###-####",
"###.###.####",
"###-###-#### x###",
"(###) ###-#### x###",
"1-###-###-#### x###",
"###.###.#### x###",
"###-###-#### x####",
"(###) ###-#### x####",
"1-###-###-#### x####",
"###.###.#### x####",
"###-###-#### x#####",
"(###) ###-#### x#####",
"1-###-###-#### x#####",
"###.###.#### x#####"
];
},{}],129:[function(require,module,exports){
var phone_number = {};
module['exports'] = phone_number;
phone_number.formats = require("./formats");
},{"./formats":128}],130:[function(require,module,exports){
var system = {};
module['exports'] = system;
system.mimeTypes = require("./mimeTypes");
},{"./mimeTypes":131}],131:[function(require,module,exports){
/*
The MIT License (MIT)
Copyright (c) 2014 Jonathan Ong [email protected]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Definitions from mime-db v1.21.0
For updates check: https://github.com/jshttp/mime-db/blob/master/db.json
*/
module['exports'] = {
"application/1d-interleaved-parityfec": {
"source": "iana"
},
"application/3gpdash-qoe-report+xml": {
"source": "iana"
},
"application/3gpp-ims+xml": {
"source": "iana"
},
"application/a2l": {
"source": "iana"
},
"application/activemessage": {
"source": "iana"
},
"application/alto-costmap+json": {
"source": "iana",
"compressible": true
},
"application/alto-costmapfilter+json": {
"source": "iana",
"compressible": true
},
"application/alto-directory+json": {
"source": "iana",
"compressible": true
},
"application/alto-endpointcost+json": {
"source": "iana",
"compressible": true
},
"application/alto-endpointcostparams+json": {
"source": "iana",
"compressible": true
},
"application/alto-endpointprop+json": {
"source": "iana",
"compressible": true
},
"application/alto-endpointpropparams+json": {
"source": "iana",
"compressible": true
},
"application/alto-error+json": {
"source": "iana",
"compressible": true
},
"application/alto-networkmap+json": {
"source": "iana",
"compressible": true
},
"application/alto-networkmapfilter+json": {
"source": "iana",
"compressible": true
},
"application/aml": {
"source": "iana"
},
"application/andrew-inset": {
"source": "iana",
"extensions": ["ez"]
},
"application/applefile": {
"source": "iana"
},
"application/applixware": {
"source": "apache",
"extensions": ["aw"]
},
"application/atf": {
"source": "iana"
},
"application/atfx": {
"source": "iana"
},
"application/atom+xml": {
"source": "iana",
"compressible": true,
"extensions": ["atom"]
},
"application/atomcat+xml": {
"source": "iana",
"extensions": ["atomcat"]
},
"application/atomdeleted+xml": {
"source": "iana"
},
"application/atomicmail": {
"source": "iana"
},
"application/atomsvc+xml": {
"source": "iana",
"extensions": ["atomsvc"]
},
"application/atxml": {
"source": "iana"
},
"application/auth-policy+xml": {
"source": "iana"
},
"application/bacnet-xdd+zip": {
"source": "iana"
},
"application/batch-smtp": {
"source": "iana"
},
"application/bdoc": {
"compressible": false,
"extensions": ["bdoc"]
},
"application/beep+xml": {
"source": "iana"
},
"application/calendar+json": {
"source": "iana",
"compressible": true
},
"application/calendar+xml": {
"source": "iana"
},
"application/call-completion": {
"source": "iana"
},
"application/cals-1840": {
"source": "iana"
},
"application/cbor": {
"source": "iana"
},
"application/ccmp+xml": {
"source": "iana"
},
"application/ccxml+xml": {
"source": "iana",
"extensions": ["ccxml"]
},
"application/cdfx+xml": {
"source": "iana"
},
"application/cdmi-capability": {
"source": "iana",
"extensions": ["cdmia"]
},
"application/cdmi-container": {
"source": "iana",
"extensions": ["cdmic"]
},
"application/cdmi-domain": {
"source": "iana",
"extensions": ["cdmid"]
},
"application/cdmi-object": {
"source": "iana",
"extensions": ["cdmio"]
},
"application/cdmi-queue": {
"source": "iana",
"extensions": ["cdmiq"]
},
"application/cdni": {
"source": "iana"
},
"application/cea": {
"source": "iana"
},
"application/cea-2018+xml": {
"source": "iana"
},
"application/cellml+xml": {
"source": "iana"
},
"application/cfw": {
"source": "iana"
},
"application/cms": {
"source": "iana"
},
"application/cnrp+xml": {
"source": "iana"
},
"application/coap-group+json": {
"source": "iana",
"compressible": true
},
"application/commonground": {
"source": "iana"
},
"application/conference-info+xml": {
"source": "iana"
},
"application/cpl+xml": {
"source": "iana"
},
"application/csrattrs": {
"source": "iana"
},
"application/csta+xml": {
"source": "iana"
},
"application/cstadata+xml": {
"source": "iana"
},
"application/csvm+json": {
"source": "iana",
"compressible": true
},
"application/cu-seeme": {
"source": "apache",
"extensions": ["cu"]
},
"application/cybercash": {
"source": "iana"
},
"application/dart": {
"compressible": true
},
"application/dash+xml": {
"source": "iana",
"extensions": ["mdp"]
},
"application/dashdelta": {
"source": "iana"
},
"application/davmount+xml": {
"source": "iana",
"extensions": ["davmount"]
},
"application/dca-rft": {
"source": "iana"
},
"application/dcd": {
"source": "iana"
},
"application/dec-dx": {
"source": "iana"
},
"application/dialog-info+xml": {
"source": "iana"
},
"application/dicom": {
"source": "iana"
},
"application/dii": {
"source": "iana"
},
"application/dit": {
"source": "iana"
},
"application/dns": {
"source": "iana"
},
"application/docbook+xml": {
"source": "apache",
"extensions": ["dbk"]
},
"application/dskpp+xml": {
"source": "iana"
},
"application/dssc+der": {
"source": "iana",
"extensions": ["dssc"]
},
"application/dssc+xml": {
"source": "iana",
"extensions": ["xdssc"]
},
"application/dvcs": {
"source": "iana"
},
"application/ecmascript": {
"source": "iana",
"compressible": true,
"extensions": ["ecma"]
},
"application/edi-consent": {
"source": "iana"
},
"application/edi-x12": {
"source": "iana",
"compressible": false
},
"application/edifact": {
"source": "iana",
"compressible": false
},
"application/emergencycalldata.comment+xml": {
"source": "iana"
},
"application/emergencycalldata.deviceinfo+xml": {
"source": "iana"
},
"application/emergencycalldata.providerinfo+xml": {
"source": "iana"
},
"application/emergencycalldata.serviceinfo+xml": {
"source": "iana"
},
"application/emergencycalldata.subscriberinfo+xml": {
"source": "iana"
},
"application/emma+xml": {
"source": "iana",
"extensions": ["emma"]
},
"application/emotionml+xml": {
"source": "iana"
},
"application/encaprtp": {
"source": "iana"
},
"application/epp+xml": {
"source": "iana"
},
"application/epub+zip": {
"source": "iana",
"extensions": ["epub"]
},
"application/eshop": {
"source": "iana"
},
"application/exi": {
"source": "iana",
"extensions": ["exi"]
},
"application/fastinfoset": {
"source": "iana"
},
"application/fastsoap": {
"source": "iana"
},
"application/fdt+xml": {
"source": "iana"
},
"application/fits": {
"source": "iana"
},
"application/font-sfnt": {
"source": "iana"
},
"application/font-tdpfr": {
"source": "iana",
"extensions": ["pfr"]
},
"application/font-woff": {
"source": "iana",
"compressible": false,
"extensions": ["woff"]
},
"application/font-woff2": {
"compressible": false,
"extensions": ["woff2"]
},
"application/framework-attributes+xml": {
"source": "iana"
},
"application/gml+xml": {
"source": "apache",
"extensions": ["gml"]
},
"application/gpx+xml": {
"source": "apache",
"extensions": ["gpx"]
},
"application/gxf": {
"source": "apache",
"extensions": ["gxf"]
},
"application/gzip": {
"source": "iana",
"compressible": false
},
"application/h224": {
"source": "iana"
},
"application/held+xml": {
"source": "iana"
},
"application/http": {
"source": "iana"
},
"application/hyperstudio": {
"source": "iana",
"extensions": ["stk"]
},
"application/ibe-key-request+xml": {
"source": "iana"
},
"application/ibe-pkg-reply+xml": {
"source": "iana"
},
"application/ibe-pp-data": {
"source": "iana"
},
"application/iges": {
"source": "iana"
},
"application/im-iscomposing+xml": {
"source": "iana"
},
"application/index": {
"source": "iana"
},
"application/index.cmd": {
"source": "iana"
},
"application/index.obj": {
"source": "iana"
},
"application/index.response": {
"source": "iana"
},
"application/index.vnd": {
"source": "iana"
},
"application/inkml+xml": {
"source": "iana",
"extensions": ["ink","inkml"]
},
"application/iotp": {
"source": "iana"
},
"application/ipfix": {
"source": "iana",
"extensions": ["ipfix"]
},
"application/ipp": {
"source": "iana"
},
"application/isup": {
"source": "iana"
},
"application/its+xml": {
"source": "iana"
},
"application/java-archive": {
"source": "apache",
"compressible": false,
"extensions": ["jar","war","ear"]
},
"application/java-serialized-object": {
"source": "apache",
"compressible": false,
"extensions": ["ser"]
},
"application/java-vm": {
"source": "apache",
"compressible": false,
"extensions": ["class"]
},
"application/javascript": {
"source": "iana",
"charset": "UTF-8",
"compressible": true,
"extensions": ["js"]
},
"application/jose": {
"source": "iana"
},
"application/jose+json": {
"source": "iana",
"compressible": true
},
"application/jrd+json": {
"source": "iana",
"compressible": true
},
"application/json": {
"source": "iana",
"charset": "UTF-8",
"compressible": true,
"extensions": ["json","map"]
},
"application/json-patch+json": {
"source": "iana",
"compressible": true
},
"application/json-seq": {
"source": "iana"
},
"application/json5": {
"extensions": ["json5"]
},
"application/jsonml+json": {
"source": "apache",
"compressible": true,
"extensions": ["jsonml"]
},
"application/jwk+json": {
"source": "iana",
"compressible": true
},
"application/jwk-set+json": {
"source": "iana",
"compressible": true
},
"application/jwt": {
"source": "iana"
},
"application/kpml-request+xml": {
"source": "iana"
},
"application/kpml-response+xml": {
"source": "iana"
},
"application/ld+json": {
"source": "iana",
"compressible": true,
"extensions": ["jsonld"]
},
"application/link-format": {
"source": "iana"
},
"application/load-control+xml": {
"source": "iana"
},
"application/lost+xml": {
"source": "iana",
"extensions": ["lostxml"]
},
"application/lostsync+xml": {
"source": "iana"
},
"application/lxf": {
"source": "iana"
},
"application/mac-binhex40": {
"source": "iana",
"extensions": ["hqx"]
},
"application/mac-compactpro": {
"source": "apache",
"extensions": ["cpt"]
},
"application/macwriteii": {
"source": "iana"
},
"application/mads+xml": {
"source": "iana",
"extensions": ["mads"]
},
"application/manifest+json": {
"charset": "UTF-8",
"compressible": true,
"extensions": ["webmanifest"]
},
"application/marc": {
"source": "iana",
"extensions": ["mrc"]
},
"application/marcxml+xml": {
"source": "iana",
"extensions": ["mrcx"]
},
"application/mathematica": {
"source": "iana",
"extensions": ["ma","nb","mb"]
},
"application/mathml+xml": {
"source": "iana",
"extensions": ["mathml"]
},
"application/mathml-content+xml": {
"source": "iana"
},
"application/mathml-presentation+xml": {
"source": "iana"
},
"application/mbms-associated-procedure-description+xml": {
"source": "iana"
},
"application/mbms-deregister+xml": {
"source": "iana"
},
"application/mbms-envelope+xml": {
"source": "iana"
},
"application/mbms-msk+xml": {
"source": "iana"
},
"application/mbms-msk-response+xml": {
"source": "iana"
},
"application/mbms-protection-description+xml": {
"source": "iana"
},
"application/mbms-reception-report+xml": {
"source": "iana"
},
"application/mbms-register+xml": {
"source": "iana"
},
"application/mbms-register-response+xml": {
"source": "iana"
},
"application/mbms-schedule+xml": {
"source": "iana"
},
"application/mbms-user-service-description+xml": {
"source": "iana"
},
"application/mbox": {
"source": "iana",
"extensions": ["mbox"]
},
"application/media-policy-dataset+xml": {
"source": "iana"
},
"application/media_control+xml": {
"source": "iana"
},
"application/mediaservercontrol+xml": {
"source": "iana",
"extensions": ["mscml"]
},
"application/merge-patch+json": {
"source": "iana",
"compressible": true
},
"application/metalink+xml": {
"source": "apache",
"extensions": ["metalink"]
},
"application/metalink4+xml": {
"source": "iana",
"extensions": ["meta4"]
},
"application/mets+xml": {
"source": "iana",
"extensions": ["mets"]
},
"application/mf4": {
"source": "iana"
},
"application/mikey": {
"source": "iana"
},
"application/mods+xml": {
"source": "iana",
"extensions": ["mods"]
},
"application/moss-keys": {
"source": "iana"
},
"application/moss-signature": {
"source": "iana"
},
"application/mosskey-data": {
"source": "iana"
},
"application/mosskey-request": {
"source": "iana"
},
"application/mp21": {
"source": "iana",
"extensions": ["m21","mp21"]
},
"application/mp4": {
"source": "iana",
"extensions": ["mp4s","m4p"]
},
"application/mpeg4-generic": {
"source": "iana"
},
"application/mpeg4-iod": {
"source": "iana"
},
"application/mpeg4-iod-xmt": {
"source": "iana"
},
"application/mrb-consumer+xml": {
"source": "iana"
},
"application/mrb-publish+xml": {
"source": "iana"
},
"application/msc-ivr+xml": {
"source": "iana"
},
"application/msc-mixer+xml": {
"source": "iana"
},
"application/msword": {
"source": "iana",
"compressible": false,
"extensions": ["doc","dot"]
},
"application/mxf": {
"source": "iana",
"extensions": ["mxf"]
},
"application/nasdata": {
"source": "iana"
},
"application/news-checkgroups": {
"source": "iana"
},
"application/news-groupinfo": {
"source": "iana"
},
"application/news-transmission": {
"source": "iana"
},
"application/nlsml+xml": {
"source": "iana"
},
"application/nss": {
"source": "iana"
},
"application/ocsp-request": {
"source": "iana"
},
"application/ocsp-response": {
"source": "iana"
},
"application/octet-stream": {
"source": "iana",
"compressible": false,
"extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]
},
"application/oda": {
"source": "iana",
"extensions": ["oda"]
},
"application/odx": {
"source": "iana"
},
"application/oebps-package+xml": {
"source": "iana",
"extensions": ["opf"]
},
"application/ogg": {
"source": "iana",
"compressible": false,
"extensions": ["ogx"]
},
"application/omdoc+xml": {
"source": "apache",
"extensions": ["omdoc"]
},
"application/onenote": {
"source": "apache",
"extensions": ["onetoc","onetoc2","onetmp","onepkg"]
},
"application/oxps": {
"source": "iana",
"extensions": ["oxps"]
},
"application/p2p-overlay+xml": {
"source": "iana"
},
"application/parityfec": {
"source": "iana"
},
"application/patch-ops-error+xml": {
"source": "iana",
"extensions": ["xer"]
},
"application/pdf": {
"source": "iana",
"compressible": false,
"extensions": ["pdf"]
},
"application/pdx": {
"source": "iana"
},
"application/pgp-encrypted": {
"source": "iana",
"compressible": false,
"extensions": ["pgp"]
},
"application/pgp-keys": {
"source": "iana"
},
"application/pgp-signature": {
"source": "iana",
"extensions": ["asc","sig"]
},
"application/pics-rules": {
"source": "apache",
"extensions": ["prf"]
},
"application/pidf+xml": {
"source": "iana"
},
"application/pidf-diff+xml": {
"source": "iana"
},
"application/pkcs10": {
"source": "iana",
"extensions": ["p10"]
},
"application/pkcs12": {
"source": "iana"
},
"application/pkcs7-mime": {
"source": "iana",
"extensions": ["p7m","p7c"]
},
"application/pkcs7-signature": {
"source": "iana",
"extensions": ["p7s"]
},
"application/pkcs8": {
"source": "iana",
"extensions": ["p8"]
},
"application/pkix-attr-cert": {
"source": "iana",
"extensions": ["ac"]
},
"application/pkix-cert": {
"source": "iana",
"extensions": ["cer"]
},
"application/pkix-crl": {
"source": "iana",
"extensions": ["crl"]
},
"application/pkix-pkipath": {
"source": "iana",
"extensions": ["pkipath"]
},
"application/pkixcmp": {
"source": "iana",
"extensions": ["pki"]
},
"application/pls+xml": {
"source": "iana",
"extensions": ["pls"]
},
"application/poc-settings+xml": {
"source": "iana"
},
"application/postscript": {
"source": "iana",
"compressible": true,
"extensions": ["ai","eps","ps"]
},
"application/provenance+xml": {
"source": "iana"
},
"application/prs.alvestrand.titrax-sheet": {
"source": "iana"
},
"application/prs.cww": {
"source": "iana",
"extensions": ["cww"]
},
"application/prs.hpub+zip": {
"source": "iana"
},
"application/prs.nprend": {
"source": "iana"
},
"application/prs.plucker": {
"source": "iana"
},
"application/prs.rdf-xml-crypt": {
"source": "iana"
},
"application/prs.xsf+xml": {
"source": "iana"
},
"application/pskc+xml": {
"source": "iana",
"extensions": ["pskcxml"]
},
"application/qsig": {
"source": "iana"
},
"application/raptorfec": {
"source": "iana"
},
"application/rdap+json": {
"source": "iana",
"compressible": true
},
"application/rdf+xml": {
"source": "iana",
"compressible": true,
"extensions": ["rdf"]
},
"application/reginfo+xml": {
"source": "iana",
"extensions": ["rif"]
},
"application/relax-ng-compact-syntax": {
"source": "iana",
"extensions": ["rnc"]
},
"application/remote-printing": {
"source": "iana"
},
"application/reputon+json": {
"source": "iana",
"compressible": true
},
"application/resource-lists+xml": {
"source": "iana",
"extensions": ["rl"]
},
"application/resource-lists-diff+xml": {
"source": "iana",
"extensions": ["rld"]
},
"application/rfc+xml": {
"source": "iana"
},
"application/riscos": {
"source": "iana"
},
"application/rlmi+xml": {
"source": "iana"
},
"application/rls-services+xml": {
"source": "iana",
"extensions": ["rs"]
},
"application/rpki-ghostbusters": {
"source": "iana",
"extensions": ["gbr"]
},
"application/rpki-manifest": {
"source": "iana",
"extensions": ["mft"]
},
"application/rpki-roa": {
"source": "iana",
"extensions": ["roa"]
},
"application/rpki-updown": {
"source": "iana"
},
"application/rsd+xml": {
"source": "apache",
"extensions": ["rsd"]
},
"application/rss+xml": {
"source": "apache",
"compressible": true,
"extensions": ["rss"]
},
"application/rtf": {
"source": "iana",
"compressible": true,
"extensions": ["rtf"]
},
"application/rtploopback": {
"source": "iana"
},
"application/rtx": {
"source": "iana"
},
"application/samlassertion+xml": {
"source": "iana"
},
"application/samlmetadata+xml": {
"source": "iana"
},
"application/sbml+xml": {
"source": "iana",
"extensions": ["sbml"]
},
"application/scaip+xml": {
"source": "iana"
},
"application/scim+json": {
"source": "iana",
"compressible": true
},
"application/scvp-cv-request": {
"source": "iana",
"extensions": ["scq"]
},
"application/scvp-cv-response": {
"source": "iana",
"extensions": ["scs"]
},
"application/scvp-vp-request": {
"source": "iana",
"extensions": ["spq"]
},
"application/scvp-vp-response": {
"source": "iana",
"extensions": ["spp"]
},
"application/sdp": {
"source": "iana",
"extensions": ["sdp"]
},
"application/sep+xml": {
"source": "iana"
},
"application/sep-exi": {
"source": "iana"
},
"application/session-info": {
"source": "iana"
},
"application/set-payment": {
"source": "iana"
},
"application/set-payment-initiation": {
"source": "iana",
"extensions": ["setpay"]
},
"application/set-registration": {
"source": "iana"
},
"application/set-registration-initiation": {
"source": "iana",
"extensions": ["setreg"]
},
"application/sgml": {
"source": "iana"
},
"application/sgml-open-catalog": {
"source": "iana"
},
"application/shf+xml": {
"source": "iana",
"extensions": ["shf"]
},
"application/sieve": {
"source": "iana"
},
"application/simple-filter+xml": {
"source": "iana"
},
"application/simple-message-summary": {
"source": "iana"
},
"application/simplesymbolcontainer": {
"source": "iana"
},
"application/slate": {
"source": "iana"
},
"application/smil": {
"source": "iana"
},
"application/smil+xml": {
"source": "iana",
"extensions": ["smi","smil"]
},
"application/smpte336m": {
"source": "iana"
},
"application/soap+fastinfoset": {
"source": "iana"
},
"application/soap+xml": {
"source": "iana",
"compressible": true
},
"application/sparql-query": {
"source": "iana",
"extensions": ["rq"]
},
"application/sparql-results+xml": {
"source": "iana",
"extensions": ["srx"]
},
"application/spirits-event+xml": {
"source": "iana"
},
"application/sql": {
"source": "iana"
},
"application/srgs": {
"source": "iana",
"extensions": ["gram"]
},
"application/srgs+xml": {
"source": "iana",
"extensions": ["grxml"]
},
"application/sru+xml": {
"source": "iana",
"extensions": ["sru"]
},
"application/ssdl+xml": {
"source": "apache",
"extensions": ["ssdl"]
},
"application/ssml+xml": {
"source": "iana",
"extensions": ["ssml"]
},
"application/tamp-apex-update": {
"source": "iana"
},
"application/tamp-apex-update-confirm": {
"source": "iana"
},
"application/tamp-community-update": {
"source": "iana"
},
"application/tamp-community-update-confirm": {
"source": "iana"
},
"application/tamp-error": {
"source": "iana"
},
"application/tamp-sequence-adjust": {
"source": "iana"
},
"application/tamp-sequence-adjust-confirm": {
"source": "iana"
},
"application/tamp-status-query": {
"source": "iana"
},
"application/tamp-status-response": {
"source": "iana"
},
"application/tamp-update": {
"source": "iana"
},
"application/tamp-update-confirm": {
"source": "iana"
},
"application/tar": {
"compressible": true
},
"application/tei+xml": {
"source": "iana",
"extensions": ["tei","teicorpus"]
},
"application/thraud+xml": {
"source": "iana",
"extensions": ["tfi"]
},
"application/timestamp-query": {
"source": "iana"
},
"application/timestamp-reply": {
"source": "iana"
},
"application/timestamped-data": {
"source": "iana",
"extensions": ["tsd"]
},
"application/ttml+xml": {
"source": "iana"
},
"application/tve-trigger": {
"source": "iana"
},
"application/ulpfec": {
"source": "iana"
},
"application/urc-grpsheet+xml": {
"source": "iana"
},
"application/urc-ressheet+xml": {
"source": "iana"
},
"application/urc-targetdesc+xml": {
"source": "iana"
},
"application/urc-uisocketdesc+xml": {
"source": "iana"
},
"application/vcard+json": {
"source": "iana",
"compressible": true
},
"application/vcard+xml": {
"source": "iana"
},
"application/vemmi": {
"source": "iana"
},
"application/vividence.scriptfile": {
"source": "apache"
},
"application/vnd.3gpp-prose+xml": {
"source": "iana"
},
"application/vnd.3gpp-prose-pc3ch+xml": {
"source": "iana"
},
"application/vnd.3gpp.access-transfer-events+xml": {
"source": "iana"
},
"application/vnd.3gpp.bsf+xml": {
"source": "iana"
},
"application/vnd.3gpp.mid-call+xml": {
"source": "iana"
},
"application/vnd.3gpp.pic-bw-large": {
"source": "iana",
"extensions": ["plb"]
},
"application/vnd.3gpp.pic-bw-small": {
"source": "iana",
"extensions": ["psb"]
},
"application/vnd.3gpp.pic-bw-var": {
"source": "iana",
"extensions": ["pvb"]
},
"application/vnd.3gpp.sms": {
"source": "iana"
},
"application/vnd.3gpp.srvcc-ext+xml": {
"source": "iana"
},
"application/vnd.3gpp.srvcc-info+xml": {
"source": "iana"
},
"application/vnd.3gpp.state-and-event-info+xml": {
"source": "iana"
},
"application/vnd.3gpp.ussd+xml": {
"source": "iana"
},
"application/vnd.3gpp2.bcmcsinfo+xml": {
"source": "iana"
},
"application/vnd.3gpp2.sms": {
"source": "iana"
},
"application/vnd.3gpp2.tcap": {
"source": "iana",
"extensions": ["tcap"]
},
"application/vnd.3m.post-it-notes": {
"source": "iana",
"extensions": ["pwn"]
},
"application/vnd.accpac.simply.aso": {
"source": "iana",
"extensions": ["aso"]
},
"application/vnd.accpac.simply.imp": {
"source": "iana",
"extensions": ["imp"]
},
"application/vnd.acucobol": {
"source": "iana",
"extensions": ["acu"]
},
"application/vnd.acucorp": {
"source": "iana",
"extensions": ["atc","acutc"]
},
"application/vnd.adobe.air-application-installer-package+zip": {
"source": "apache",
"extensions": ["air"]
},
"application/vnd.adobe.flash.movie": {
"source": "iana"
},
"application/vnd.adobe.formscentral.fcdt": {
"source": "iana",
"extensions": ["fcdt"]
},
"application/vnd.adobe.fxp": {
"source": "iana",
"extensions": ["fxp","fxpl"]
},
"application/vnd.adobe.partial-upload": {
"source": "iana"
},
"application/vnd.adobe.xdp+xml": {
"source": "iana",
"extensions": ["xdp"]
},
"application/vnd.adobe.xfdf": {
"source": "iana",
"extensions": ["xfdf"]
},
"application/vnd.aether.imp": {
"source": "iana"
},
"application/vnd.ah-barcode": {
"source": "iana"
},
"application/vnd.ahead.space": {
"source": "iana",
"extensions": ["ahead"]
},
"application/vnd.airzip.filesecure.azf": {
"source": "iana",
"extensions": ["azf"]
},
"application/vnd.airzip.filesecure.azs": {
"source": "iana",
"extensions": ["azs"]
},
"application/vnd.amazon.ebook": {
"source": "apache",
"extensions": ["azw"]
},
"application/vnd.americandynamics.acc": {
"source": "iana",
"extensions": ["acc"]
},
"application/vnd.amiga.ami": {
"source": "iana",
"extensions": ["ami"]
},
"application/vnd.amundsen.maze+xml": {
"source": "iana"
},
"application/vnd.android.package-archive": {
"source": "apache",
"compressible": false,
"extensions": ["apk"]
},
"application/vnd.anki": {
"source": "iana"
},
"application/vnd.anser-web-certificate-issue-initiation": {
"source": "iana",
"extensions": ["cii"]
},
"application/vnd.anser-web-funds-transfer-initiation": {
"source": "apache",
"extensions": ["fti"]
},
"application/vnd.antix.game-component": {
"source": "iana",
"extensions": ["atx"]
},
"application/vnd.apache.thrift.binary": {
"source": "iana"
},
"application/vnd.apache.thrift.compact": {
"source": "iana"
},
"application/vnd.apache.thrift.json": {
"source": "iana"
},
"application/vnd.api+json": {
"source": "iana",
"compressible": true
},
"application/vnd.apple.installer+xml": {
"source": "iana",
"extensions": ["mpkg"]
},
"application/vnd.apple.mpegurl": {
"source": "iana",
"extensions": ["m3u8"]
},
"application/vnd.apple.pkpass": {
"compressible": false,
"extensions": ["pkpass"]
},
"application/vnd.arastra.swi": {
"source": "iana"
},
"application/vnd.aristanetworks.swi": {
"source": "iana",
"extensions": ["swi"]
},
"application/vnd.artsquare": {
"source": "iana"
},
"application/vnd.astraea-software.iota": {
"source": "iana",
"extensions": ["iota"]
},
"application/vnd.audiograph": {
"source": "iana",
"extensions": ["aep"]
},
"application/vnd.autopackage": {
"source": "iana"
},
"application/vnd.avistar+xml": {
"source": "iana"
},
"application/vnd.balsamiq.bmml+xml": {
"source": "iana"
},
"application/vnd.balsamiq.bmpr": {
"source": "iana"
},
"application/vnd.bekitzur-stech+json": {
"source": "iana",
"compressible": true
},
"application/vnd.biopax.rdf+xml": {
"source": "iana"
},
"application/vnd.blueice.multipass": {
"source": "iana",
"extensions": ["mpm"]
},
"application/vnd.bluetooth.ep.oob": {
"source": "iana"
},
"application/vnd.bluetooth.le.oob": {
"source": "iana"
},
"application/vnd.bmi": {
"source": "iana",
"extensions": ["bmi"]
},
"application/vnd.businessobjects": {
"source": "iana",
"extensions": ["rep"]
},
"application/vnd.cab-jscript": {
"source": "iana"
},
"application/vnd.canon-cpdl": {
"source": "iana"
},
"application/vnd.canon-lips": {
"source": "iana"
},
"application/vnd.cendio.thinlinc.clientconf": {
"source": "iana"
},
"application/vnd.century-systems.tcp_stream": {
"source": "iana"
},
"application/vnd.chemdraw+xml": {
"source": "iana",
"extensions": ["cdxml"]
},
"application/vnd.chipnuts.karaoke-mmd": {
"source": "iana",
"extensions": ["mmd"]
},
"application/vnd.cinderella": {
"source": "iana",
"extensions": ["cdy"]
},
"application/vnd.cirpack.isdn-ext": {
"source": "iana"
},
"application/vnd.citationstyles.style+xml": {
"source": "iana"
},
"application/vnd.claymore": {
"source": "iana",
"extensions": ["cla"]
},
"application/vnd.cloanto.rp9": {
"source": "iana",
"extensions": ["rp9"]
},
"application/vnd.clonk.c4group": {
"source": "iana",
"extensions": ["c4g","c4d","c4f","c4p","c4u"]
},
"application/vnd.cluetrust.cartomobile-config": {
"source": "iana",
"extensions": ["c11amc"]
},
"application/vnd.cluetrust.cartomobile-config-pkg": {
"source": "iana",
"extensions": ["c11amz"]
},
"application/vnd.coffeescript": {
"source": "iana"
},
"application/vnd.collection+json": {
"source": "iana",
"compressible": true
},
"application/vnd.collection.doc+json": {
"source": "iana",
"compressible": true
},
"application/vnd.collection.next+json": {
"source": "iana",
"compressible": true
},
"application/vnd.commerce-battelle": {
"source": "iana"
},
"application/vnd.commonspace": {
"source": "iana",
"extensions": ["csp"]
},
"application/vnd.contact.cmsg": {
"source": "iana",
"extensions": ["cdbcmsg"]
},
"application/vnd.cosmocaller": {
"source": "iana",
"extensions": ["cmc"]
},
"application/vnd.crick.clicker": {
"source": "iana",
"extensions": ["clkx"]
},
"application/vnd.crick.clicker.keyboard": {
"source": "iana",
"extensions": ["clkk"]
},
"application/vnd.crick.clicker.palette": {
"source": "iana",
"extensions": ["clkp"]
},
"application/vnd.crick.clicker.template": {
"source": "iana",
"extensions": ["clkt"]
},
"application/vnd.crick.clicker.wordbank": {
"source": "iana",
"extensions": ["clkw"]
},
"application/vnd.criticaltools.wbs+xml": {
"source": "iana",
"extensions": ["wbs"]
},
"application/vnd.ctc-posml": {
"source": "iana",
"extensions": ["pml"]
},
"application/vnd.ctct.ws+xml": {
"source": "iana"
},
"application/vnd.cups-pdf": {
"source": "iana"
},
"application/vnd.cups-postscript": {
"source": "iana"
},
"application/vnd.cups-ppd": {
"source": "iana",
"extensions": ["ppd"]
},
"application/vnd.cups-raster": {
"source": "iana"
},
"application/vnd.cups-raw": {
"source": "iana"
},
"application/vnd.curl": {
"source": "iana"
},
"application/vnd.curl.car": {
"source": "apache",
"extensions": ["car"]
},
"application/vnd.curl.pcurl": {
"source": "apache",
"extensions": ["pcurl"]
},
"application/vnd.cyan.dean.root+xml": {
"source": "iana"
},
"application/vnd.cybank": {
"source": "iana"
},
"application/vnd.dart": {
"source": "iana",
"compressible": true,
"extensions": ["dart"]
},
"application/vnd.data-vision.rdz": {
"source": "iana",
"extensions": ["rdz"]
},
"application/vnd.debian.binary-package": {
"source": "iana"
},
"application/vnd.dece.data": {
"source": "iana",
"extensions": ["uvf","uvvf","uvd","uvvd"]
},
"application/vnd.dece.ttml+xml": {
"source": "iana",
"extensions": ["uvt","uvvt"]
},
"application/vnd.dece.unspecified": {
"source": "iana",
"extensions": ["uvx","uvvx"]
},
"application/vnd.dece.zip": {
"source": "iana",
"extensions": ["uvz","uvvz"]
},
"application/vnd.denovo.fcselayout-link": {
"source": "iana",
"extensions": ["fe_launch"]
},
"application/vnd.desmume-movie": {
"source": "iana"
},
"application/vnd.dir-bi.plate-dl-nosuffix": {
"source": "iana"
},
"application/vnd.dm.delegation+xml": {
"source": "iana"
},
"application/vnd.dna": {
"source": "iana",
"extensions": ["dna"]
},
"application/vnd.document+json": {
"source": "iana",
"compressible": true
},
"application/vnd.dolby.mlp": {
"source": "apache",
"extensions": ["mlp"]
},
"application/vnd.dolby.mobile.1": {
"source": "iana"
},
"application/vnd.dolby.mobile.2": {
"source": "iana"
},
"application/vnd.doremir.scorecloud-binary-document": {
"source": "iana"
},
"application/vnd.dpgraph": {
"source": "iana",
"extensions": ["dpg"]
},
"application/vnd.dreamfactory": {
"source": "iana",
"extensions": ["dfac"]
},
"application/vnd.drive+json": {
"source": "iana",
"compressible": true
},
"application/vnd.ds-keypoint": {
"source": "apache",
"extensions": ["kpxx"]
},
"application/vnd.dtg.local": {
"source": "iana"
},
"application/vnd.dtg.local.flash": {
"source": "iana"
},
"application/vnd.dtg.local.html": {
"source": "iana"
},
"application/vnd.dvb.ait": {
"source": "iana",
"extensions": ["ait"]
},
"application/vnd.dvb.dvbj": {
"source": "iana"
},
"application/vnd.dvb.esgcontainer": {
"source": "iana"
},
"application/vnd.dvb.ipdcdftnotifaccess": {
"source": "iana"
},
"application/vnd.dvb.ipdcesgaccess": {
"source": "iana"
},
"application/vnd.dvb.ipdcesgaccess2": {
"source": "iana"
},
"application/vnd.dvb.ipdcesgpdd": {
"source": "iana"
},
"application/vnd.dvb.ipdcroaming": {
"source": "iana"
},
"application/vnd.dvb.iptv.alfec-base": {
"source": "iana"
},
"application/vnd.dvb.iptv.alfec-enhancement": {
"source": "iana"
},
"application/vnd.dvb.notif-aggregate-root+xml": {
"source": "iana"
},
"application/vnd.dvb.notif-container+xml": {
"source": "iana"
},
"application/vnd.dvb.notif-generic+xml": {
"source": "iana"
},
"application/vnd.dvb.notif-ia-msglist+xml": {
"source": "iana"
},
"application/vnd.dvb.notif-ia-registration-request+xml": {
"source": "iana"
},
"application/vnd.dvb.notif-ia-registration-response+xml": {
"source": "iana"
},
"application/vnd.dvb.notif-init+xml": {
"source": "iana"
},
"application/vnd.dvb.pfr": {
"source": "iana"
},
"application/vnd.dvb.service": {
"source": "iana",
"extensions": ["svc"]
},
"application/vnd.dxr": {
"source": "iana"
},
"application/vnd.dynageo": {
"source": "iana",
"extensions": ["geo"]
},
"application/vnd.dzr": {
"source": "iana"
},
"application/vnd.easykaraoke.cdgdownload": {
"source": "iana"
},
"application/vnd.ecdis-update": {
"source": "iana"
},
"application/vnd.ecowin.chart": {
"source": "iana",
"extensions": ["mag"]
},
"application/vnd.ecowin.filerequest": {
"source": "iana"
},
"application/vnd.ecowin.fileupdate": {
"source": "iana"
},
"application/vnd.ecowin.series": {
"source": "iana"
},
"application/vnd.ecowin.seriesrequest": {
"source": "iana"
},
"application/vnd.ecowin.seriesupdate": {
"source": "iana"
},
"application/vnd.emclient.accessrequest+xml": {
"source": "iana"
},
"application/vnd.enliven": {
"source": "iana",
"extensions": ["nml"]
},
"application/vnd.enphase.envoy": {
"source": "iana"
},
"application/vnd.eprints.data+xml": {
"source": "iana"
},
"application/vnd.epson.esf": {
"source": "iana",
"extensions": ["esf"]
},
"application/vnd.epson.msf": {
"source": "iana",
"extensions": ["msf"]
},
"application/vnd.epson.quickanime": {
"source": "iana",
"extensions": ["qam"]
},
"application/vnd.epson.salt": {
"source": "iana",
"extensions": ["slt"]
},
"application/vnd.epson.ssf": {
"source": "iana",
"extensions": ["ssf"]
},
"application/vnd.ericsson.quickcall": {
"source": "iana"
},
"application/vnd.eszigno3+xml": {
"source": "iana",
"extensions": ["es3","et3"]
},
"application/vnd.etsi.aoc+xml": {
"source": "iana"
},
"application/vnd.etsi.asic-e+zip": {
"source": "iana"
},
"application/vnd.etsi.asic-s+zip": {
"source": "iana"
},
"application/vnd.etsi.cug+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvcommand+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvdiscovery+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvprofile+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvsad-bc+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvsad-cod+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvsad-npvr+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvservice+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvsync+xml": {
"source": "iana"
},
"application/vnd.etsi.iptvueprofile+xml": {
"source": "iana"
},
"application/vnd.etsi.mcid+xml": {
"source": "iana"
},
"application/vnd.etsi.mheg5": {
"source": "iana"
},
"application/vnd.etsi.overload-control-policy-dataset+xml": {
"source": "iana"
},
"application/vnd.etsi.pstn+xml": {
"source": "iana"
},
"application/vnd.etsi.sci+xml": {
"source": "iana"
},
"application/vnd.etsi.simservs+xml": {
"source": "iana"
},
"application/vnd.etsi.timestamp-token": {
"source": "iana"
},
"application/vnd.etsi.tsl+xml": {
"source": "iana"
},
"application/vnd.etsi.tsl.der": {
"source": "iana"
},
"application/vnd.eudora.data": {
"source": "iana"
},
"application/vnd.ezpix-album": {
"source": "iana",
"extensions": ["ez2"]
},
"application/vnd.ezpix-package": {
"source": "iana",
"extensions": ["ez3"]
},
"application/vnd.f-secure.mobile": {
"source": "iana"
},
"application/vnd.fastcopy-disk-image": {
"source": "iana"
},
"application/vnd.fdf": {
"source": "iana",
"extensions": ["fdf"]
},
"application/vnd.fdsn.mseed": {
"source": "iana",
"extensions": ["mseed"]
},
"application/vnd.fdsn.seed": {
"source": "iana",
"extensions": ["seed","dataless"]
},
"application/vnd.ffsns": {
"source": "iana"
},
"application/vnd.filmit.zfc": {
"source": "iana"
},
"application/vnd.fints": {
"source": "iana"
},
"application/vnd.firemonkeys.cloudcell": {
"source": "iana"
},
"application/vnd.flographit": {
"source": "iana",
"extensions": ["gph"]
},
"application/vnd.fluxtime.clip": {
"source": "iana",
"extensions": ["ftc"]
},
"application/vnd.font-fontforge-sfd": {
"source": "iana"
},
"application/vnd.framemaker": {
"source": "iana",
"extensions": ["fm","frame","maker","book"]
},
"application/vnd.frogans.fnc": {
"source": "iana",
"extensions": ["fnc"]
},
"application/vnd.frogans.ltf": {
"source": "iana",
"extensions": ["ltf"]
},
"application/vnd.fsc.weblaunch": {
"source": "iana",
"extensions": ["fsc"]
},
"application/vnd.fujitsu.oasys": {
"source": "iana",
"extensions": ["oas"]
},
"application/vnd.fujitsu.oasys2": {
"source": "iana",
"extensions": ["oa2"]
},
"application/vnd.fujitsu.oasys3": {
"source": "iana",
"extensions": ["oa3"]
},
"application/vnd.fujitsu.oasysgp": {
"source": "iana",
"extensions": ["fg5"]
},
"application/vnd.fujitsu.oasysprs": {
"source": "iana",
"extensions": ["bh2"]
},
"application/vnd.fujixerox.art-ex": {
"source": "iana"
},
"application/vnd.fujixerox.art4": {
"source": "iana"
},
"application/vnd.fujixerox.ddd": {
"source": "iana",
"extensions": ["ddd"]
},
"application/vnd.fujixerox.docuworks": {
"source": "iana",
"extensions": ["xdw"]
},
"application/vnd.fujixerox.docuworks.binder": {
"source": "iana",
"extensions": ["xbd"]
},
"application/vnd.fujixerox.docuworks.container": {
"source": "iana"
},
"application/vnd.fujixerox.hbpl": {
"source": "iana"
},
"application/vnd.fut-misnet": {
"source": "iana"
},
"application/vnd.fuzzysheet": {
"source": "iana",
"extensions": ["fzs"]
},
"application/vnd.genomatix.tuxedo": {
"source": "iana",
"extensions": ["txd"]
},
"application/vnd.geo+json": {
"source": "iana",
"compressible": true
},
"application/vnd.geocube+xml": {
"source": "iana"
},
"application/vnd.geogebra.file": {
"source": "iana",
"extensions": ["ggb"]
},
"application/vnd.geogebra.tool": {
"source": "iana",
"extensions": ["ggt"]
},
"application/vnd.geometry-explorer": {
"source": "iana",
"extensions": ["gex","gre"]
},
"application/vnd.geonext": {
"source": "iana",
"extensions": ["gxt"]
},
"application/vnd.geoplan": {
"source": "iana",
"extensions": ["g2w"]
},
"application/vnd.geospace": {
"source": "iana",
"extensions": ["g3w"]
},
"application/vnd.gerber": {
"source": "iana"
},
"application/vnd.globalplatform.card-content-mgt": {
"source": "iana"
},
"application/vnd.globalplatform.card-content-mgt-response": {
"source": "iana"
},
"application/vnd.gmx": {
"source": "iana",
"extensions": ["gmx"]
},
"application/vnd.google-apps.document": {
"compressible": false,
"extensions": ["gdoc"]
},
"application/vnd.google-apps.presentation": {
"compressible": false,
"extensions": ["gslides"]
},
"application/vnd.google-apps.spreadsheet": {
"compressible": false,
"extensions": ["gsheet"]
},
"application/vnd.google-earth.kml+xml": {
"source": "iana",
"compressible": true,
"extensions": ["kml"]
},
"application/vnd.google-earth.kmz": {
"source": "iana",
"compressible": false,
"extensions": ["kmz"]
},
"application/vnd.gov.sk.e-form+xml": {
"source": "iana"
},
"application/vnd.gov.sk.e-form+zip": {
"source": "iana"
},
"application/vnd.gov.sk.xmldatacontainer+xml": {
"source": "iana"
},
"application/vnd.grafeq": {
"source": "iana",
"extensions": ["gqf","gqs"]
},
"application/vnd.gridmp": {
"source": "iana"
},
"application/vnd.groove-account": {
"source": "iana",
"extensions": ["gac"]
},
"application/vnd.groove-help": {
"source": "iana",
"extensions": ["ghf"]
},
"application/vnd.groove-identity-message": {
"source": "iana",
"extensions": ["gim"]
},
"application/vnd.groove-injector": {
"source": "iana",
"extensions": ["grv"]
},
"application/vnd.groove-tool-message": {
"source": "iana",
"extensions": ["gtm"]
},
"application/vnd.groove-tool-template": {
"source": "iana",
"extensions": ["tpl"]
},
"application/vnd.groove-vcard": {
"source": "iana",
"extensions": ["vcg"]
},
"application/vnd.hal+json": {
"source": "iana",
"compressible": true
},
"application/vnd.hal+xml": {
"source": "iana",
"extensions": ["hal"]
},
"application/vnd.handheld-entertainment+xml": {
"source": "iana",
"extensions": ["zmm"]
},
"application/vnd.hbci": {
"source": "iana",
"extensions": ["hbci"]
},
"application/vnd.hcl-bireports": {
"source": "iana"
},
"application/vnd.heroku+json": {
"source": "iana",
"compressible": true
},
"application/vnd.hhe.lesson-player": {
"source": "iana",
"extensions": ["les"]
},
"application/vnd.hp-hpgl": {
"source": "iana",
"extensions": ["hpgl"]
},
"application/vnd.hp-hpid": {
"source": "iana",
"extensions": ["hpid"]
},
"application/vnd.hp-hps": {
"source": "iana",
"extensions": ["hps"]
},
"application/vnd.hp-jlyt": {
"source": "iana",
"extensions": ["jlt"]
},
"application/vnd.hp-pcl": {
"source": "iana",
"extensions": ["pcl"]
},
"application/vnd.hp-pclxl": {
"source": "iana",
"extensions": ["pclxl"]
},
"application/vnd.httphone": {
"source": "iana"
},
"application/vnd.hydrostatix.sof-data": {
"source": "iana",
"extensions": ["sfd-hdstx"]
},
"application/vnd.hyperdrive+json": {
"source": "iana",
"compressible": true
},
"application/vnd.hzn-3d-crossword": {
"source": "iana"
},
"application/vnd.ibm.afplinedata": {
"source": "iana"
},
"application/vnd.ibm.electronic-media": {
"source": "iana"
},
"application/vnd.ibm.minipay": {
"source": "iana",
"extensions": ["mpy"]
},
"application/vnd.ibm.modcap": {
"source": "iana",
"extensions": ["afp","listafp","list3820"]
},
"application/vnd.ibm.rights-management": {
"source": "iana",
"extensions": ["irm"]
},
"application/vnd.ibm.secure-container": {
"source": "iana",
"extensions": ["sc"]
},
"application/vnd.iccprofile": {
"source": "iana",
"extensions": ["icc","icm"]
},
"application/vnd.ieee.1905": {
"source": "iana"
},
"application/vnd.igloader": {
"source": "iana",
"extensions": ["igl"]
},
"application/vnd.immervision-ivp": {
"source": "iana",
"extensions": ["ivp"]
},
"application/vnd.immervision-ivu": {
"source": "iana",
"extensions": ["ivu"]
},
"application/vnd.ims.imsccv1p1": {
"source": "iana"
},
"application/vnd.ims.imsccv1p2": {
"source": "iana"
},
"application/vnd.ims.imsccv1p3": {
"source": "iana"
},
"application/vnd.ims.lis.v2.result+json": {
"source": "iana",
"compressible": true
},
"application/vnd.ims.lti.v2.toolconsumerprofile+json": {
"source": "iana",
"compressible": true
},
"application/vnd.ims.lti.v2.toolproxy+json": {
"source": "iana",
"compressible": true
},
"application/vnd.ims.lti.v2.toolproxy.id+json": {
"source": "iana",
"compressible": true
},
"application/vnd.ims.lti.v2.toolsettings+json": {
"source": "iana",
"compressible": true
},
"application/vnd.ims.lti.v2.toolsettings.simple+json": {
"source": "iana",
"compressible": true
},
"application/vnd.informedcontrol.rms+xml": {
"source": "iana"
},
"application/vnd.informix-visionary": {
"source": "iana"
},
"application/vnd.infotech.project": {
"source": "iana"
},
"application/vnd.infotech.project+xml": {
"source": "iana"
},
"application/vnd.innopath.wamp.notification": {
"source": "iana"
},
"application/vnd.insors.igm": {
"source": "iana",
"extensions": ["igm"]
},
"application/vnd.intercon.formnet": {
"source": "iana",
"extensions": ["xpw","xpx"]
},
"application/vnd.intergeo": {
"source": "iana",
"extensions": ["i2g"]
},
"application/vnd.intertrust.digibox": {
"source": "iana"
},
"application/vnd.intertrust.nncp": {
"source": "iana"
},
"application/vnd.intu.qbo": {
"source": "iana",
"extensions": ["qbo"]
},
"application/vnd.intu.qfx": {
"source": "iana",
"extensions": ["qfx"]
},
"application/vnd.iptc.g2.catalogitem+xml": {
"source": "iana"
},
"application/vnd.iptc.g2.conceptitem+xml": {
"source": "iana"
},
"application/vnd.iptc.g2.knowledgeitem+xml": {
"source": "iana"
},
"application/vnd.iptc.g2.newsitem+xml": {
"source": "iana"
},
"application/vnd.iptc.g2.newsmessage+xml": {
"source": "iana"
},
"application/vnd.iptc.g2.packageitem+xml": {
"source": "iana"
},
"application/vnd.iptc.g2.planningitem+xml": {
"source": "iana"
},
"application/vnd.ipunplugged.rcprofile": {
"source": "iana",
"extensions": ["rcprofile"]
},
"application/vnd.irepository.package+xml": {
"source": "iana",
"extensions": ["irp"]
},
"application/vnd.is-xpr": {
"source": "iana",
"extensions": ["xpr"]
},
"application/vnd.isac.fcs": {
"source": "iana",
"extensions": ["fcs"]
},
"application/vnd.jam": {
"source": "iana",
"extensions": ["jam"]
},
"application/vnd.japannet-directory-service": {
"source": "iana"
},
"application/vnd.japannet-jpnstore-wakeup": {
"source": "iana"
},
"application/vnd.japannet-payment-wakeup": {
"source": "iana"
},
"application/vnd.japannet-registration": {
"source": "iana"
},
"application/vnd.japannet-registration-wakeup": {
"source": "iana"
},
"application/vnd.japannet-setstore-wakeup": {
"source": "iana"
},
"application/vnd.japannet-verification": {
"source": "iana"
},
"application/vnd.japannet-verification-wakeup": {
"source": "iana"
},
"application/vnd.jcp.javame.midlet-rms": {
"source": "iana",
"extensions": ["rms"]
},
"application/vnd.jisp": {
"source": "iana",
"extensions": ["jisp"]
},
"application/vnd.joost.joda-archive": {
"source": "iana",
"extensions": ["joda"]
},
"application/vnd.jsk.isdn-ngn": {
"source": "iana"
},
"application/vnd.kahootz": {
"source": "iana",
"extensions": ["ktz","ktr"]
},
"application/vnd.kde.karbon": {
"source": "iana",
"extensions": ["karbon"]
},
"application/vnd.kde.kchart": {
"source": "iana",
"extensions": ["chrt"]
},
"application/vnd.kde.kformula": {
"source": "iana",
"extensions": ["kfo"]
},
"application/vnd.kde.kivio": {
"source": "iana",
"extensions": ["flw"]
},
"application/vnd.kde.kontour": {
"source": "iana",
"extensions": ["kon"]
},
"application/vnd.kde.kpresenter": {
"source": "iana",
"extensions": ["kpr","kpt"]
},
"application/vnd.kde.kspread": {
"source": "iana",
"extensions": ["ksp"]
},
"application/vnd.kde.kword": {
"source": "iana",
"extensions": ["kwd","kwt"]
},
"application/vnd.kenameaapp": {
"source": "iana",
"extensions": ["htke"]
},
"application/vnd.kidspiration": {
"source": "iana",
"extensions": ["kia"]
},
"application/vnd.kinar": {
"source": "iana",
"extensions": ["kne","knp"]
},
"application/vnd.koan": {
"source": "iana",
"extensions": ["skp","skd","skt","skm"]
},
"application/vnd.kodak-descriptor": {
"source": "iana",
"extensions": ["sse"]
},
"application/vnd.las.las+xml": {
"source": "iana",
"extensions": ["lasxml"]
},
"application/vnd.liberty-request+xml": {
"source": "iana"
},
"application/vnd.llamagraphics.life-balance.desktop": {
"source": "iana",
"extensions": ["lbd"]
},
"application/vnd.llamagraphics.life-balance.exchange+xml": {
"source": "iana",
"extensions": ["lbe"]
},
"application/vnd.lotus-1-2-3": {
"source": "iana",
"extensions": ["123"]
},
"application/vnd.lotus-approach": {
"source": "iana",
"extensions": ["apr"]
},
"application/vnd.lotus-freelance": {
"source": "iana",
"extensions": ["pre"]
},
"application/vnd.lotus-notes": {
"source": "iana",
"extensions": ["nsf"]
},
"application/vnd.lotus-organizer": {
"source": "iana",
"extensions": ["org"]
},
"application/vnd.lotus-screencam": {
"source": "iana",
"extensions": ["scm"]
},
"application/vnd.lotus-wordpro": {
"source": "iana",
"extensions": ["lwp"]
},
"application/vnd.macports.portpkg": {
"source": "iana",
"extensions": ["portpkg"]
},
"application/vnd.mapbox-vector-tile": {
"source": "iana"
},
"application/vnd.marlin.drm.actiontoken+xml": {
"source": "iana"
},
"application/vnd.marlin.drm.conftoken+xml": {
"source": "iana"
},
"application/vnd.marlin.drm.license+xml": {
"source": "iana"
},
"application/vnd.marlin.drm.mdcf": {
"source": "iana"
},
"application/vnd.mason+json": {
"source": "iana",
"compressible": true
},
"application/vnd.maxmind.maxmind-db": {
"source": "iana"
},
"application/vnd.mcd": {
"source": "iana",
"extensions": ["mcd"]
},
"application/vnd.medcalcdata": {
"source": "iana",
"extensions": ["mc1"]
},
"application/vnd.mediastation.cdkey": {
"source": "iana",
"extensions": ["cdkey"]
},
"application/vnd.meridian-slingshot": {
"source": "iana"
},
"application/vnd.mfer": {
"source": "iana",
"extensions": ["mwf"]
},
"application/vnd.mfmp": {
"source": "iana",
"extensions": ["mfm"]
},
"application/vnd.micro+json": {
"source": "iana",
"compressible": true
},
"application/vnd.micrografx.flo": {
"source": "iana",
"extensions": ["flo"]
},
"application/vnd.micrografx.igx": {
"source": "iana",
"extensions": ["igx"]
},
"application/vnd.microsoft.portable-executable": {
"source": "iana"
},
"application/vnd.miele+json": {
"source": "iana",
"compressible": true
},
"application/vnd.mif": {
"source": "iana",
"extensions": ["mif"]
},
"application/vnd.minisoft-hp3000-save": {
"source": "iana"
},
"application/vnd.mitsubishi.misty-guard.trustweb": {
"source": "iana"
},
"application/vnd.mobius.daf": {
"source": "iana",
"extensions": ["daf"]
},
"application/vnd.mobius.dis": {
"source": "iana",
"extensions": ["dis"]
},
"application/vnd.mobius.mbk": {
"source": "iana",
"extensions": ["mbk"]
},
"application/vnd.mobius.mqy": {
"source": "iana",
"extensions": ["mqy"]
},
"application/vnd.mobius.msl": {
"source": "iana",
"extensions": ["msl"]
},
"application/vnd.mobius.plc": {
"source": "iana",
"extensions": ["plc"]
},
"application/vnd.mobius.txf": {
"source": "iana",
"extensions": ["txf"]
},
"application/vnd.mophun.application": {
"source": "iana",
"extensions": ["mpn"]
},
"application/vnd.mophun.certificate": {
"source": "iana",
"extensions": ["mpc"]
},
"application/vnd.motorola.flexsuite": {
"source": "iana"
},
"application/vnd.motorola.flexsuite.adsi": {
"source": "iana"
},
"application/vnd.motorola.flexsuite.fis": {
"source": "iana"
},
"application/vnd.motorola.flexsuite.gotap": {
"source": "iana"
},
"application/vnd.motorola.flexsuite.kmr": {
"source": "iana"
},
"application/vnd.motorola.flexsuite.ttc": {
"source": "iana"
},
"application/vnd.motorola.flexsuite.wem": {
"source": "iana"
},
"application/vnd.motorola.iprm": {
"source": "iana"
},
"application/vnd.mozilla.xul+xml": {
"source": "iana",
"compressible": true,
"extensions": ["xul"]
},
"application/vnd.ms-3mfdocument": {
"source": "iana"
},
"application/vnd.ms-artgalry": {
"source": "iana",
"extensions": ["cil"]
},
"application/vnd.ms-asf": {
"source": "iana"
},
"application/vnd.ms-cab-compressed": {
"source": "iana",
"extensions": ["cab"]
},
"application/vnd.ms-color.iccprofile": {
"source": "apache"
},
"application/vnd.ms-excel": {
"source": "iana",
"compressible": false,
"extensions": ["xls","xlm","xla","xlc","xlt","xlw"]
},
"application/vnd.ms-excel.addin.macroenabled.12": {
"source": "iana",
"extensions": ["xlam"]
},
"application/vnd.ms-excel.sheet.binary.macroenabled.12": {
"source": "iana",
"extensions": ["xlsb"]
},
"application/vnd.ms-excel.sheet.macroenabled.12": {
"source": "iana",
"extensions": ["xlsm"]
},
"application/vnd.ms-excel.template.macroenabled.12": {
"source": "iana",
"extensions": ["xltm"]
},
"application/vnd.ms-fontobject": {
"source": "iana",
"compressible": true,
"extensions": ["eot"]
},
"application/vnd.ms-htmlhelp": {
"source": "iana",
"extensions": ["chm"]
},
"application/vnd.ms-ims": {
"source": "iana",
"extensions": ["ims"]
},
"application/vnd.ms-lrm": {
"source": "iana",
"extensions": ["lrm"]
},
"application/vnd.ms-office.activex+xml": {
"source": "iana"
},
"application/vnd.ms-officetheme": {
"source": "iana",
"extensions": ["thmx"]
},
"application/vnd.ms-opentype": {
"source": "apache",
"compressible": true
},
"application/vnd.ms-package.obfuscated-opentype": {
"source": "apache"
},
"application/vnd.ms-pki.seccat": {
"source": "apache",
"extensions": ["cat"]
},
"application/vnd.ms-pki.stl": {
"source": "apache",
"extensions": ["stl"]
},
"application/vnd.ms-playready.initiator+xml": {
"source": "iana"
},
"application/vnd.ms-powerpoint": {
"source": "iana",
"compressible": false,
"extensions": ["ppt","pps","pot"]
},
"application/vnd.ms-powerpoint.addin.macroenabled.12": {
"source": "iana",
"extensions": ["ppam"]
},
"application/vnd.ms-powerpoint.presentation.macroenabled.12": {
"source": "iana",
"extensions": ["pptm"]
},
"application/vnd.ms-powerpoint.slide.macroenabled.12": {
"source": "iana",
"extensions": ["sldm"]
},
"application/vnd.ms-powerpoint.slideshow.macroenabled.12": {
"source": "iana",
"extensions": ["ppsm"]
},
"application/vnd.ms-powerpoint.template.macroenabled.12": {
"source": "iana",
"extensions": ["potm"]
},
"application/vnd.ms-printdevicecapabilities+xml": {
"source": "iana"
},
"application/vnd.ms-printing.printticket+xml": {
"source": "apache"
},
"application/vnd.ms-project": {
"source": "iana",
"extensions": ["mpp","mpt"]
},
"application/vnd.ms-tnef": {
"source": "iana"
},
"application/vnd.ms-windows.devicepairing": {
"source": "iana"
},
"application/vnd.ms-windows.nwprinting.oob": {
"source": "iana"
},
"application/vnd.ms-windows.printerpairing": {
"source": "iana"
},
"application/vnd.ms-windows.wsd.oob": {
"source": "iana"
},
"application/vnd.ms-wmdrm.lic-chlg-req": {
"source": "iana"
},
"application/vnd.ms-wmdrm.lic-resp": {
"source": "iana"
},
"application/vnd.ms-wmdrm.meter-chlg-req": {
"source": "iana"
},
"application/vnd.ms-wmdrm.meter-resp": {
"source": "iana"
},
"application/vnd.ms-word.document.macroenabled.12": {
"source": "iana",
"extensions": ["docm"]
},
"application/vnd.ms-word.template.macroenabled.12": {
"source": "iana",
"extensions": ["dotm"]
},
"application/vnd.ms-works": {
"source": "iana",
"extensions": ["wps","wks","wcm","wdb"]
},
"application/vnd.ms-wpl": {
"source": "iana",
"extensions": ["wpl"]
},
"application/vnd.ms-xpsdocument": {
"source": "iana",
"compressible": false,
"extensions": ["xps"]
},
"application/vnd.msa-disk-image": {
"source": "iana"
},
"application/vnd.mseq": {
"source": "iana",
"extensions": ["mseq"]
},
"application/vnd.msign": {
"source": "iana"
},
"application/vnd.multiad.creator": {
"source": "iana"
},
"application/vnd.multiad.creator.cif": {
"source": "iana"
},
"application/vnd.music-niff": {
"source": "iana"
},
"application/vnd.musician": {
"source": "iana",
"extensions": ["mus"]
},
"application/vnd.muvee.style": {
"source": "iana",
"extensions": ["msty"]
},
"application/vnd.mynfc": {
"source": "iana",
"extensions": ["taglet"]
},
"application/vnd.ncd.control": {
"source": "iana"
},
"application/vnd.ncd.reference": {
"source": "iana"
},
"application/vnd.nervana": {
"source": "iana"
},
"application/vnd.netfpx": {
"source": "iana"
},
"application/vnd.neurolanguage.nlu": {
"source": "iana",
"extensions": ["nlu"]
},
"application/vnd.nintendo.nitro.rom": {
"source": "iana"
},
"application/vnd.nintendo.snes.rom": {
"source": "iana"
},
"application/vnd.nitf": {
"source": "iana",
"extensions": ["ntf","nitf"]
},
"application/vnd.noblenet-directory": {
"source": "iana",
"extensions": ["nnd"]
},
"application/vnd.noblenet-sealer": {
"source": "iana",
"extensions": ["nns"]
},
"application/vnd.noblenet-web": {
"source": "iana",
"extensions": ["nnw"]
},
"application/vnd.nokia.catalogs": {
"source": "iana"
},
"application/vnd.nokia.conml+wbxml": {
"source": "iana"
},
"application/vnd.nokia.conml+xml": {
"source": "iana"
},
"application/vnd.nokia.iptv.config+xml": {
"source": "iana"
},
"application/vnd.nokia.isds-radio-presets": {
"source": "iana"
},
"application/vnd.nokia.landmark+wbxml": {
"source": "iana"
},
"application/vnd.nokia.landmark+xml": {
"source": "iana"
},
"application/vnd.nokia.landmarkcollection+xml": {
"source": "iana"
},
"application/vnd.nokia.n-gage.ac+xml": {
"source": "iana"
},
"application/vnd.nokia.n-gage.data": {
"source": "iana",
"extensions": ["ngdat"]
},
"application/vnd.nokia.n-gage.symbian.install": {
"source": "iana",
"extensions": ["n-gage"]
},
"application/vnd.nokia.ncd": {
"source": "iana"
},
"application/vnd.nokia.pcd+wbxml": {
"source": "iana"
},
"application/vnd.nokia.pcd+xml": {
"source": "iana"
},
"application/vnd.nokia.radio-preset": {
"source": "iana",
"extensions": ["rpst"]
},
"application/vnd.nokia.radio-presets": {
"source": "iana",
"extensions": ["rpss"]
},
"application/vnd.novadigm.edm": {
"source": "iana",
"extensions": ["edm"]
},
"application/vnd.novadigm.edx": {
"source": "iana",
"extensions": ["edx"]
},
"application/vnd.novadigm.ext": {
"source": "iana",
"extensions": ["ext"]
},
"application/vnd.ntt-local.content-share": {
"source": "iana"
},
"application/vnd.ntt-local.file-transfer": {
"source": "iana"
},
"application/vnd.ntt-local.ogw_remote-access": {
"source": "iana"
},
"application/vnd.ntt-local.sip-ta_remote": {
"source": "iana"
},
"application/vnd.ntt-local.sip-ta_tcp_stream": {
"source": "iana"
},
"application/vnd.oasis.opendocument.chart": {
"source": "iana",
"extensions": ["odc"]
},
"application/vnd.oasis.opendocument.chart-template": {
"source": "iana",
"extensions": ["otc"]
},
"application/vnd.oasis.opendocument.database": {
"source": "iana",
"extensions": ["odb"]
},
"application/vnd.oasis.opendocument.formula": {
"source": "iana",
"extensions": ["odf"]
},
"application/vnd.oasis.opendocument.formula-template": {
"source": "iana",
"extensions": ["odft"]
},
"application/vnd.oasis.opendocument.graphics": {
"source": "iana",
"compressible": false,
"extensions": ["odg"]
},
"application/vnd.oasis.opendocument.graphics-template": {
"source": "iana",
"extensions": ["otg"]
},
"application/vnd.oasis.opendocument.image": {
"source": "iana",
"extensions": ["odi"]
},
"application/vnd.oasis.opendocument.image-template": {
"source": "iana",
"extensions": ["oti"]
},
"application/vnd.oasis.opendocument.presentation": {
"source": "iana",
"compressible": false,
"extensions": ["odp"]
},
"application/vnd.oasis.opendocument.presentation-template": {
"source": "iana",
"extensions": ["otp"]
},
"application/vnd.oasis.opendocument.spreadsheet": {
"source": "iana",
"compressible": false,
"extensions": ["ods"]
},
"application/vnd.oasis.opendocument.spreadsheet-template": {
"source": "iana",
"extensions": ["ots"]
},
"application/vnd.oasis.opendocument.text": {
"source": "iana",
"compressible": false,
"extensions": ["odt"]
},
"application/vnd.oasis.opendocument.text-master": {
"source": "iana",
"extensions": ["odm"]
},
"application/vnd.oasis.opendocument.text-template": {
"source": "iana",
"extensions": ["ott"]
},
"application/vnd.oasis.opendocument.text-web": {
"source": "iana",
"extensions": ["oth"]
},
"application/vnd.obn": {
"source": "iana"
},
"application/vnd.oftn.l10n+json": {
"source": "iana",
"compressible": true
},
"application/vnd.oipf.contentaccessdownload+xml": {
"source": "iana"
},
"application/vnd.oipf.contentaccessstreaming+xml": {
"source": "iana"
},
"application/vnd.oipf.cspg-hexbinary": {
"source": "iana"
},
"application/vnd.oipf.dae.svg+xml": {
"source": "iana"
},
"application/vnd.oipf.dae.xhtml+xml": {
"source": "iana"
},
"application/vnd.oipf.mippvcontrolmessage+xml": {
"source": "iana"
},
"application/vnd.oipf.pae.gem": {
"source": "iana"
},
"application/vnd.oipf.spdiscovery+xml": {
"source": "iana"
},
"application/vnd.oipf.spdlist+xml": {
"source": "iana"
},
"application/vnd.oipf.ueprofile+xml": {
"source": "iana"
},
"application/vnd.oipf.userprofile+xml": {
"source": "iana"
},
"application/vnd.olpc-sugar": {
"source": "iana",
"extensions": ["xo"]
},
"application/vnd.oma-scws-config": {
"source": "iana"
},
"application/vnd.oma-scws-http-request": {
"source": "iana"
},
"application/vnd.oma-scws-http-response": {
"source": "iana"
},
"application/vnd.oma.bcast.associated-procedure-parameter+xml": {
"source": "iana"
},
"application/vnd.oma.bcast.drm-trigger+xml": {
"source": "iana"
},
"application/vnd.oma.bcast.imd+xml": {
"source": "iana"
},
"application/vnd.oma.bcast.ltkm": {
"source": "iana"
},
"application/vnd.oma.bcast.notification+xml": {
"source": "iana"
},
"application/vnd.oma.bcast.provisioningtrigger": {
"source": "iana"
},
"application/vnd.oma.bcast.sgboot": {
"source": "iana"
},
"application/vnd.oma.bcast.sgdd+xml": {
"source": "iana"
},
"application/vnd.oma.bcast.sgdu": {
"source": "iana"
},
"application/vnd.oma.bcast.simple-symbol-container": {
"source": "iana"
},
"application/vnd.oma.bcast.smartcard-trigger+xml": {
"source": "iana"
},
"application/vnd.oma.bcast.sprov+xml": {
"source": "iana"
},
"application/vnd.oma.bcast.stkm": {
"source": "iana"
},
"application/vnd.oma.cab-address-book+xml": {
"source": "iana"
},
"application/vnd.oma.cab-feature-handler+xml": {
"source": "iana"
},
"application/vnd.oma.cab-pcc+xml": {
"source": "iana"
},
"application/vnd.oma.cab-subs-invite+xml": {
"source": "iana"
},
"application/vnd.oma.cab-user-prefs+xml": {
"source": "iana"
},
"application/vnd.oma.dcd": {
"source": "iana"
},
"application/vnd.oma.dcdc": {
"source": "iana"
},
"application/vnd.oma.dd2+xml": {
"source": "iana",
"extensions": ["dd2"]
},
"application/vnd.oma.drm.risd+xml": {
"source": "iana"
},
"application/vnd.oma.group-usage-list+xml": {
"source": "iana"
},
"application/vnd.oma.pal+xml": {
"source": "iana"
},
"application/vnd.oma.poc.detailed-progress-report+xml": {
"source": "iana"
},
"application/vnd.oma.poc.final-report+xml": {
"source": "iana"
},
"application/vnd.oma.poc.groups+xml": {
"source": "iana"
},
"application/vnd.oma.poc.invocation-descriptor+xml": {
"source": "iana"
},
"application/vnd.oma.poc.optimized-progress-report+xml": {
"source": "iana"
},
"application/vnd.oma.push": {
"source": "iana"
},
"application/vnd.oma.scidm.messages+xml": {
"source": "iana"
},
"application/vnd.oma.xcap-directory+xml": {
"source": "iana"
},
"application/vnd.omads-email+xml": {
"source": "iana"
},
"application/vnd.omads-file+xml": {
"source": "iana"
},
"application/vnd.omads-folder+xml": {
"source": "iana"
},
"application/vnd.omaloc-supl-init": {
"source": "iana"
},
"application/vnd.openblox.game+xml": {
"source": "iana"
},
"application/vnd.openblox.game-binary": {
"source": "iana"
},
"application/vnd.openeye.oeb": {
"source": "iana"
},
"application/vnd.openofficeorg.extension": {
"source": "apache",
"extensions": ["oxt"]
},
"application/vnd.openxmlformats-officedocument.custom-properties+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.customxmlproperties+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.drawing+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.drawingml.chart+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.extended-properties+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml-template": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.comments+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.presentation": {
"source": "iana",
"compressible": false,
"extensions": ["pptx"]
},
"application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.slide": {
"source": "iana",
"extensions": ["sldx"]
},
"application/vnd.openxmlformats-officedocument.presentationml.slide+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.slideshow": {
"source": "iana",
"extensions": ["ppsx"]
},
"application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.tags+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.template": {
"source": "apache",
"extensions": ["potx"]
},
"application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml-template": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
"source": "iana",
"compressible": false,
"extensions": ["xlsx"]
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.template": {
"source": "apache",
"extensions": ["xltx"]
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.theme+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.themeoverride+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.vmldrawing": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml-template": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": {
"source": "iana",
"compressible": false,
"extensions": ["docx"]
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.template": {
"source": "apache",
"extensions": ["dotx"]
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-package.core-properties+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": {
"source": "iana"
},
"application/vnd.openxmlformats-package.relationships+xml": {
"source": "iana"
},
"application/vnd.oracle.resource+json": {
"source": "iana",
"compressible": true
},
"application/vnd.orange.indata": {
"source": "iana"
},
"application/vnd.osa.netdeploy": {
"source": "iana"
},
"application/vnd.osgeo.mapguide.package": {
"source": "iana",
"extensions": ["mgp"]
},
"application/vnd.osgi.bundle": {
"source": "iana"
},
"application/vnd.osgi.dp": {
"source": "iana",
"extensions": ["dp"]
},
"application/vnd.osgi.subsystem": {
"source": "iana",
"extensions": ["esa"]
},
"application/vnd.otps.ct-kip+xml": {
"source": "iana"
},
"application/vnd.oxli.countgraph": {
"source": "iana"
},
"application/vnd.pagerduty+json": {
"source": "iana",
"compressible": true
},
"application/vnd.palm": {
"source": "iana",
"extensions": ["pdb","pqa","oprc"]
},
"application/vnd.panoply": {
"source": "iana"
},
"application/vnd.paos+xml": {
"source": "iana"
},
"application/vnd.paos.xml": {
"source": "apache"
},
"application/vnd.pawaafile": {
"source": "iana",
"extensions": ["paw"]
},
"application/vnd.pcos": {
"source": "iana"
},
"application/vnd.pg.format": {
"source": "iana",
"extensions": ["str"]
},
"application/vnd.pg.osasli": {
"source": "iana",
"extensions": ["ei6"]
},
"application/vnd.piaccess.application-licence": {
"source": "iana"
},
"application/vnd.picsel": {
"source": "iana",
"extensions": ["efif"]
},
"application/vnd.pmi.widget": {
"source": "iana",
"extensions": ["wg"]
},
"application/vnd.poc.group-advertisement+xml": {
"source": "iana"
},
"application/vnd.pocketlearn": {
"source": "iana",
"extensions": ["plf"]
},
"application/vnd.powerbuilder6": {
"source": "iana",
"extensions": ["pbd"]
},
"application/vnd.powerbuilder6-s": {
"source": "iana"
},
"application/vnd.powerbuilder7": {
"source": "iana"
},
"application/vnd.powerbuilder7-s": {
"source": "iana"
},
"application/vnd.powerbuilder75": {
"source": "iana"
},
"application/vnd.powerbuilder75-s": {
"source": "iana"
},
"application/vnd.preminet": {
"source": "iana"
},
"application/vnd.previewsystems.box": {
"source": "iana",
"extensions": ["box"]
},
"application/vnd.proteus.magazine": {
"source": "iana",
"extensions": ["mgz"]
},
"application/vnd.publishare-delta-tree": {
"source": "iana",
"extensions": ["qps"]
},
"application/vnd.pvi.ptid1": {
"source": "iana",
"extensions": ["ptid"]
},
"application/vnd.pwg-multiplexed": {
"source": "iana"
},
"application/vnd.pwg-xhtml-print+xml": {
"source": "iana"
},
"application/vnd.qualcomm.brew-app-res": {
"source": "iana"
},
"application/vnd.quark.quarkxpress": {
"source": "iana",
"extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"]
},
"application/vnd.quobject-quoxdocument": {
"source": "iana"
},
"application/vnd.radisys.moml+xml": {
"source": "iana"
},
"application/vnd.radisys.msml+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-audit+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-audit-conf+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-audit-conn+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-audit-dialog+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-audit-stream+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-conf+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-dialog+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-dialog-base+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-dialog-fax-detect+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-dialog-fax-sendrecv+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-dialog-group+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-dialog-speech+xml": {
"source": "iana"
},
"application/vnd.radisys.msml-dialog-transform+xml": {
"source": "iana"
},
"application/vnd.rainstor.data": {
"source": "iana"
},
"application/vnd.rapid": {
"source": "iana"
},
"application/vnd.realvnc.bed": {
"source": "iana",
"extensions": ["bed"]
},
"application/vnd.recordare.musicxml": {
"source": "iana",
"extensions": ["mxl"]
},
"application/vnd.recordare.musicxml+xml": {
"source": "iana",
"extensions": ["musicxml"]
},
"application/vnd.renlearn.rlprint": {
"source": "iana"
},
"application/vnd.rig.cryptonote": {
"source": "iana",
"extensions": ["cryptonote"]
},
"application/vnd.rim.cod": {
"source": "apache",
"extensions": ["cod"]
},
"application/vnd.rn-realmedia": {
"source": "apache",
"extensions": ["rm"]
},
"application/vnd.rn-realmedia-vbr": {
"source": "apache",
"extensions": ["rmvb"]
},
"application/vnd.route66.link66+xml": {
"source": "iana",
"extensions": ["link66"]
},
"application/vnd.rs-274x": {
"source": "iana"
},
"application/vnd.ruckus.download": {
"source": "iana"
},
"application/vnd.s3sms": {
"source": "iana"
},
"application/vnd.sailingtracker.track": {
"source": "iana",
"extensions": ["st"]
},
"application/vnd.sbm.cid": {
"source": "iana"
},
"application/vnd.sbm.mid2": {
"source": "iana"
},
"application/vnd.scribus": {
"source": "iana"
},
"application/vnd.sealed.3df": {
"source": "iana"
},
"application/vnd.sealed.csf": {
"source": "iana"
},
"application/vnd.sealed.doc": {
"source": "iana"
},
"application/vnd.sealed.eml": {
"source": "iana"
},
"application/vnd.sealed.mht": {
"source": "iana"
},
"application/vnd.sealed.net": {
"source": "iana"
},
"application/vnd.sealed.ppt": {
"source": "iana"
},
"application/vnd.sealed.tiff": {
"source": "iana"
},
"application/vnd.sealed.xls": {
"source": "iana"
},
"application/vnd.sealedmedia.softseal.html": {
"source": "iana"
},
"application/vnd.sealedmedia.softseal.pdf": {
"source": "iana"
},
"application/vnd.seemail": {
"source": "iana",
"extensions": ["see"]
},
"application/vnd.sema": {
"source": "iana",
"extensions": ["sema"]
},
"application/vnd.semd": {
"source": "iana",
"extensions": ["semd"]
},
"application/vnd.semf": {
"source": "iana",
"extensions": ["semf"]
},
"application/vnd.shana.informed.formdata": {
"source": "iana",
"extensions": ["ifm"]
},
"application/vnd.shana.informed.formtemplate": {
"source": "iana",
"extensions": ["itp"]
},
"application/vnd.shana.informed.interchange": {
"source": "iana",
"extensions": ["iif"]
},
"application/vnd.shana.informed.package": {
"source": "iana",
"extensions": ["ipk"]
},
"application/vnd.simtech-mindmapper": {
"source": "iana",
"extensions": ["twd","twds"]
},
"application/vnd.siren+json": {
"source": "iana",
"compressible": true
},
"application/vnd.smaf": {
"source": "iana",
"extensions": ["mmf"]
},
"application/vnd.smart.notebook": {
"source": "iana"
},
"application/vnd.smart.teacher": {
"source": "iana",
"extensions": ["teacher"]
},
"application/vnd.software602.filler.form+xml": {
"source": "iana"
},
"application/vnd.software602.filler.form-xml-zip": {
"source": "iana"
},
"application/vnd.solent.sdkm+xml": {
"source": "iana",
"extensions": ["sdkm","sdkd"]
},
"application/vnd.spotfire.dxp": {
"source": "iana",
"extensions": ["dxp"]
},
"application/vnd.spotfire.sfs": {
"source": "iana",
"extensions": ["sfs"]
},
"application/vnd.sss-cod": {
"source": "iana"
},
"application/vnd.sss-dtf": {
"source": "iana"
},
"application/vnd.sss-ntf": {
"source": "iana"
},
"application/vnd.stardivision.calc": {
"source": "apache",
"extensions": ["sdc"]
},
"application/vnd.stardivision.draw": {
"source": "apache",
"extensions": ["sda"]
},
"application/vnd.stardivision.impress": {
"source": "apache",
"extensions": ["sdd"]
},
"application/vnd.stardivision.math": {
"source": "apache",
"extensions": ["smf"]
},
"application/vnd.stardivision.writer": {
"source": "apache",
"extensions": ["sdw","vor"]
},
"application/vnd.stardivision.writer-global": {
"source": "apache",
"extensions": ["sgl"]
},
"application/vnd.stepmania.package": {
"source": "iana",
"extensions": ["smzip"]
},
"application/vnd.stepmania.stepchart": {
"source": "iana",
"extensions": ["sm"]
},
"application/vnd.street-stream": {
"source": "iana"
},
"application/vnd.sun.wadl+xml": {
"source": "iana"
},
"application/vnd.sun.xml.calc": {
"source": "apache",
"extensions": ["sxc"]
},
"application/vnd.sun.xml.calc.template": {
"source": "apache",
"extensions": ["stc"]
},
"application/vnd.sun.xml.draw": {
"source": "apache",
"extensions": ["sxd"]
},
"application/vnd.sun.xml.draw.template": {
"source": "apache",
"extensions": ["std"]
},
"application/vnd.sun.xml.impress": {
"source": "apache",
"extensions": ["sxi"]
},
"application/vnd.sun.xml.impress.template": {
"source": "apache",
"extensions": ["sti"]
},
"application/vnd.sun.xml.math": {
"source": "apache",
"extensions": ["sxm"]
},
"application/vnd.sun.xml.writer": {
"source": "apache",
"extensions": ["sxw"]
},
"application/vnd.sun.xml.writer.global": {
"source": "apache",
"extensions": ["sxg"]
},
"application/vnd.sun.xml.writer.template": {
"source": "apache",
"extensions": ["stw"]
},
"application/vnd.sus-calendar": {
"source": "iana",
"extensions": ["sus","susp"]
},
"application/vnd.svd": {
"source": "iana",
"extensions": ["svd"]
},
"application/vnd.swiftview-ics": {
"source": "iana"
},
"application/vnd.symbian.install": {
"source": "apache",
"extensions": ["sis","sisx"]
},
"application/vnd.syncml+xml": {
"source": "iana",
"extensions": ["xsm"]
},
"application/vnd.syncml.dm+wbxml": {
"source": "iana",
"extensions": ["bdm"]
},
"application/vnd.syncml.dm+xml": {
"source": "iana",
"extensions": ["xdm"]
},
"application/vnd.syncml.dm.notification": {
"source": "iana"
},
"application/vnd.syncml.dmddf+wbxml": {
"source": "iana"
},
"application/vnd.syncml.dmddf+xml": {
"source": "iana"
},
"application/vnd.syncml.dmtnds+wbxml": {
"source": "iana"
},
"application/vnd.syncml.dmtnds+xml": {
"source": "iana"
},
"application/vnd.syncml.ds.notification": {
"source": "iana"
},
"application/vnd.tao.intent-module-archive": {
"source": "iana",
"extensions": ["tao"]
},
"application/vnd.tcpdump.pcap": {
"source": "iana",
"extensions": ["pcap","cap","dmp"]
},
"application/vnd.tmd.mediaflex.api+xml": {
"source": "iana"
},
"application/vnd.tml": {
"source": "iana"
},
"application/vnd.tmobile-livetv": {
"source": "iana",
"extensions": ["tmo"]
},
"application/vnd.trid.tpt": {
"source": "iana",
"extensions": ["tpt"]
},
"application/vnd.triscape.mxs": {
"source": "iana",
"extensions": ["mxs"]
},
"application/vnd.trueapp": {
"source": "iana",
"extensions": ["tra"]
},
"application/vnd.truedoc": {
"source": "iana"
},
"application/vnd.ubisoft.webplayer": {
"source": "iana"
},
"application/vnd.ufdl": {
"source": "iana",
"extensions": ["ufd","ufdl"]
},
"application/vnd.uiq.theme": {
"source": "iana",
"extensions": ["utz"]
},
"application/vnd.umajin": {
"source": "iana",
"extensions": ["umj"]
},
"application/vnd.unity": {
"source": "iana",
"extensions": ["unityweb"]
},
"application/vnd.uoml+xml": {
"source": "iana",
"extensions": ["uoml"]
},
"application/vnd.uplanet.alert": {
"source": "iana"
},
"application/vnd.uplanet.alert-wbxml": {
"source": "iana"
},
"application/vnd.uplanet.bearer-choice": {
"source": "iana"
},
"application/vnd.uplanet.bearer-choice-wbxml": {
"source": "iana"
},
"application/vnd.uplanet.cacheop": {
"source": "iana"
},
"application/vnd.uplanet.cacheop-wbxml": {
"source": "iana"
},
"application/vnd.uplanet.channel": {
"source": "iana"
},
"application/vnd.uplanet.channel-wbxml": {
"source": "iana"
},
"application/vnd.uplanet.list": {
"source": "iana"
},
"application/vnd.uplanet.list-wbxml": {
"source": "iana"
},
"application/vnd.uplanet.listcmd": {
"source": "iana"
},
"application/vnd.uplanet.listcmd-wbxml": {
"source": "iana"
},
"application/vnd.uplanet.signal": {
"source": "iana"
},
"application/vnd.uri-map": {
"source": "iana"
},
"application/vnd.valve.source.material": {
"source": "iana"
},
"application/vnd.vcx": {
"source": "iana",
"extensions": ["vcx"]
},
"application/vnd.vd-study": {
"source": "iana"
},
"application/vnd.vectorworks": {
"source": "iana"
},
"application/vnd.verimatrix.vcas": {
"source": "iana"
},
"application/vnd.vidsoft.vidconference": {
"source": "iana"
},
"application/vnd.visio": {
"source": "iana",
"extensions": ["vsd","vst","vss","vsw"]
},
"application/vnd.visionary": {
"source": "iana",
"extensions": ["vis"]
},
"application/vnd.vividence.scriptfile": {
"source": "iana"
},
"application/vnd.vsf": {
"source": "iana",
"extensions": ["vsf"]
},
"application/vnd.wap.sic": {
"source": "iana"
},
"application/vnd.wap.slc": {
"source": "iana"
},
"application/vnd.wap.wbxml": {
"source": "iana",
"extensions": ["wbxml"]
},
"application/vnd.wap.wmlc": {
"source": "iana",
"extensions": ["wmlc"]
},
"application/vnd.wap.wmlscriptc": {
"source": "iana",
"extensions": ["wmlsc"]
},
"application/vnd.webturbo": {
"source": "iana",
"extensions": ["wtb"]
},
"application/vnd.wfa.p2p": {
"source": "iana"
},
"application/vnd.wfa.wsc": {
"source": "iana"
},
"application/vnd.windows.devicepairing": {
"source": "iana"
},
"application/vnd.wmc": {
"source": "iana"
},
"application/vnd.wmf.bootstrap": {
"source": "iana"
},
"application/vnd.wolfram.mathematica": {
"source": "iana"
},
"application/vnd.wolfram.mathematica.package": {
"source": "iana"
},
"application/vnd.wolfram.player": {
"source": "iana",
"extensions": ["nbp"]
},
"application/vnd.wordperfect": {
"source": "iana",
"extensions": ["wpd"]
},
"application/vnd.wqd": {
"source": "iana",
"extensions": ["wqd"]
},
"application/vnd.wrq-hp3000-labelled": {
"source": "iana"
},
"application/vnd.wt.stf": {
"source": "iana",
"extensions": ["stf"]
},
"application/vnd.wv.csp+wbxml": {
"source": "iana"
},
"application/vnd.wv.csp+xml": {
"source": "iana"
},
"application/vnd.wv.ssp+xml": {
"source": "iana"
},
"application/vnd.xacml+json": {
"source": "iana",
"compressible": true
},
"application/vnd.xara": {
"source": "iana",
"extensions": ["xar"]
},
"application/vnd.xfdl": {
"source": "iana",
"extensions": ["xfdl"]
},
"application/vnd.xfdl.webform": {
"source": "iana"
},
"application/vnd.xmi+xml": {
"source": "iana"
},
"application/vnd.xmpie.cpkg": {
"source": "iana"
},
"application/vnd.xmpie.dpkg": {
"source": "iana"
},
"application/vnd.xmpie.plan": {
"source": "iana"
},
"application/vnd.xmpie.ppkg": {
"source": "iana"
},
"application/vnd.xmpie.xlim": {
"source": "iana"
},
"application/vnd.yamaha.hv-dic": {
"source": "iana",
"extensions": ["hvd"]
},
"application/vnd.yamaha.hv-script": {
"source": "iana",
"extensions": ["hvs"]
},
"application/vnd.yamaha.hv-voice": {
"source": "iana",
"extensions": ["hvp"]
},
"application/vnd.yamaha.openscoreformat": {
"source": "iana",
"extensions": ["osf"]
},
"application/vnd.yamaha.openscoreformat.osfpvg+xml": {
"source": "iana",
"extensions": ["osfpvg"]
},
"application/vnd.yamaha.remote-setup": {
"source": "iana"
},
"application/vnd.yamaha.smaf-audio": {
"source": "iana",
"extensions": ["saf"]
},
"application/vnd.yamaha.smaf-phrase": {
"source": "iana",
"extensions": ["spf"]
},
"application/vnd.yamaha.through-ngn": {
"source": "iana"
},
"application/vnd.yamaha.tunnel-udpencap": {
"source": "iana"
},
"application/vnd.yaoweme": {
"source": "iana"
},
"application/vnd.yellowriver-custom-menu": {
"source": "iana",
"extensions": ["cmp"]
},
"application/vnd.zul": {
"source": "iana",
"extensions": ["zir","zirz"]
},
"application/vnd.zzazz.deck+xml": {
"source": "iana",
"extensions": ["zaz"]
},
"application/voicexml+xml": {
"source": "iana",
"extensions": ["vxml"]
},
"application/vq-rtcpxr": {
"source": "iana"
},
"application/watcherinfo+xml": {
"source": "iana"
},
"application/whoispp-query": {
"source": "iana"
},
"application/whoispp-response": {
"source": "iana"
},
"application/widget": {
"source": "iana",
"extensions": ["wgt"]
},
"application/winhlp": {
"source": "apache",
"extensions": ["hlp"]
},
"application/wita": {
"source": "iana"
},
"application/wordperfect5.1": {
"source": "iana"
},
"application/wsdl+xml": {
"source": "iana",
"extensions": ["wsdl"]
},
"application/wspolicy+xml": {
"source": "iana",
"extensions": ["wspolicy"]
},
"application/x-7z-compressed": {
"source": "apache",
"compressible": false,
"extensions": ["7z"]
},
"application/x-abiword": {
"source": "apache",
"extensions": ["abw"]
},
"application/x-ace-compressed": {
"source": "apache",
"extensions": ["ace"]
},
"application/x-amf": {
"source": "apache"
},
"application/x-apple-diskimage": {
"source": "apache",
"extensions": ["dmg"]
},
"application/x-authorware-bin": {
"source": "apache",
"extensions": ["aab","x32","u32","vox"]
},
"application/x-authorware-map": {
"source": "apache",
"extensions": ["aam"]
},
"application/x-authorware-seg": {
"source": "apache",
"extensions": ["aas"]
},
"application/x-bcpio": {
"source": "apache",
"extensions": ["bcpio"]
},
"application/x-bdoc": {
"compressible": false,
"extensions": ["bdoc"]
},
"application/x-bittorrent": {
"source": "apache",
"extensions": ["torrent"]
},
"application/x-blorb": {
"source": "apache",
"extensions": ["blb","blorb"]
},
"application/x-bzip": {
"source": "apache",
"compressible": false,
"extensions": ["bz"]
},
"application/x-bzip2": {
"source": "apache",
"compressible": false,
"extensions": ["bz2","boz"]
},
"application/x-cbr": {
"source": "apache",
"extensions": ["cbr","cba","cbt","cbz","cb7"]
},
"application/x-cdlink": {
"source": "apache",
"extensions": ["vcd"]
},
"application/x-cfs-compressed": {
"source": "apache",
"extensions": ["cfs"]
},
"application/x-chat": {
"source": "apache",
"extensions": ["chat"]
},
"application/x-chess-pgn": {
"source": "apache",
"extensions": ["pgn"]
},
"application/x-chrome-extension": {
"extensions": ["crx"]
},
"application/x-cocoa": {
"source": "nginx",
"extensions": ["cco"]
},
"application/x-compress": {
"source": "apache"
},
"application/x-conference": {
"source": "apache",
"extensions": ["nsc"]
},
"application/x-cpio": {
"source": "apache",
"extensions": ["cpio"]
},
"application/x-csh": {
"source": "apache",
"extensions": ["csh"]
},
"application/x-deb": {
"compressible": false
},
"application/x-debian-package": {
"source": "apache",
"extensions": ["deb","udeb"]
},
"application/x-dgc-compressed": {
"source": "apache",
"extensions": ["dgc"]
},
"application/x-director": {
"source": "apache",
"extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]
},
"application/x-doom": {
"source": "apache",
"extensions": ["wad"]
},
"application/x-dtbncx+xml": {
"source": "apache",
"extensions": ["ncx"]
},
"application/x-dtbook+xml": {
"source": "apache",
"extensions": ["dtb"]
},
"application/x-dtbresource+xml": {
"source": "apache",
"extensions": ["res"]
},
"application/x-dvi": {
"source": "apache",
"compressible": false,
"extensions": ["dvi"]
},
"application/x-envoy": {
"source": "apache",
"extensions": ["evy"]
},
"application/x-eva": {
"source": "apache",
"extensions": ["eva"]
},
"application/x-font-bdf": {
"source": "apache",
"extensions": ["bdf"]
},
"application/x-font-dos": {
"source": "apache"
},
"application/x-font-framemaker": {
"source": "apache"
},
"application/x-font-ghostscript": {
"source": "apache",
"extensions": ["gsf"]
},
"application/x-font-libgrx": {
"source": "apache"
},
"application/x-font-linux-psf": {
"source": "apache",
"extensions": ["psf"]
},
"application/x-font-otf": {
"source": "apache",
"compressible": true,
"extensions": ["otf"]
},
"application/x-font-pcf": {
"source": "apache",
"extensions": ["pcf"]
},
"application/x-font-snf": {
"source": "apache",
"extensions": ["snf"]
},
"application/x-font-speedo": {
"source": "apache"
},
"application/x-font-sunos-news": {
"source": "apache"
},
"application/x-font-ttf": {
"source": "apache",
"compressible": true,
"extensions": ["ttf","ttc"]
},
"application/x-font-type1": {
"source": "apache",
"extensions": ["pfa","pfb","pfm","afm"]
},
"application/x-font-vfont": {
"source": "apache"
},
"application/x-freearc": {
"source": "apache",
"extensions": ["arc"]
},
"application/x-futuresplash": {
"source": "apache",
"extensions": ["spl"]
},
"application/x-gca-compressed": {
"source": "apache",
"extensions": ["gca"]
},
"application/x-glulx": {
"source": "apache",
"extensions": ["ulx"]
},
"application/x-gnumeric": {
"source": "apache",
"extensions": ["gnumeric"]
},
"application/x-gramps-xml": {
"source": "apache",
"extensions": ["gramps"]
},
"application/x-gtar": {
"source": "apache",
"extensions": ["gtar"]
},
"application/x-gzip": {
"source": "apache"
},
"application/x-hdf": {
"source": "apache",
"extensions": ["hdf"]
},
"application/x-httpd-php": {
"compressible": true,
"extensions": ["php"]
},
"application/x-install-instructions": {
"source": "apache",
"extensions": ["install"]
},
"application/x-iso9660-image": {
"source": "apache",
"extensions": ["iso"]
},
"application/x-java-archive-diff": {
"source": "nginx",
"extensions": ["jardiff"]
},
"application/x-java-jnlp-file": {
"source": "apache",
"compressible": false,
"extensions": ["jnlp"]
},
"application/x-javascript": {
"compressible": true
},
"application/x-latex": {
"source": "apache",
"compressible": false,
"extensions": ["latex"]
},
"application/x-lua-bytecode": {
"extensions": ["luac"]
},
"application/x-lzh-compressed": {
"source": "apache",
"extensions": ["lzh","lha"]
},
"application/x-makeself": {
"source": "nginx",
"extensions": ["run"]
},
"application/x-mie": {
"source": "apache",
"extensions": ["mie"]
},
"application/x-mobipocket-ebook": {
"source": "apache",
"extensions": ["prc","mobi"]
},
"application/x-mpegurl": {
"compressible": false
},
"application/x-ms-application": {
"source": "apache",
"extensions": ["application"]
},
"application/x-ms-shortcut": {
"source": "apache",
"extensions": ["lnk"]
},
"application/x-ms-wmd": {
"source": "apache",
"extensions": ["wmd"]
},
"application/x-ms-wmz": {
"source": "apache",
"extensions": ["wmz"]
},
"application/x-ms-xbap": {
"source": "apache",
"extensions": ["xbap"]
},
"application/x-msaccess": {
"source": "apache",
"extensions": ["mdb"]
},
"application/x-msbinder": {
"source": "apache",
"extensions": ["obd"]
},
"application/x-mscardfile": {
"source": "apache",
"extensions": ["crd"]
},
"application/x-msclip": {
"source": "apache",
"extensions": ["clp"]
},
"application/x-msdos-program": {
"extensions": ["exe"]
},
"application/x-msdownload": {
"source": "apache",
"extensions": ["exe","dll","com","bat","msi"]
},
"application/x-msmediaview": {
"source": "apache",
"extensions": ["mvb","m13","m14"]
},
"application/x-msmetafile": {
"source": "apache",
"extensions": ["wmf","wmz","emf","emz"]
},
"application/x-msmoney": {
"source": "apache",
"extensions": ["mny"]
},
"application/x-mspublisher": {
"source": "apache",
"extensions": ["pub"]
},
"application/x-msschedule": {
"source": "apache",
"extensions": ["scd"]
},
"application/x-msterminal": {
"source": "apache",
"extensions": ["trm"]
},
"application/x-mswrite": {
"source": "apache",
"extensions": ["wri"]
},
"application/x-netcdf": {
"source": "apache",
"extensions": ["nc","cdf"]
},
"application/x-ns-proxy-autoconfig": {
"compressible": true,
"extensions": ["pac"]
},
"application/x-nzb": {
"source": "apache",
"extensions": ["nzb"]
},
"application/x-perl": {
"source": "nginx",
"extensions": ["pl","pm"]
},
"application/x-pilot": {
"source": "nginx",
"extensions": ["prc","pdb"]
},
"application/x-pkcs12": {
"source": "apache",
"compressible": false,
"extensions": ["p12","pfx"]
},
"application/x-pkcs7-certificates": {
"source": "apache",
"extensions": ["p7b","spc"]
},
"application/x-pkcs7-certreqresp": {
"source": "apache",
"extensions": ["p7r"]
},
"application/x-rar-compressed": {
"source": "apache",
"compressible": false,
"extensions": ["rar"]
},
"application/x-redhat-package-manager": {
"source": "nginx",
"extensions": ["rpm"]
},
"application/x-research-info-systems": {
"source": "apache",
"extensions": ["ris"]
},
"application/x-sea": {
"source": "nginx",
"extensions": ["sea"]
},
"application/x-sh": {
"source": "apache",
"compressible": true,
"extensions": ["sh"]
},
"application/x-shar": {
"source": "apache",
"extensions": ["shar"]
},
"application/x-shockwave-flash": {
"source": "apache",
"compressible": false,
"extensions": ["swf"]
},
"application/x-silverlight-app": {
"source": "apache",
"extensions": ["xap"]
},
"application/x-sql": {
"source": "apache",
"extensions": ["sql"]
},
"application/x-stuffit": {
"source": "apache",
"compressible": false,
"extensions": ["sit"]
},
"application/x-stuffitx": {
"source": "apache",
"extensions": ["sitx"]
},
"application/x-subrip": {
"source": "apache",
"extensions": ["srt"]
},
"application/x-sv4cpio": {
"source": "apache",
"extensions": ["sv4cpio"]
},
"application/x-sv4crc": {
"source": "apache",
"extensions": ["sv4crc"]
},
"application/x-t3vm-image": {
"source": "apache",
"extensions": ["t3"]
},
"application/x-tads": {
"source": "apache",
"extensions": ["gam"]
},
"application/x-tar": {
"source": "apache",
"compressible": true,
"extensions": ["tar"]
},
"application/x-tcl": {
"source": "apache",
"extensions": ["tcl","tk"]
},
"application/x-tex": {
"source": "apache",
"extensions": ["tex"]
},
"application/x-tex-tfm": {
"source": "apache",
"extensions": ["tfm"]
},
"application/x-texinfo": {
"source": "apache",
"extensions": ["texinfo","texi"]
},
"application/x-tgif": {
"source": "apache",
"extensions": ["obj"]
},
"application/x-ustar": {
"source": "apache",
"extensions": ["ustar"]
},
"application/x-wais-source": {
"source": "apache",
"extensions": ["src"]
},
"application/x-web-app-manifest+json": {
"compressible": true,
"extensions": ["webapp"]
},
"application/x-www-form-urlencoded": {
"source": "iana",
"compressible": true
},
"application/x-x509-ca-cert": {
"source": "apache",
"extensions": ["der","crt","pem"]
},
"application/x-xfig": {
"source": "apache",
"extensions": ["fig"]
},
"application/x-xliff+xml": {
"source": "apache",
"extensions": ["xlf"]
},
"application/x-xpinstall": {
"source": "apache",
"compressible": false,
"extensions": ["xpi"]
},
"application/x-xz": {
"source": "apache",
"extensions": ["xz"]
},
"application/x-zmachine": {
"source": "apache",
"extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"]
},
"application/x400-bp": {
"source": "iana"
},
"application/xacml+xml": {
"source": "iana"
},
"application/xaml+xml": {
"source": "apache",
"extensions": ["xaml"]
},
"application/xcap-att+xml": {
"source": "iana"
},
"application/xcap-caps+xml": {
"source": "iana"
},
"application/xcap-diff+xml": {
"source": "iana",
"extensions": ["xdf"]
},
"application/xcap-el+xml": {
"source": "iana"
},
"application/xcap-error+xml": {
"source": "iana"
},
"application/xcap-ns+xml": {
"source": "iana"
},
"application/xcon-conference-info+xml": {
"source": "iana"
},
"application/xcon-conference-info-diff+xml": {
"source": "iana"
},
"application/xenc+xml": {
"source": "iana",
"extensions": ["xenc"]
},
"application/xhtml+xml": {
"source": "iana",
"compressible": true,
"extensions": ["xhtml","xht"]
},
"application/xhtml-voice+xml": {
"source": "apache"
},
"application/xml": {
"source": "iana",
"compressible": true,
"extensions": ["xml","xsl","xsd"]
},
"application/xml-dtd": {
"source": "iana",
"compressible": true,
"extensions": ["dtd"]
},
"application/xml-external-parsed-entity": {
"source": "iana"
},
"application/xml-patch+xml": {
"source": "iana"
},
"application/xmpp+xml": {
"source": "iana"
},
"application/xop+xml": {
"source": "iana",
"compressible": true,
"extensions": ["xop"]
},
"application/xproc+xml": {
"source": "apache",
"extensions": ["xpl"]
},
"application/xslt+xml": {
"source": "iana",
"extensions": ["xslt"]
},
"application/xspf+xml": {
"source": "apache",
"extensions": ["xspf"]
},
"application/xv+xml": {
"source": "iana",
"extensions": ["mxml","xhvml","xvml","xvm"]
},
"application/yang": {
"source": "iana",
"extensions": ["yang"]
},
"application/yin+xml": {
"source": "iana",
"extensions": ["yin"]
},
"application/zip": {
"source": "iana",
"compressible": false,
"extensions": ["zip"]
},
"application/zlib": {
"source": "iana"
},
"audio/1d-interleaved-parityfec": {
"source": "iana"
},
"audio/32kadpcm": {
"source": "iana"
},
"audio/3gpp": {
"source": "iana"
},
"audio/3gpp2": {
"source": "iana"
},
"audio/ac3": {
"source": "iana"
},
"audio/adpcm": {
"source": "apache",
"extensions": ["adp"]
},
"audio/amr": {
"source": "iana"
},
"audio/amr-wb": {
"source": "iana"
},
"audio/amr-wb+": {
"source": "iana"
},
"audio/aptx": {
"source": "iana"
},
"audio/asc": {
"source": "iana"
},
"audio/atrac-advanced-lossless": {
"source": "iana"
},
"audio/atrac-x": {
"source": "iana"
},
"audio/atrac3": {
"source": "iana"
},
"audio/basic": {
"source": "iana",
"compressible": false,
"extensions": ["au","snd"]
},
"audio/bv16": {
"source": "iana"
},
"audio/bv32": {
"source": "iana"
},
"audio/clearmode": {
"source": "iana"
},
"audio/cn": {
"source": "iana"
},
"audio/dat12": {
"source": "iana"
},
"audio/dls": {
"source": "iana"
},
"audio/dsr-es201108": {
"source": "iana"
},
"audio/dsr-es202050": {
"source": "iana"
},
"audio/dsr-es202211": {
"source": "iana"
},
"audio/dsr-es202212": {
"source": "iana"
},
"audio/dv": {
"source": "iana"
},
"audio/dvi4": {
"source": "iana"
},
"audio/eac3": {
"source": "iana"
},
"audio/encaprtp": {
"source": "iana"
},
"audio/evrc": {
"source": "iana"
},
"audio/evrc-qcp": {
"source": "iana"
},
"audio/evrc0": {
"source": "iana"
},
"audio/evrc1": {
"source": "iana"
},
"audio/evrcb": {
"source": "iana"
},
"audio/evrcb0": {
"source": "iana"
},
"audio/evrcb1": {
"source": "iana"
},
"audio/evrcnw": {
"source": "iana"
},
"audio/evrcnw0": {
"source": "iana"
},
"audio/evrcnw1": {
"source": "iana"
},
"audio/evrcwb": {
"source": "iana"
},
"audio/evrcwb0": {
"source": "iana"
},
"audio/evrcwb1": {
"source": "iana"
},
"audio/evs": {
"source": "iana"
},
"audio/fwdred": {
"source": "iana"
},
"audio/g711-0": {
"source": "iana"
},
"audio/g719": {
"source": "iana"
},
"audio/g722": {
"source": "iana"
},
"audio/g7221": {
"source": "iana"
},
"audio/g723": {
"source": "iana"
},
"audio/g726-16": {
"source": "iana"
},
"audio/g726-24": {
"source": "iana"
},
"audio/g726-32": {
"source": "iana"
},
"audio/g726-40": {
"source": "iana"
},
"audio/g728": {
"source": "iana"
},
"audio/g729": {
"source": "iana"
},
"audio/g7291": {
"source": "iana"
},
"audio/g729d": {
"source": "iana"
},
"audio/g729e": {
"source": "iana"
},
"audio/gsm": {
"source": "iana"
},
"audio/gsm-efr": {
"source": "iana"
},
"audio/gsm-hr-08": {
"source": "iana"
},
"audio/ilbc": {
"source": "iana"
},
"audio/ip-mr_v2.5": {
"source": "iana"
},
"audio/isac": {
"source": "apache"
},
"audio/l16": {
"source": "iana"
},
"audio/l20": {
"source": "iana"
},
"audio/l24": {
"source": "iana",
"compressible": false
},
"audio/l8": {
"source": "iana"
},
"audio/lpc": {
"source": "iana"
},
"audio/midi": {
"source": "apache",
"extensions": ["mid","midi","kar","rmi"]
},
"audio/mobile-xmf": {
"source": "iana"
},
"audio/mp4": {
"source": "iana",
"compressible": false,
"extensions": ["mp4a","m4a"]
},
"audio/mp4a-latm": {
"source": "iana"
},
"audio/mpa": {
"source": "iana"
},
"audio/mpa-robust": {
"source": "iana"
},
"audio/mpeg": {
"source": "iana",
"compressible": false,
"extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"]
},
"audio/mpeg4-generic": {
"source": "iana"
},
"audio/musepack": {
"source": "apache"
},
"audio/ogg": {
"source": "iana",
"compressible": false,
"extensions": ["oga","ogg","spx"]
},
"audio/opus": {
"source": "iana"
},
"audio/parityfec": {
"source": "iana"
},
"audio/pcma": {
"source": "iana"
},
"audio/pcma-wb": {
"source": "iana"
},
"audio/pcmu": {
"source": "iana"
},
"audio/pcmu-wb": {
"source": "iana"
},
"audio/prs.sid": {
"source": "iana"
},
"audio/qcelp": {
"source": "iana"
},
"audio/raptorfec": {
"source": "iana"
},
"audio/red": {
"source": "iana"
},
"audio/rtp-enc-aescm128": {
"source": "iana"
},
"audio/rtp-midi": {
"source": "iana"
},
"audio/rtploopback": {
"source": "iana"
},
"audio/rtx": {
"source": "iana"
},
"audio/s3m": {
"source": "apache",
"extensions": ["s3m"]
},
"audio/silk": {
"source": "apache",
"extensions": ["sil"]
},
"audio/smv": {
"source": "iana"
},
"audio/smv-qcp": {
"source": "iana"
},
"audio/smv0": {
"source": "iana"
},
"audio/sp-midi": {
"source": "iana"
},
"audio/speex": {
"source": "iana"
},
"audio/t140c": {
"source": "iana"
},
"audio/t38": {
"source": "iana"
},
"audio/telephone-event": {
"source": "iana"
},
"audio/tone": {
"source": "iana"
},
"audio/uemclip": {
"source": "iana"
},
"audio/ulpfec": {
"source": "iana"
},
"audio/vdvi": {
"source": "iana"
},
"audio/vmr-wb": {
"source": "iana"
},
"audio/vnd.3gpp.iufp": {
"source": "iana"
},
"audio/vnd.4sb": {
"source": "iana"
},
"audio/vnd.audiokoz": {
"source": "iana"
},
"audio/vnd.celp": {
"source": "iana"
},
"audio/vnd.cisco.nse": {
"source": "iana"
},
"audio/vnd.cmles.radio-events": {
"source": "iana"
},
"audio/vnd.cns.anp1": {
"source": "iana"
},
"audio/vnd.cns.inf1": {
"source": "iana"
},
"audio/vnd.dece.audio": {
"source": "iana",
"extensions": ["uva","uvva"]
},
"audio/vnd.digital-winds": {
"source": "iana",
"extensions": ["eol"]
},
"audio/vnd.dlna.adts": {
"source": "iana"
},
"audio/vnd.dolby.heaac.1": {
"source": "iana"
},
"audio/vnd.dolby.heaac.2": {
"source": "iana"
},
"audio/vnd.dolby.mlp": {
"source": "iana"
},
"audio/vnd.dolby.mps": {
"source": "iana"
},
"audio/vnd.dolby.pl2": {
"source": "iana"
},
"audio/vnd.dolby.pl2x": {
"source": "iana"
},
"audio/vnd.dolby.pl2z": {
"source": "iana"
},
"audio/vnd.dolby.pulse.1": {
"source": "iana"
},
"audio/vnd.dra": {
"source": "iana",
"extensions": ["dra"]
},
"audio/vnd.dts": {
"source": "iana",
"extensions": ["dts"]
},
"audio/vnd.dts.hd": {
"source": "iana",
"extensions": ["dtshd"]
},
"audio/vnd.dvb.file": {
"source": "iana"
},
"audio/vnd.everad.plj": {
"source": "iana"
},
"audio/vnd.hns.audio": {
"source": "iana"
},
"audio/vnd.lucent.voice": {
"source": "iana",
"extensions": ["lvp"]
},
"audio/vnd.ms-playready.media.pya": {
"source": "iana",
"extensions": ["pya"]
},
"audio/vnd.nokia.mobile-xmf": {
"source": "iana"
},
"audio/vnd.nortel.vbk": {
"source": "iana"
},
"audio/vnd.nuera.ecelp4800": {
"source": "iana",
"extensions": ["ecelp4800"]
},
"audio/vnd.nuera.ecelp7470": {
"source": "iana",
"extensions": ["ecelp7470"]
},
"audio/vnd.nuera.ecelp9600": {
"source": "iana",
"extensions": ["ecelp9600"]
},
"audio/vnd.octel.sbc": {
"source": "iana"
},
"audio/vnd.qcelp": {
"source": "iana"
},
"audio/vnd.rhetorex.32kadpcm": {
"source": "iana"
},
"audio/vnd.rip": {
"source": "iana",
"extensions": ["rip"]
},
"audio/vnd.rn-realaudio": {
"compressible": false
},
"audio/vnd.sealedmedia.softseal.mpeg": {
"source": "iana"
},
"audio/vnd.vmx.cvsd": {
"source": "iana"
},
"audio/vnd.wave": {
"compressible": false
},
"audio/vorbis": {
"source": "iana",
"compressible": false
},
"audio/vorbis-config": {
"source": "iana"
},
"audio/wav": {
"compressible": false,
"extensions": ["wav"]
},
"audio/wave": {
"compressible": false,
"extensions": ["wav"]
},
"audio/webm": {
"source": "apache",
"compressible": false,
"extensions": ["weba"]
},
"audio/x-aac": {
"source": "apache",
"compressible": false,
"extensions": ["aac"]
},
"audio/x-aiff": {
"source": "apache",
"extensions": ["aif","aiff","aifc"]
},
"audio/x-caf": {
"source": "apache",
"compressible": false,
"extensions": ["caf"]
},
"audio/x-flac": {
"source": "apache",
"extensions": ["flac"]
},
"audio/x-m4a": {
"source": "nginx",
"extensions": ["m4a"]
},
"audio/x-matroska": {
"source": "apache",
"extensions": ["mka"]
},
"audio/x-mpegurl": {
"source": "apache",
"extensions": ["m3u"]
},
"audio/x-ms-wax": {
"source": "apache",
"extensions": ["wax"]
},
"audio/x-ms-wma": {
"source": "apache",
"extensions": ["wma"]
},
"audio/x-pn-realaudio": {
"source": "apache",
"extensions": ["ram","ra"]
},
"audio/x-pn-realaudio-plugin": {
"source": "apache",
"extensions": ["rmp"]
},
"audio/x-realaudio": {
"source": "nginx",
"extensions": ["ra"]
},
"audio/x-tta": {
"source": "apache"
},
"audio/x-wav": {
"source": "apache",
"extensions": ["wav"]
},
"audio/xm": {
"source": "apache",
"extensions": ["xm"]
},
"chemical/x-cdx": {
"source": "apache",
"extensions": ["cdx"]
},
"chemical/x-cif": {
"source": "apache",
"extensions": ["cif"]
},
"chemical/x-cmdf": {
"source": "apache",
"extensions": ["cmdf"]
},
"chemical/x-cml": {
"source": "apache",
"extensions": ["cml"]
},
"chemical/x-csml": {
"source": "apache",
"extensions": ["csml"]
},
"chemical/x-pdb": {
"source": "apache"
},
"chemical/x-xyz": {
"source": "apache",
"extensions": ["xyz"]
},
"font/opentype": {
"compressible": true,
"extensions": ["otf"]
},
"image/bmp": {
"source": "apache",
"compressible": true,
"extensions": ["bmp"]
},
"image/cgm": {
"source": "iana",
"extensions": ["cgm"]
},
"image/fits": {
"source": "iana"
},
"image/g3fax": {
"source": "iana",
"extensions": ["g3"]
},
"image/gif": {
"source": "iana",
"compressible": false,
"extensions": ["gif"]
},
"image/ief": {
"source": "iana",
"extensions": ["ief"]
},
"image/jp2": {
"source": "iana"
},
"image/jpeg": {
"source": "iana",
"compressible": false,
"extensions": ["jpeg","jpg","jpe"]
},
"image/jpm": {
"source": "iana"
},
"image/jpx": {
"source": "iana"
},
"image/ktx": {
"source": "iana",
"extensions": ["ktx"]
},
"image/naplps": {
"source": "iana"
},
"image/pjpeg": {
"compressible": false
},
"image/png": {
"source": "iana",
"compressible": false,
"extensions": ["png"]
},
"image/prs.btif": {
"source": "iana",
"extensions": ["btif"]
},
"image/prs.pti": {
"source": "iana"
},
"image/pwg-raster": {
"source": "iana"
},
"image/sgi": {
"source": "apache",
"extensions": ["sgi"]
},
"image/svg+xml": {
"source": "iana",
"compressible": true,
"extensions": ["svg","svgz"]
},
"image/t38": {
"source": "iana"
},
"image/tiff": {
"source": "iana",
"compressible": false,
"extensions": ["tiff","tif"]
},
"image/tiff-fx": {
"source": "iana"
},
"image/vnd.adobe.photoshop": {
"source": "iana",
"compressible": true,
"extensions": ["psd"]
},
"image/vnd.airzip.accelerator.azv": {
"source": "iana"
},
"image/vnd.cns.inf2": {
"source": "iana"
},
"image/vnd.dece.graphic": {
"source": "iana",
"extensions": ["uvi","uvvi","uvg","uvvg"]
},
"image/vnd.djvu": {
"source": "iana",
"extensions": ["djvu","djv"]
},
"image/vnd.dvb.subtitle": {
"source": "iana",
"extensions": ["sub"]
},
"image/vnd.dwg": {
"source": "iana",
"extensions": ["dwg"]
},
"image/vnd.dxf": {
"source": "iana",
"extensions": ["dxf"]
},
"image/vnd.fastbidsheet": {
"source": "iana",
"extensions": ["fbs"]
},
"image/vnd.fpx": {
"source": "iana",
"extensions": ["fpx"]
},
"image/vnd.fst": {
"source": "iana",
"extensions": ["fst"]
},
"image/vnd.fujixerox.edmics-mmr": {
"source": "iana",
"extensions": ["mmr"]
},
"image/vnd.fujixerox.edmics-rlc": {
"source": "iana",
"extensions": ["rlc"]
},
"image/vnd.globalgraphics.pgb": {
"source": "iana"
},
"image/vnd.microsoft.icon": {
"source": "iana"
},
"image/vnd.mix": {
"source": "iana"
},
"image/vnd.mozilla.apng": {
"source": "iana"
},
"image/vnd.ms-modi": {
"source": "iana",
"extensions": ["mdi"]
},
"image/vnd.ms-photo": {
"source": "apache",
"extensions": ["wdp"]
},
"image/vnd.net-fpx": {
"source": "iana",
"extensions": ["npx"]
},
"image/vnd.radiance": {
"source": "iana"
},
"image/vnd.sealed.png": {
"source": "iana"
},
"image/vnd.sealedmedia.softseal.gif": {
"source": "iana"
},
"image/vnd.sealedmedia.softseal.jpg": {
"source": "iana"
},
"image/vnd.svf": {
"source": "iana"
},
"image/vnd.tencent.tap": {
"source": "iana"
},
"image/vnd.valve.source.texture": {
"source": "iana"
},
"image/vnd.wap.wbmp": {
"source": "iana",
"extensions": ["wbmp"]
},
"image/vnd.xiff": {
"source": "iana",
"extensions": ["xif"]
},
"image/vnd.zbrush.pcx": {
"source": "iana"
},
"image/webp": {
"source": "apache",
"extensions": ["webp"]
},
"image/x-3ds": {
"source": "apache",
"extensions": ["3ds"]
},
"image/x-cmu-raster": {
"source": "apache",
"extensions": ["ras"]
},
"image/x-cmx": {
"source": "apache",
"extensions": ["cmx"]
},
"image/x-freehand": {
"source": "apache",
"extensions": ["fh","fhc","fh4","fh5","fh7"]
},
"image/x-icon": {
"source": "apache",
"compressible": true,
"extensions": ["ico"]
},
"image/x-jng": {
"source": "nginx",
"extensions": ["jng"]
},
"image/x-mrsid-image": {
"source": "apache",
"extensions": ["sid"]
},
"image/x-ms-bmp": {
"source": "nginx",
"compressible": true,
"extensions": ["bmp"]
},
"image/x-pcx": {
"source": "apache",
"extensions": ["pcx"]
},
"image/x-pict": {
"source": "apache",
"extensions": ["pic","pct"]
},
"image/x-portable-anymap": {
"source": "apache",
"extensions": ["pnm"]
},
"image/x-portable-bitmap": {
"source": "apache",
"extensions": ["pbm"]
},
"image/x-portable-graymap": {
"source": "apache",
"extensions": ["pgm"]
},
"image/x-portable-pixmap": {
"source": "apache",
"extensions": ["ppm"]
},
"image/x-rgb": {
"source": "apache",
"extensions": ["rgb"]
},
"image/x-tga": {
"source": "apache",
"extensions": ["tga"]
},
"image/x-xbitmap": {
"source": "apache",
"extensions": ["xbm"]
},
"image/x-xcf": {
"compressible": false
},
"image/x-xpixmap": {
"source": "apache",
"extensions": ["xpm"]
},
"image/x-xwindowdump": {
"source": "apache",
"extensions": ["xwd"]
},
"message/cpim": {
"source": "iana"
},
"message/delivery-status": {
"source": "iana"
},
"message/disposition-notification": {
"source": "iana"
},
"message/external-body": {
"source": "iana"
},
"message/feedback-report": {
"source": "iana"
},
"message/global": {
"source": "iana"
},
"message/global-delivery-status": {
"source": "iana"
},
"message/global-disposition-notification": {
"source": "iana"
},
"message/global-headers": {
"source": "iana"
},
"message/http": {
"source": "iana",
"compressible": false
},
"message/imdn+xml": {
"source": "iana",
"compressible": true
},
"message/news": {
"source": "iana"
},
"message/partial": {
"source": "iana",
"compressible": false
},
"message/rfc822": {
"source": "iana",
"compressible": true,
"extensions": ["eml","mime"]
},
"message/s-http": {
"source": "iana"
},
"message/sip": {
"source": "iana"
},
"message/sipfrag": {
"source": "iana"
},
"message/tracking-status": {
"source": "iana"
},
"message/vnd.si.simp": {
"source": "iana"
},
"message/vnd.wfa.wsc": {
"source": "iana"
},
"model/iges": {
"source": "iana",
"compressible": false,
"extensions": ["igs","iges"]
},
"model/mesh": {
"source": "iana",
"compressible": false,
"extensions": ["msh","mesh","silo"]
},
"model/vnd.collada+xml": {
"source": "iana",
"extensions": ["dae"]
},
"model/vnd.dwf": {
"source": "iana",
"extensions": ["dwf"]
},
"model/vnd.flatland.3dml": {
"source": "iana"
},
"model/vnd.gdl": {
"source": "iana",
"extensions": ["gdl"]
},
"model/vnd.gs-gdl": {
"source": "apache"
},
"model/vnd.gs.gdl": {
"source": "iana"
},
"model/vnd.gtw": {
"source": "iana",
"extensions": ["gtw"]
},
"model/vnd.moml+xml": {
"source": "iana"
},
"model/vnd.mts": {
"source": "iana",
"extensions": ["mts"]
},
"model/vnd.opengex": {
"source": "iana"
},
"model/vnd.parasolid.transmit.binary": {
"source": "iana"
},
"model/vnd.parasolid.transmit.text": {
"source": "iana"
},
"model/vnd.valve.source.compiled-map": {
"source": "iana"
},
"model/vnd.vtu": {
"source": "iana",
"extensions": ["vtu"]
},
"model/vrml": {
"source": "iana",
"compressible": false,
"extensions": ["wrl","vrml"]
},
"model/x3d+binary": {
"source": "apache",
"compressible": false,
"extensions": ["x3db","x3dbz"]
},
"model/x3d+fastinfoset": {
"source": "iana"
},
"model/x3d+vrml": {
"source": "apache",
"compressible": false,
"extensions": ["x3dv","x3dvz"]
},
"model/x3d+xml": {
"source": "iana",
"compressible": true,
"extensions": ["x3d","x3dz"]
},
"model/x3d-vrml": {
"source": "iana"
},
"multipart/alternative": {
"source": "iana",
"compressible": false
},
"multipart/appledouble": {
"source": "iana"
},
"multipart/byteranges": {
"source": "iana"
},
"multipart/digest": {
"source": "iana"
},
"multipart/encrypted": {
"source": "iana",
"compressible": false
},
"multipart/form-data": {
"source": "iana",
"compressible": false
},
"multipart/header-set": {
"source": "iana"
},
"multipart/mixed": {
"source": "iana",
"compressible": false
},
"multipart/parallel": {
"source": "iana"
},
"multipart/related": {
"source": "iana",
"compressible": false
},
"multipart/report": {
"source": "iana"
},
"multipart/signed": {
"source": "iana",
"compressible": false
},
"multipart/voice-message": {
"source": "iana"
},
"multipart/x-mixed-replace": {
"source": "iana"
},
"text/1d-interleaved-parityfec": {
"source": "iana"
},
"text/cache-manifest": {
"source": "iana",
"compressible": true,
"extensions": ["appcache","manifest"]
},
"text/calendar": {
"source": "iana",
"extensions": ["ics","ifb"]
},
"text/calender": {
"compressible": true
},
"text/cmd": {
"compressible": true
},
"text/coffeescript": {
"extensions": ["coffee","litcoffee"]
},
"text/css": {
"source": "iana",
"compressible": true,
"extensions": ["css"]
},
"text/csv": {
"source": "iana",
"compressible": true,
"extensions": ["csv"]
},
"text/csv-schema": {
"source": "iana"
},
"text/directory": {
"source": "iana"
},
"text/dns": {
"source": "iana"
},
"text/ecmascript": {
"source": "iana"
},
"text/encaprtp": {
"source": "iana"
},
"text/enriched": {
"source": "iana"
},
"text/fwdred": {
"source": "iana"
},
"text/grammar-ref-list": {
"source": "iana"
},
"text/hjson": {
"extensions": ["hjson"]
},
"text/html": {
"source": "iana",
"compressible": true,
"extensions": ["html","htm","shtml"]
},
"text/jade": {
"extensions": ["jade"]
},
"text/javascript": {
"source": "iana",
"compressible": true
},
"text/jcr-cnd": {
"source": "iana"
},
"text/jsx": {
"compressible": true,
"extensions": ["jsx"]
},
"text/less": {
"extensions": ["less"]
},
"text/markdown": {
"source": "iana"
},
"text/mathml": {
"source": "nginx",
"extensions": ["mml"]
},
"text/mizar": {
"source": "iana"
},
"text/n3": {
"source": "iana",
"compressible": true,
"extensions": ["n3"]
},
"text/parameters": {
"source": "iana"
},
"text/parityfec": {
"source": "iana"
},
"text/plain": {
"source": "iana",
"compressible": true,
"extensions": ["txt","text","conf","def","list","log","in","ini"]
},
"text/provenance-notation": {
"source": "iana"
},
"text/prs.fallenstein.rst": {
"source": "iana"
},
"text/prs.lines.tag": {
"source": "iana",
"extensions": ["dsc"]
},
"text/raptorfec": {
"source": "iana"
},
"text/red": {
"source": "iana"
},
"text/rfc822-headers": {
"source": "iana"
},
"text/richtext": {
"source": "iana",
"compressible": true,
"extensions": ["rtx"]
},
"text/rtf": {
"source": "iana",
"compressible": true,
"extensions": ["rtf"]
},
"text/rtp-enc-aescm128": {
"source": "iana"
},
"text/rtploopback": {
"source": "iana"
},
"text/rtx": {
"source": "iana"
},
"text/sgml": {
"source": "iana",
"extensions": ["sgml","sgm"]
},
"text/stylus": {
"extensions": ["stylus","styl"]
},
"text/t140": {
"source": "iana"
},
"text/tab-separated-values": {
"source": "iana",
"compressible": true,
"extensions": ["tsv"]
},
"text/troff": {
"source": "iana",
"extensions": ["t","tr","roff","man","me","ms"]
},
"text/turtle": {
"source": "iana",
"extensions": ["ttl"]
},
"text/ulpfec": {
"source": "iana"
},
"text/uri-list": {
"source": "iana",
"compressible": true,
"extensions": ["uri","uris","urls"]
},
"text/vcard": {
"source": "iana",
"compressible": true,
"extensions": ["vcard"]
},
"text/vnd.a": {
"source": "iana"
},
"text/vnd.abc": {
"source": "iana"
},
"text/vnd.curl": {
"source": "iana",
"extensions": ["curl"]
},
"text/vnd.curl.dcurl": {
"source": "apache",
"extensions": ["dcurl"]
},
"text/vnd.curl.mcurl": {
"source": "apache",
"extensions": ["mcurl"]
},
"text/vnd.curl.scurl": {
"source": "apache",
"extensions": ["scurl"]
},
"text/vnd.debian.copyright": {
"source": "iana"
},
"text/vnd.dmclientscript": {
"source": "iana"
},
"text/vnd.dvb.subtitle": {
"source": "iana",
"extensions": ["sub"]
},
"text/vnd.esmertec.theme-descriptor": {
"source": "iana"
},
"text/vnd.fly": {
"source": "iana",
"extensions": ["fly"]
},
"text/vnd.fmi.flexstor": {
"source": "iana",
"extensions": ["flx"]
},
"text/vnd.graphviz": {
"source": "iana",
"extensions": ["gv"]
},
"text/vnd.in3d.3dml": {
"source": "iana",
"extensions": ["3dml"]
},
"text/vnd.in3d.spot": {
"source": "iana",
"extensions": ["spot"]
},
"text/vnd.iptc.newsml": {
"source": "iana"
},
"text/vnd.iptc.nitf": {
"source": "iana"
},
"text/vnd.latex-z": {
"source": "iana"
},
"text/vnd.motorola.reflex": {
"source": "iana"
},
"text/vnd.ms-mediapackage": {
"source": "iana"
},
"text/vnd.net2phone.commcenter.command": {
"source": "iana"
},
"text/vnd.radisys.msml-basic-layout": {
"source": "iana"
},
"text/vnd.si.uricatalogue": {
"source": "iana"
},
"text/vnd.sun.j2me.app-descriptor": {
"source": "iana",
"extensions": ["jad"]
},
"text/vnd.trolltech.linguist": {
"source": "iana"
},
"text/vnd.wap.si": {
"source": "iana"
},
"text/vnd.wap.sl": {
"source": "iana"
},
"text/vnd.wap.wml": {
"source": "iana",
"extensions": ["wml"]
},
"text/vnd.wap.wmlscript": {
"source": "iana",
"extensions": ["wmls"]
},
"text/vtt": {
"charset": "UTF-8",
"compressible": true,
"extensions": ["vtt"]
},
"text/x-asm": {
"source": "apache",
"extensions": ["s","asm"]
},
"text/x-c": {
"source": "apache",
"extensions": ["c","cc","cxx","cpp","h","hh","dic"]
},
"text/x-component": {
"source": "nginx",
"extensions": ["htc"]
},
"text/x-fortran": {
"source": "apache",
"extensions": ["f","for","f77","f90"]
},
"text/x-gwt-rpc": {
"compressible": true
},
"text/x-handlebars-template": {
"extensions": ["hbs"]
},
"text/x-java-source": {
"source": "apache",
"extensions": ["java"]
},
"text/x-jquery-tmpl": {
"compressible": true
},
"text/x-lua": {
"extensions": ["lua"]
},
"text/x-markdown": {
"compressible": true,
"extensions": ["markdown","md","mkd"]
},
"text/x-nfo": {
"source": "apache",
"extensions": ["nfo"]
},
"text/x-opml": {
"source": "apache",
"extensions": ["opml"]
},
"text/x-pascal": {
"source": "apache",
"extensions": ["p","pas"]
},
"text/x-processing": {
"compressible": true,
"extensions": ["pde"]
},
"text/x-sass": {
"extensions": ["sass"]
},
"text/x-scss": {
"extensions": ["scss"]
},
"text/x-setext": {
"source": "apache",
"extensions": ["etx"]
},
"text/x-sfv": {
"source": "apache",
"extensions": ["sfv"]
},
"text/x-suse-ymp": {
"compressible": true,
"extensions": ["ymp"]
},
"text/x-uuencode": {
"source": "apache",
"extensions": ["uu"]
},
"text/x-vcalendar": {
"source": "apache",
"extensions": ["vcs"]
},
"text/x-vcard": {
"source": "apache",
"extensions": ["vcf"]
},
"text/xml": {
"source": "iana",
"compressible": true,
"extensions": ["xml"]
},
"text/xml-external-parsed-entity": {
"source": "iana"
},
"text/yaml": {
"extensions": ["yaml","yml"]
},
"video/1d-interleaved-parityfec": {
"source": "apache"
},
"video/3gpp": {
"source": "apache",
"extensions": ["3gp","3gpp"]
},
"video/3gpp-tt": {
"source": "apache"
},
"video/3gpp2": {
"source": "apache",
"extensions": ["3g2"]
},
"video/bmpeg": {
"source": "apache"
},
"video/bt656": {
"source": "apache"
},
"video/celb": {
"source": "apache"
},
"video/dv": {
"source": "apache"
},
"video/h261": {
"source": "apache",
"extensions": ["h261"]
},
"video/h263": {
"source": "apache",
"extensions": ["h263"]
},
"video/h263-1998": {
"source": "apache"
},
"video/h263-2000": {
"source": "apache"
},
"video/h264": {
"source": "apache",
"extensions": ["h264"]
},
"video/h264-rcdo": {
"source": "apache"
},
"video/h264-svc": {
"source": "apache"
},
"video/jpeg": {
"source": "apache",
"extensions": ["jpgv"]
},
"video/jpeg2000": {
"source": "apache"
},
"video/jpm": {
"source": "apache",
"extensions": ["jpm","jpgm"]
},
"video/mj2": {
"source": "apache",
"extensions": ["mj2","mjp2"]
},
"video/mp1s": {
"source": "apache"
},
"video/mp2p": {
"source": "apache"
},
"video/mp2t": {
"source": "apache",
"extensions": ["ts"]
},
"video/mp4": {
"source": "apache",
"compressible": false,
"extensions": ["mp4","mp4v","mpg4"]
},
"video/mp4v-es": {
"source": "apache"
},
"video/mpeg": {
"source": "apache",
"compressible": false,
"extensions": ["mpeg","mpg","mpe","m1v","m2v"]
},
"video/mpeg4-generic": {
"source": "apache"
},
"video/mpv": {
"source": "apache"
},
"video/nv": {
"source": "apache"
},
"video/ogg": {
"source": "apache",
"compressible": false,
"extensions": ["ogv"]
},
"video/parityfec": {
"source": "apache"
},
"video/pointer": {
"source": "apache"
},
"video/quicktime": {
"source": "apache",
"compressible": false,
"extensions": ["qt","mov"]
},
"video/raw": {
"source": "apache"
},
"video/rtp-enc-aescm128": {
"source": "apache"
},
"video/rtx": {
"source": "apache"
},
"video/smpte292m": {
"source": "apache"
},
"video/ulpfec": {
"source": "apache"
},
"video/vc1": {
"source": "apache"
},
"video/vnd.cctv": {
"source": "apache"
},
"video/vnd.dece.hd": {
"source": "apache",
"extensions": ["uvh","uvvh"]
},
"video/vnd.dece.mobile": {
"source": "apache",
"extensions": ["uvm","uvvm"]
},
"video/vnd.dece.mp4": {
"source": "apache"
},
"video/vnd.dece.pd": {
"source": "apache",
"extensions": ["uvp","uvvp"]
},
"video/vnd.dece.sd": {
"source": "apache",
"extensions": ["uvs","uvvs"]
},
"video/vnd.dece.video": {
"source": "apache",
"extensions": ["uvv","uvvv"]
},
"video/vnd.directv.mpeg": {
"source": "apache"
},
"video/vnd.directv.mpeg-tts": {
"source": "apache"
},
"video/vnd.dlna.mpeg-tts": {
"source": "apache"
},
"video/vnd.dvb.file": {
"source": "apache",
"extensions": ["dvb"]
},
"video/vnd.fvt": {
"source": "apache",
"extensions": ["fvt"]
},
"video/vnd.hns.video": {
"source": "apache"
},
"video/vnd.iptvforum.1dparityfec-1010": {
"source": "apache"
},
"video/vnd.iptvforum.1dparityfec-2005": {
"source": "apache"
},
"video/vnd.iptvforum.2dparityfec-1010": {
"source": "apache"
},
"video/vnd.iptvforum.2dparityfec-2005": {
"source": "apache"
},
"video/vnd.iptvforum.ttsavc": {
"source": "apache"
},
"video/vnd.iptvforum.ttsmpeg2": {
"source": "apache"
},
"video/vnd.motorola.video": {
"source": "apache"
},
"video/vnd.motorola.videop": {
"source": "apache"
},
"video/vnd.mpegurl": {
"source": "apache",
"extensions": ["mxu","m4u"]
},
"video/vnd.ms-playready.media.pyv": {
"source": "apache",
"extensions": ["pyv"]
},
"video/vnd.nokia.interleaved-multimedia": {
"source": "apache"
},
"video/vnd.nokia.videovoip": {
"source": "apache"
},
"video/vnd.objectvideo": {
"source": "apache"
},
"video/vnd.sealed.mpeg1": {
"source": "apache"
},
"video/vnd.sealed.mpeg4": {
"source": "apache"
},
"video/vnd.sealed.swf": {
"source": "apache"
},
"video/vnd.sealedmedia.softseal.mov": {
"source": "apache"
},
"video/vnd.uvvu.mp4": {
"source": "apache",
"extensions": ["uvu","uvvu"]
},
"video/vnd.vivo": {
"source": "apache",
"extensions": ["viv"]
},
"video/webm": {
"source": "apache",
"compressible": false,
"extensions": ["webm"]
},
"video/x-f4v": {
"source": "apache",
"extensions": ["f4v"]
},
"video/x-fli": {
"source": "apache",
"extensions": ["fli"]
},
"video/x-flv": {
"source": "apache",
"compressible": false,
"extensions": ["flv"]
},
"video/x-m4v": {
"source": "apache",
"extensions": ["m4v"]
},
"video/x-matroska": {
"source": "apache",
"compressible": false,
"extensions": ["mkv","mk3d","mks"]
},
"video/x-mng": {
"source": "apache",
"extensions": ["mng"]
},
"video/x-ms-asf": {
"source": "apache",
"extensions": ["asf","asx"]
},
"video/x-ms-vob": {
"source": "apache",
"extensions": ["vob"]
},
"video/x-ms-wm": {
"source": "apache",
"extensions": ["wm"]
},
"video/x-ms-wmv": {
"source": "apache",
"compressible": false,
"extensions": ["wmv"]
},
"video/x-ms-wmx": {
"source": "apache",
"extensions": ["wmx"]
},
"video/x-ms-wvx": {
"source": "apache",
"extensions": ["wvx"]
},
"video/x-msvideo": {
"source": "apache",
"extensions": ["avi"]
},
"video/x-sgi-movie": {
"source": "apache",
"extensions": ["movie"]
},
"video/x-smv": {
"source": "apache",
"extensions": ["smv"]
},
"x-conference/x-cooltalk": {
"source": "apache",
"extensions": ["ice"]
},
"x-shader/x-fragment": {
"compressible": true
},
"x-shader/x-vertex": {
"compressible": true
}
}
},{}],132:[function(require,module,exports){
module["exports"] = [
"ants",
"bats",
"bears",
"bees",
"birds",
"buffalo",
"cats",
"chickens",
"cattle",
"dogs",
"dolphins",
"ducks",
"elephants",
"fishes",
"foxes",
"frogs",
"geese",
"goats",
"horses",
"kangaroos",
"lions",
"monkeys",
"owls",
"oxen",
"penguins",
"people",
"pigs",
"rabbits",
"sheep",
"tigers",
"whales",
"wolves",
"zebras",
"banshees",
"crows",
"black cats",
"chimeras",
"ghosts",
"conspirators",
"dragons",
"dwarves",
"elves",
"enchanters",
"exorcists",
"sons",
"foes",
"giants",
"gnomes",
"goblins",
"gooses",
"griffins",
"lycanthropes",
"nemesis",
"ogres",
"oracles",
"prophets",
"sorcerors",
"spiders",
"spirits",
"vampires",
"warlocks",
"vixens",
"werewolves",
"witches",
"worshipers",
"zombies",
"druids"
];
},{}],133:[function(require,module,exports){
var team = {};
module['exports'] = team;
team.creature = require("./creature");
team.name = require("./name");
},{"./creature":132,"./name":134}],134:[function(require,module,exports){
module["exports"] = [
"#{Address.state} #{creature}"
];
},{}],135:[function(require,module,exports){
module["exports"] = [
"####",
"###",
"##"
];
},{}],136:[function(require,module,exports){
module["exports"] = [
"Australia"
];
},{}],137:[function(require,module,exports){
var address = {};
module['exports'] = address;
address.state_abbr = require("./state_abbr");
address.state = require("./state");
address.postcode = require("./postcode");
address.building_number = require("./building_number");
address.street_suffix = require("./street_suffix");
address.default_country = require("./default_country");
},{"./building_number":135,"./default_country":136,"./postcode":138,"./state":139,"./state_abbr":140,"./street_suffix":141}],138:[function(require,module,exports){
module["exports"] = [
"0###",
"2###",
"3###",
"4###",
"5###",
"6###",
"7###"
];
},{}],139:[function(require,module,exports){
module["exports"] = [
"New South Wales",
"Queensland",
"Northern Territory",
"South Australia",
"Western Australia",
"Tasmania",
"Australian Capital Territory",
"Victoria"
];
},{}],140:[function(require,module,exports){
module["exports"] = [
"NSW",
"QLD",
"NT",
"SA",
"WA",
"TAS",
"ACT",
"VIC"
];
},{}],141:[function(require,module,exports){
module["exports"] = [
"Avenue",
"Boulevard",
"Circle",
"Circuit",
"Court",
"Crescent",
"Crest",
"Drive",
"Estate Dr",
"Grove",
"Hill",
"Island",
"Junction",
"Knoll",
"Lane",
"Loop",
"Mall",
"Manor",
"Meadow",
"Mews",
"Parade",
"Parkway",
"Pass",
"Place",
"Plaza",
"Ridge",
"Road",
"Run",
"Square",
"Station St",
"Street",
"Summit",
"Terrace",
"Track",
"Trail",
"View Rd",
"Way"
];
},{}],142:[function(require,module,exports){
var company = {};
module['exports'] = company;
company.suffix = require("./suffix");
},{"./suffix":143}],143:[function(require,module,exports){
module["exports"] = [
"Pty Ltd",
"and Sons",
"Corp",
"Group",
"Brothers",
"Partners"
];
},{}],144:[function(require,module,exports){
var en_AU = {};
module['exports'] = en_AU;
en_AU.title = "Australia (English)";
en_AU.name = require("./name");
en_AU.company = require("./company");
en_AU.internet = require("./internet");
en_AU.address = require("./address");
en_AU.phone_number = require("./phone_number");
},{"./address":137,"./company":142,"./internet":146,"./name":148,"./phone_number":151}],145:[function(require,module,exports){
module["exports"] = [
"com.au",
"com",
"net.au",
"net",
"org.au",
"org"
];
},{}],146:[function(require,module,exports){
var internet = {};
module['exports'] = internet;
internet.domain_suffix = require("./domain_suffix");
},{"./domain_suffix":145}],147:[function(require,module,exports){
module["exports"] = [
"William",
"Jack",
"Oliver",
"Joshua",
"Thomas",
"Lachlan",
"Cooper",
"Noah",
"Ethan",
"Lucas",
"James",
"Samuel",
"Jacob",
"Liam",
"Alexander",
"Benjamin",
"Max",
"Isaac",
"Daniel",
"Riley",
"Ryan",
"Charlie",
"Tyler",
"Jake",
"Matthew",
"Xavier",
"Harry",
"Jayden",
"Nicholas",
"Harrison",
"Levi",
"Luke",
"Adam",
"Henry",
"Aiden",
"Dylan",
"Oscar",
"Michael",
"Jackson",
"Logan",
"Joseph",
"Blake",
"Nathan",
"Connor",
"Elijah",
"Nate",
"Archie",
"Bailey",
"Marcus",
"Cameron",
"Jordan",
"Zachary",
"Caleb",
"Hunter",
"Ashton",
"Toby",
"Aidan",
"Hayden",
"Mason",
"Hamish",
"Edward",
"Angus",
"Eli",
"Sebastian",
"Christian",
"Patrick",
"Andrew",
"Anthony",
"Luca",
"Kai",
"Beau",
"Alex",
"George",
"Callum",
"Finn",
"Zac",
"Mitchell",
"Jett",
"Jesse",
"Gabriel",
"Leo",
"Declan",
"Charles",
"Jasper",
"Jonathan",
"Aaron",
"Hugo",
"David",
"Christopher",
"Chase",
"Owen",
"Justin",
"Ali",
"Darcy",
"Lincoln",
"Cody",
"Phoenix",
"Sam",
"John",
"Joel",
"Isabella",
"Ruby",
"Chloe",
"Olivia",
"Charlotte",
"Mia",
"Lily",
"Emily",
"Ella",
"Sienna",
"Sophie",
"Amelia",
"Grace",
"Ava",
"Zoe",
"Emma",
"Sophia",
"Matilda",
"Hannah",
"Jessica",
"Lucy",
"Georgia",
"Sarah",
"Abigail",
"Zara",
"Eva",
"Scarlett",
"Jasmine",
"Chelsea",
"Lilly",
"Ivy",
"Isla",
"Evie",
"Isabelle",
"Maddison",
"Layla",
"Summer",
"Annabelle",
"Alexis",
"Elizabeth",
"Bella",
"Holly",
"Lara",
"Madison",
"Alyssa",
"Maya",
"Tahlia",
"Claire",
"Hayley",
"Imogen",
"Jade",
"Ellie",
"Sofia",
"Addison",
"Molly",
"Phoebe",
"Alice",
"Savannah",
"Gabriella",
"Kayla",
"Mikayla",
"Abbey",
"Eliza",
"Willow",
"Alexandra",
"Poppy",
"Samantha",
"Stella",
"Amy",
"Amelie",
"Anna",
"Piper",
"Gemma",
"Isabel",
"Victoria",
"Stephanie",
"Caitlin",
"Heidi",
"Paige",
"Rose",
"Amber",
"Audrey",
"Claudia",
"Taylor",
"Madeline",
"Angelina",
"Natalie",
"Charli",
"Lauren",
"Ashley",
"Violet",
"Mackenzie",
"Abby",
"Skye",
"Lillian",
"Alana",
"Lola",
"Leah",
"Eve",
"Kiara"
];
},{}],148:[function(require,module,exports){
var name = {};
module['exports'] = name;
name.first_name = require("./first_name");
name.last_name = require("./last_name");
},{"./first_name":147,"./last_name":149}],149:[function(require,module,exports){
module["exports"] = [
"Smith",
"Jones",
"Williams",
"Brown",
"Wilson",
"Taylor",
"Johnson",
"White",
"Martin",
"Anderson",
"Thompson",
"Nguyen",
"Thomas",
"Walker",
"Harris",
"Lee",
"Ryan",
"Robinson",
"Kelly",
"King",
"Davis",
"Wright",
"Evans",
"Roberts",
"Green",
"Hall",
"Wood",
"Jackson",
"Clarke",
"Patel",
"Khan",
"Lewis",
"James",
"Phillips",
"Mason",
"Mitchell",
"Rose",
"Davies",
"Rodriguez",
"Cox",
"Alexander",
"Garden",
"Campbell",
"Johnston",
"Moore",
"Smyth",
"O'neill",
"Doherty",
"Stewart",
"Quinn",
"Murphy",
"Graham",
"Mclaughlin",
"Hamilton",
"Murray",
"Hughes",
"Robertson",
"Thomson",
"Scott",
"Macdonald",
"Reid",
"Clark",
"Ross",
"Young",
"Watson",
"Paterson",
"Morrison",
"Morgan",
"Griffiths",
"Edwards",
"Rees",
"Jenkins",
"Owen",
"Price",
"Moss",
"Richards",
"Abbott",
"Adams",
"Armstrong",
"Bahringer",
"Bailey",
"Barrows",
"Bartell",
"Bartoletti",
"Barton",
"Bauch",
"Baumbach",
"Bayer",
"Beahan",
"Beatty",
"Becker",
"Beier",
"Berge",
"Bergstrom",
"Bode",
"Bogan",
"Borer",
"Bosco",
"Botsford",
"Boyer",
"Boyle",
"Braun",
"Bruen",
"Carroll",
"Carter",
"Cartwright",
"Casper",
"Cassin",
"Champlin",
"Christiansen",
"Cole",
"Collier",
"Collins",
"Connelly",
"Conroy",
"Corkery",
"Cormier",
"Corwin",
"Cronin",
"Crooks",
"Cruickshank",
"Cummings",
"D'amore",
"Daniel",
"Dare",
"Daugherty",
"Dickens",
"Dickinson",
"Dietrich",
"Donnelly",
"Dooley",
"Douglas",
"Doyle",
"Durgan",
"Ebert",
"Emard",
"Emmerich",
"Erdman",
"Ernser",
"Fadel",
"Fahey",
"Farrell",
"Fay",
"Feeney",
"Feil",
"Ferry",
"Fisher",
"Flatley",
"Gibson",
"Gleason",
"Glover",
"Goldner",
"Goodwin",
"Grady",
"Grant",
"Greenfelder",
"Greenholt",
"Grimes",
"Gutmann",
"Hackett",
"Hahn",
"Haley",
"Hammes",
"Hand",
"Hane",
"Hansen",
"Harber",
"Hartmann",
"Harvey",
"Hayes",
"Heaney",
"Heathcote",
"Heller",
"Hermann",
"Hermiston",
"Hessel",
"Hettinger",
"Hickle",
"Hill",
"Hills",
"Hoppe",
"Howe",
"Howell",
"Hudson",
"Huel",
"Hyatt",
"Jacobi",
"Jacobs",
"Jacobson",
"Jerde",
"Johns",
"Keeling",
"Kemmer",
"Kessler",
"Kiehn",
"Kirlin",
"Klein",
"Koch",
"Koelpin",
"Kohler",
"Koss",
"Kovacek",
"Kreiger",
"Kris",
"Kuhlman",
"Kuhn",
"Kulas",
"Kunde",
"Kutch",
"Lakin",
"Lang",
"Langworth",
"Larkin",
"Larson",
"Leannon",
"Leffler",
"Little",
"Lockman",
"Lowe",
"Lynch",
"Mann",
"Marks",
"Marvin",
"Mayer",
"Mccullough",
"Mcdermott",
"Mckenzie",
"Miller",
"Mills",
"Monahan",
"Morissette",
"Mueller",
"Muller",
"Nader",
"Nicolas",
"Nolan",
"O'connell",
"O'conner",
"O'hara",
"O'keefe",
"Olson",
"O'reilly",
"Parisian",
"Parker",
"Quigley",
"Reilly",
"Reynolds",
"Rice",
"Ritchie",
"Rohan",
"Rolfson",
"Rowe",
"Russel",
"Rutherford",
"Sanford",
"Sauer",
"Schmidt",
"Schmitt",
"Schneider",
"Schroeder",
"Schultz",
"Shields",
"Smitham",
"Spencer",
"Stanton",
"Stark",
"Stokes",
"Swift",
"Tillman",
"Towne",
"Tremblay",
"Tromp",
"Turcotte",
"Turner",
"Walsh",
"Walter",
"Ward",
"Waters",
"Weber",
"Welch",
"West",
"Wilderman",
"Wilkinson",
"Williamson",
"Windler",
"Wolf"
];
},{}],150:[function(require,module,exports){
module["exports"] = [
"0# #### ####",
"+61 # #### ####",
"04## ### ###",
"+61 4## ### ###"
];
},{}],151:[function(require,module,exports){
arguments[4][129][0].apply(exports,arguments)
},{"./formats":150,"dup":129}],152:[function(require,module,exports){
/**
*
* @namespace faker.lorem
*/
var Lorem = function (faker) {
var self = this;
var Helpers = faker.helpers;
/**
* word
*
* @method faker.lorem.word
* @param {number} num
*/
self.word = function (num) {
return faker.random.arrayElement(faker.definitions.lorem.words);
};
/**
* generates a space separated list of words
*
* @method faker.lorem.words
* @param {number} num number of words, defaults to 3
*/
self.words = function (num) {
if (typeof num == 'undefined') { num = 3; }
var words = [];
for (var i = 0; i < num; i++) {
words.push(faker.lorem.word());
}
return words.join(' ');
};
/**
* sentence
*
* @method faker.lorem.sentence
* @param {number} wordCount defaults to a random number between 3 and 10
* @param {number} range
*/
self.sentence = function (wordCount, range) {
if (typeof wordCount == 'undefined') { wordCount = faker.random.number({ min: 3, max: 10 }); }
// if (typeof range == 'undefined') { range = 7; }
// strange issue with the node_min_test failing for captialize, please fix and add faker.lorem.back
//return faker.lorem.words(wordCount + Helpers.randomNumber(range)).join(' ').capitalize();
var sentence = faker.lorem.words(wordCount);
return sentence.charAt(0).toUpperCase() + sentence.slice(1) + '.';
};
/**
* sentences
*
* @method faker.lorem.sentences
* @param {number} sentenceCount defautls to a random number between 2 and 6
* @param {string} separator defaults to `' '`
*/
self.sentences = function (sentenceCount, separator) {
if (typeof sentenceCount === 'undefined') { sentenceCount = faker.random.number({ min: 2, max: 6 });}
if (typeof separator == 'undefined') { separator = " "; }
var sentences = [];
for (sentenceCount; sentenceCount > 0; sentenceCount--) {
sentences.push(faker.lorem.sentence());
}
return sentences.join(separator);
};
/**
* paragraph
*
* @method faker.lorem.paragraph
* @param {number} sentenceCount defaults to 3
*/
self.paragraph = function (sentenceCount) {
if (typeof sentenceCount == 'undefined') { sentenceCount = 3; }
return faker.lorem.sentences(sentenceCount + faker.random.number(3));
};
/**
* paragraphs
*
* @method faker.lorem.paragraphs
* @param {number} paragraphCount defaults to 3
* @param {string} separatora defaults to `'\n \r'`
*/
self.paragraphs = function (paragraphCount, separator) {
if (typeof separator === "undefined") {
separator = "\n \r";
}
if (typeof paragraphCount == 'undefined') { paragraphCount = 3; }
var paragraphs = [];
for (paragraphCount; paragraphCount > 0; paragraphCount--) {
paragraphs.push(faker.lorem.paragraph());
}
return paragraphs.join(separator);
}
/**
* returns random text based on a random lorem method
*
* @method faker.lorem.text
* @param {number} times
*/
self.text = function loremText (times) {
var loremMethods = ['lorem.word', 'lorem.words', 'lorem.sentence', 'lorem.sentences', 'lorem.paragraph', 'lorem.paragraphs', 'lorem.lines'];
var randomLoremMethod = faker.random.arrayElement(loremMethods);
return faker.fake('{{' + randomLoremMethod + '}}');
};
/**
* returns lines of lorem separated by `'\n'`
*
* @method faker.lorem.lines
* @param {number} lineCount defaults to a random number between 1 and 5
*/
self.lines = function lines (lineCount) {
if (typeof lineCount === 'undefined') { lineCount = faker.random.number({ min: 1, max: 5 });}
return faker.lorem.sentences(lineCount, '\n')
};
return self;
};
module["exports"] = Lorem;
},{}],153:[function(require,module,exports){
/**
*
* @namespace faker.name
*/
function Name (faker) {
/**
* firstName
*
* @method firstName
* @param {mixed} gender
* @memberof faker.name
*/
this.firstName = function (gender) {
if (typeof faker.definitions.name.male_first_name !== "undefined" && typeof faker.definitions.name.female_first_name !== "undefined") {
// some locale datasets ( like ru ) have first_name split by gender. since the name.first_name field does not exist in these datasets,
// we must randomly pick a name from either gender array so faker.name.firstName will return the correct locale data ( and not fallback )
if (typeof gender !== 'number') {
gender = faker.random.number(1);
}
if (gender === 0) {
return faker.random.arrayElement(faker.locales[faker.locale].name.male_first_name)
} else {
return faker.random.arrayElement(faker.locales[faker.locale].name.female_first_name);
}
}
return faker.random.arrayElement(faker.definitions.name.first_name);
};
/**
* lastName
*
* @method lastName
* @param {mixed} gender
* @memberof faker.name
*/
this.lastName = function (gender) {
if (typeof faker.definitions.name.male_last_name !== "undefined" && typeof faker.definitions.name.female_last_name !== "undefined") {
// some locale datasets ( like ru ) have last_name split by gender. i have no idea how last names can have genders, but also i do not speak russian
// see above comment of firstName method
if (typeof gender !== 'number') {
gender = faker.random.number(1);
}
if (gender === 0) {
return faker.random.arrayElement(faker.locales[faker.locale].name.male_last_name);
} else {
return faker.random.arrayElement(faker.locales[faker.locale].name.female_last_name);
}
}
return faker.random.arrayElement(faker.definitions.name.last_name);
};
/**
* findName
*
* @method findName
* @param {string} firstName
* @param {string} lastName
* @param {mixed} gender
* @memberof faker.name
*/
this.findName = function (firstName, lastName, gender) {
var r = faker.random.number(8);
var prefix, suffix;
// in particular locales first and last names split by gender,
// thus we keep consistency by passing 0 as male and 1 as female
if (typeof gender !== 'number') {
gender = faker.random.number(1);
}
firstName = firstName || faker.name.firstName(gender);
lastName = lastName || faker.name.lastName(gender);
switch (r) {
case 0:
prefix = faker.name.prefix(gender);
if (prefix) {
return prefix + " " + firstName + " " + lastName;
}
case 1:
suffix = faker.name.suffix(gender);
if (suffix) {
return firstName + " " + lastName + " " + suffix;
}
}
return firstName + " " + lastName;
};
/**
* jobTitle
*
* @method jobTitle
* @memberof faker.name
*/
this.jobTitle = function () {
return faker.name.jobDescriptor() + " " +
faker.name.jobArea() + " " +
faker.name.jobType();
};
/**
* prefix
*
* @method prefix
* @param {mixed} gender
* @memberof faker.name
*/
this.prefix = function (gender) {
if (typeof faker.definitions.name.male_prefix !== "undefined" && typeof faker.definitions.name.female_prefix !== "undefined") {
if (typeof gender !== 'number') {
gender = faker.random.number(1);
}
if (gender === 0) {
return faker.random.arrayElement(faker.locales[faker.locale].name.male_prefix);
} else {
return faker.random.arrayElement(faker.locales[faker.locale].name.female_prefix);
}
}
return faker.random.arrayElement(faker.definitions.name.prefix);
};
/**
* suffix
*
* @method suffix
* @memberof faker.name
*/
this.suffix = function () {
return faker.random.arrayElement(faker.definitions.name.suffix);
};
/**
* title
*
* @method title
* @memberof faker.name
*/
this.title = function() {
var descriptor = faker.random.arrayElement(faker.definitions.name.title.descriptor),
level = faker.random.arrayElement(faker.definitions.name.title.level),
job = faker.random.arrayElement(faker.definitions.name.title.job);
return descriptor + " " + level + " " + job;
};
/**
* jobDescriptor
*
* @method jobDescriptor
* @memberof faker.name
*/
this.jobDescriptor = function () {
return faker.random.arrayElement(faker.definitions.name.title.descriptor);
};
/**
* jobArea
*
* @method jobArea
* @memberof faker.name
*/
this.jobArea = function () {
return faker.random.arrayElement(faker.definitions.name.title.level);
};
/**
* jobType
*
* @method jobType
* @memberof faker.name
*/
this.jobType = function () {
return faker.random.arrayElement(faker.definitions.name.title.job);
};
}
module['exports'] = Name;
},{}],154:[function(require,module,exports){
/**
*
* @namespace faker.phone
*/
var Phone = function (faker) {
var self = this;
/**
* phoneNumber
*
* @method faker.phone.phoneNumber
* @param {string} format
*/
self.phoneNumber = function (format) {
format = format || faker.phone.phoneFormats();
return faker.helpers.replaceSymbolWithNumber(format);
};
// FIXME: this is strange passing in an array index.
/**
* phoneNumberFormat
*
* @method faker.phone.phoneFormatsArrayIndex
* @param phoneFormatsArrayIndex
*/
self.phoneNumberFormat = function (phoneFormatsArrayIndex) {
phoneFormatsArrayIndex = phoneFormatsArrayIndex || 0;
return faker.helpers.replaceSymbolWithNumber(faker.definitions.phone_number.formats[phoneFormatsArrayIndex]);
};
/**
* phoneFormats
*
* @method faker.phone.phoneFormats
*/
self.phoneFormats = function () {
return faker.random.arrayElement(faker.definitions.phone_number.formats);
};
return self;
};
module['exports'] = Phone;
},{}],155:[function(require,module,exports){
var mersenne = require('../vendor/mersenne');
/**
*
* @namespace faker.random
*/
function Random (faker, seed) {
// Use a user provided seed if it exists
if (seed) {
if (Array.isArray(seed) && seed.length) {
mersenne.seed_array(seed);
}
else {
mersenne.seed(seed);
}
}
/**
* returns a single random number based on a max number or range
*
* @method faker.random.number
* @param {mixed} options
*/
this.number = function (options) {
if (typeof options === "number") {
options = {
max: options
};
}
options = options || {};
if (typeof options.min === "undefined") {
options.min = 0;
}
if (typeof options.max === "undefined") {
options.max = 99999;
}
if (typeof options.precision === "undefined") {
options.precision = 1;
}
// Make the range inclusive of the max value
var max = options.max;
if (max >= 0) {
max += options.precision;
}
var randomNumber = options.precision * Math.floor(
mersenne.rand(max / options.precision, options.min / options.precision));
return randomNumber;
}
/**
* takes an array and returns a random element of the array
*
* @method faker.random.arrayElement
* @param {array} array
*/
this.arrayElement = function (array) {
array = array || ["a", "b", "c"];
var r = faker.random.number({ max: array.length - 1 });
return array[r];
}
/**
* takes an object and returns the randomly key or value
*
* @method faker.random.objectElement
* @param {object} object
* @param {mixed} field
*/
this.objectElement = function (object, field) {
object = object || { "foo": "bar", "too": "car" };
var array = Object.keys(object);
var key = faker.random.arrayElement(array);
return field === "key" ? key : object[key];
}
/**
* uuid
*
* @method faker.random.uuid
*/
this.uuid = function () {
var self = this;
var RFC4122_TEMPLATE = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
var replacePlaceholders = function (placeholder) {
var random = self.number({ min: 0, max: 15 });
var value = placeholder == 'x' ? random : (random &0x3 | 0x8);
return value.toString(16);
};
return RFC4122_TEMPLATE.replace(/[xy]/g, replacePlaceholders);
}
/**
* boolean
*
* @method faker.random.boolean
*/
this.boolean = function () {
return !!faker.random.number(1)
}
// TODO: have ability to return specific type of word? As in: noun, adjective, verb, etc
/**
* word
*
* @method faker.random.word
* @param {string} type
*/
this.word = function randomWord (type) {
var wordMethods = [
'commerce.department',
'commerce.productName',
'commerce.productAdjective',
'commerce.productMaterial',
'commerce.product',
'commerce.color',
'company.catchPhraseAdjective',
'company.catchPhraseDescriptor',
'company.catchPhraseNoun',
'company.bsAdjective',
'company.bsBuzz',
'company.bsNoun',
'address.streetSuffix',
'address.county',
'address.country',
'address.state',
'finance.accountName',
'finance.transactionType',
'finance.currencyName',
'hacker.noun',
'hacker.verb',
'hacker.adjective',
'hacker.ingverb',
'hacker.abbreviation',
'name.jobDescriptor',
'name.jobArea',
'name.jobType'];
// randomly pick from the many faker methods that can generate words
var randomWordMethod = faker.random.arrayElement(wordMethods);
return faker.fake('{{' + randomWordMethod + '}}');
}
/**
* randomWords
*
* @method faker.random.words
* @param {number} count defaults to a random value between 1 and 3
*/
this.words = function randomWords (count) {
var words = [];
if (typeof count === "undefined") {
count = faker.random.number({min:1, max: 3});
}
for (var i = 0; i<count; i++) {
words.push(faker.random.word());
}
return words.join(' ');
}
/**
* locale
*
* @method faker.random.image
*/
this.image = function randomImage () {
return faker.image.image();
}
/**
* locale
*
* @method faker.random.locale
*/
this.locale = function randomLocale () {
return faker.random.arrayElement(Object.keys(faker.locales));
};
/**
* alphaNumeric
*
* @method faker.random.alphaNumeric
*/
this.alphaNumeric = function alphaNumeric() {
return faker.random.arrayElement(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]);
}
return this;
}
module['exports'] = Random;
},{"../vendor/mersenne":158}],156:[function(require,module,exports){
// generates fake data for many computer systems properties
/**
*
* @namespace faker.system
*/
function System (faker) {
/**
* generates a file name with extension or optional type
*
* @method faker.system.fileName
* @param {string} ext
* @param {string} type
*/
this.fileName = function (ext, type) {
var str = faker.fake("{{random.words}}.{{system.fileExt}}");
str = str.replace(/ /g, '_');
str = str.replace(/\,/g, '_');
str = str.replace(/\-/g, '_');
str = str.replace(/\\/g, '_');
str = str.toLowerCase();
return str;
};
/**
* commonFileName
*
* @method faker.system.commonFileName
* @param {string} ext
* @param {string} type
*/
this.commonFileName = function (ext, type) {
var str = faker.random.words() + "." + (ext || faker.system.commonFileExt());
str = str.replace(/ /g, '_');
str = str.replace(/\,/g, '_');
str = str.replace(/\-/g, '_');
str = str.replace(/\\/g, '_');
str = str.toLowerCase();
return str;
};
/**
* mimeType
*
* @method faker.system.mimeType
*/
this.mimeType = function () {
return faker.random.arrayElement(Object.keys(faker.definitions.system.mimeTypes));
};
/**
* returns a commonly used file type
*
* @method faker.system.commonFileType
*/
this.commonFileType = function () {
var types = ['video', 'audio', 'image', 'text', 'application'];
return faker.random.arrayElement(types)
};
/**
* returns a commonly used file extension based on optional type
*
* @method faker.system.commonFileExt
* @param {string} type
*/
this.commonFileExt = function (type) {
var types = [
'application/pdf',
'audio/mpeg',
'audio/wav',
'image/png',
'image/jpeg',
'image/gif',
'video/mp4',
'video/mpeg',
'text/html'
];
return faker.system.fileExt(faker.random.arrayElement(types));
};
/**
* returns any file type available as mime-type
*
* @method faker.system.fileType
*/
this.fileType = function () {
var types = [];
var mimes = faker.definitions.system.mimeTypes;
Object.keys(mimes).forEach(function(m){
var parts = m.split('/');
if (types.indexOf(parts[0]) === -1) {
types.push(parts[0]);
}
});
return faker.random.arrayElement(types);
};
/**
* fileExt
*
* @method faker.system.fileExt
* @param {string} mimeType
*/
this.fileExt = function (mimeType) {
var exts = [];
var mimes = faker.definitions.system.mimeTypes;
// get specific ext by mime-type
if (typeof mimes[mimeType] === "object") {
return faker.random.arrayElement(mimes[mimeType].extensions);
}
// reduce mime-types to those with file-extensions
Object.keys(mimes).forEach(function(m){
if (mimes[m].extensions instanceof Array) {
mimes[m].extensions.forEach(function(ext){
exts.push(ext)
});
}
});
return faker.random.arrayElement(exts);
};
/**
* not yet implemented
*
* @method faker.system.directoryPath
*/
this.directoryPath = function () {
// TODO
};
/**
* not yet implemented
*
* @method faker.system.filePath
*/
this.filePath = function () {
// TODO
};
/**
* semver
*
* @method faker.system.semver
*/
this.semver = function () {
return [faker.random.number(9),
faker.random.number(9),
faker.random.number(9)].join('.');
}
}
module['exports'] = System;
},{}],157:[function(require,module,exports){
var Faker = require('../lib');
var faker = new Faker({ locale: 'en_AU', localeFallback: 'en' });
faker.locales['en_AU'] = require('../lib/locales/en_AU');
faker.locales['en'] = require('../lib/locales/en');
module['exports'] = faker;
},{"../lib":45,"../lib/locales/en":112,"../lib/locales/en_AU":144}],158:[function(require,module,exports){
// this program is a JavaScript version of Mersenne Twister, with concealment and encapsulation in class,
// an almost straight conversion from the original program, mt19937ar.c,
// translated by y. okada on July 17, 2006.
// and modified a little at july 20, 2006, but there are not any substantial differences.
// in this program, procedure descriptions and comments of original source code were not removed.
// lines commented with //c// were originally descriptions of c procedure. and a few following lines are appropriate JavaScript descriptions.
// lines commented with /* and */ are original comments.
// lines commented with // are additional comments in this JavaScript version.
// before using this version, create at least one instance of MersenneTwister19937 class, and initialize the each state, given below in c comments, of all the instances.
/*
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/
function MersenneTwister19937()
{
/* constants should be scoped inside the class */
var N, M, MATRIX_A, UPPER_MASK, LOWER_MASK;
/* Period parameters */
//c//#define N 624
//c//#define M 397
//c//#define MATRIX_A 0x9908b0dfUL /* constant vector a */
//c//#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
//c//#define LOWER_MASK 0x7fffffffUL /* least significant r bits */
N = 624;
M = 397;
MATRIX_A = 0x9908b0df; /* constant vector a */
UPPER_MASK = 0x80000000; /* most significant w-r bits */
LOWER_MASK = 0x7fffffff; /* least significant r bits */
//c//static unsigned long mt[N]; /* the array for the state vector */
//c//static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */
var mt = new Array(N); /* the array for the state vector */
var mti = N+1; /* mti==N+1 means mt[N] is not initialized */
function unsigned32 (n1) // returns a 32-bits unsiged integer from an operand to which applied a bit operator.
{
return n1 < 0 ? (n1 ^ UPPER_MASK) + UPPER_MASK : n1;
}
function subtraction32 (n1, n2) // emulates lowerflow of a c 32-bits unsiged integer variable, instead of the operator -. these both arguments must be non-negative integers expressible using unsigned 32 bits.
{
return n1 < n2 ? unsigned32((0x100000000 - (n2 - n1)) & 0xffffffff) : n1 - n2;
}
function addition32 (n1, n2) // emulates overflow of a c 32-bits unsiged integer variable, instead of the operator +. these both arguments must be non-negative integers expressible using unsigned 32 bits.
{
return unsigned32((n1 + n2) & 0xffffffff)
}
function multiplication32 (n1, n2) // emulates overflow of a c 32-bits unsiged integer variable, instead of the operator *. these both arguments must be non-negative integers expressible using unsigned 32 bits.
{
var sum = 0;
for (var i = 0; i < 32; ++i){
if ((n1 >>> i) & 0x1){
sum = addition32(sum, unsigned32(n2 << i));
}
}
return sum;
}
/* initializes mt[N] with a seed */
//c//void init_genrand(unsigned long s)
this.init_genrand = function (s)
{
//c//mt[0]= s & 0xffffffff;
mt[0]= unsigned32(s & 0xffffffff);
for (mti=1; mti<N; mti++) {
mt[mti] =
//c//(1812433253 * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
addition32(multiplication32(1812433253, unsigned32(mt[mti-1] ^ (mt[mti-1] >>> 30))), mti);
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
//c//mt[mti] &= 0xffffffff;
mt[mti] = unsigned32(mt[mti] & 0xffffffff);
/* for >32 bit machines */
}
}
/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
//c//void init_by_array(unsigned long init_key[], int key_length)
this.init_by_array = function (init_key, key_length)
{
//c//int i, j, k;
var i, j, k;
//c//init_genrand(19650218);
this.init_genrand(19650218);
i=1; j=0;
k = (N>key_length ? N : key_length);
for (; k; k--) {
//c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525))
//c// + init_key[j] + j; /* non linear */
mt[i] = addition32(addition32(unsigned32(mt[i] ^ multiplication32(unsigned32(mt[i-1] ^ (mt[i-1] >>> 30)), 1664525)), init_key[j]), j);
mt[i] =
//c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */
unsigned32(mt[i] & 0xffffffff);
i++; j++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
if (j>=key_length) j=0;
}
for (k=N-1; k; k--) {
//c//mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941))
//c//- i; /* non linear */
mt[i] = subtraction32(unsigned32((dbg=mt[i]) ^ multiplication32(unsigned32(mt[i-1] ^ (mt[i-1] >>> 30)), 1566083941)), i);
//c//mt[i] &= 0xffffffff; /* for WORDSIZE > 32 machines */
mt[i] = unsigned32(mt[i] & 0xffffffff);
i++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
}
mt[0] = 0x80000000; /* MSB is 1; assuring non-zero initial array */
}
/* moved outside of genrand_int32() by jwatte 2010-11-17; generate less garbage */
var mag01 = [0x0, MATRIX_A];
/* generates a random number on [0,0xffffffff]-interval */
//c//unsigned long genrand_int32(void)
this.genrand_int32 = function ()
{
//c//unsigned long y;
//c//static unsigned long mag01[2]={0x0UL, MATRIX_A};
var y;
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (mti >= N) { /* generate N words at one time */
//c//int kk;
var kk;
if (mti == N+1) /* if init_genrand() has not been called, */
//c//init_genrand(5489); /* a default initial seed is used */
this.init_genrand(5489); /* a default initial seed is used */
for (kk=0;kk<N-M;kk++) {
//c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
//c//mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1];
y = unsigned32((mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK));
mt[kk] = unsigned32(mt[kk+M] ^ (y >>> 1) ^ mag01[y & 0x1]);
}
for (;kk<N-1;kk++) {
//c//y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
//c//mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1];
y = unsigned32((mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK));
mt[kk] = unsigned32(mt[kk+(M-N)] ^ (y >>> 1) ^ mag01[y & 0x1]);
}
//c//y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
//c//mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1];
y = unsigned32((mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK));
mt[N-1] = unsigned32(mt[M-1] ^ (y >>> 1) ^ mag01[y & 0x1]);
mti = 0;
}
y = mt[mti++];
/* Tempering */
//c//y ^= (y >> 11);
//c//y ^= (y << 7) & 0x9d2c5680;
//c//y ^= (y << 15) & 0xefc60000;
//c//y ^= (y >> 18);
y = unsigned32(y ^ (y >>> 11));
y = unsigned32(y ^ ((y << 7) & 0x9d2c5680));
y = unsigned32(y ^ ((y << 15) & 0xefc60000));
y = unsigned32(y ^ (y >>> 18));
return y;
}
/* generates a random number on [0,0x7fffffff]-interval */
//c//long genrand_int31(void)
this.genrand_int31 = function ()
{
//c//return (genrand_int32()>>1);
return (this.genrand_int32()>>>1);
}
/* generates a random number on [0,1]-real-interval */
//c//double genrand_real1(void)
this.genrand_real1 = function ()
{
//c//return genrand_int32()*(1.0/4294967295.0);
return this.genrand_int32()*(1.0/4294967295.0);
/* divided by 2^32-1 */
}
/* generates a random number on [0,1)-real-interval */
//c//double genrand_real2(void)
this.genrand_real2 = function ()
{
//c//return genrand_int32()*(1.0/4294967296.0);
return this.genrand_int32()*(1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on (0,1)-real-interval */
//c//double genrand_real3(void)
this.genrand_real3 = function ()
{
//c//return ((genrand_int32()) + 0.5)*(1.0/4294967296.0);
return ((this.genrand_int32()) + 0.5)*(1.0/4294967296.0);
/* divided by 2^32 */
}
/* generates a random number on [0,1) with 53-bit resolution*/
//c//double genrand_res53(void)
this.genrand_res53 = function ()
{
//c//unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6;
var a=this.genrand_int32()>>>5, b=this.genrand_int32()>>>6;
return(a*67108864.0+b)*(1.0/9007199254740992.0);
}
/* These real versions are due to Isaku Wada, 2002/01/09 added */
}
// Exports: Public API
// Export the twister class
exports.MersenneTwister19937 = MersenneTwister19937;
// Export a simplified function to generate random numbers
var gen = new MersenneTwister19937;
gen.init_genrand((new Date).getTime() % 1000000000);
// Added max, min range functionality, Marak Squires Sept 11 2014
exports.rand = function(max, min) {
if (max === undefined)
{
min = 0;
max = 32768;
}
return Math.floor(gen.genrand_real2() * (max - min) + min);
}
exports.seed = function(S) {
if (typeof(S) != 'number')
{
throw new Error("seed(S) must take numeric argument; is " + typeof(S));
}
gen.init_genrand(S);
}
exports.seed_array = function(A) {
if (typeof(A) != 'object')
{
throw new Error("seed_array(A) must take array of numbers; is " + typeof(A));
}
gen.init_by_array(A);
}
},{}],159:[function(require,module,exports){
/*
* password-generator
* Copyright(c) 2011-2013 Bermi Ferrer <[email protected]>
* MIT Licensed
*/
(function (root) {
var localName, consonant, letter, password, vowel;
letter = /[a-zA-Z]$/;
vowel = /[aeiouAEIOU]$/;
consonant = /[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]$/;
// Defines the name of the local variable the passwordGenerator library will use
// this is specially useful if window.passwordGenerator is already being used
// by your application and you want a different name. For example:
// // Declare before including the passwordGenerator library
// var localPasswordGeneratorLibraryName = 'pass';
localName = root.localPasswordGeneratorLibraryName || "generatePassword",
password = function (length, memorable, pattern, prefix) {
var char, n;
if (length == null) {
length = 10;
}
if (memorable == null) {
memorable = true;
}
if (pattern == null) {
pattern = /\w/;
}
if (prefix == null) {
prefix = '';
}
if (prefix.length >= length) {
return prefix;
}
if (memorable) {
if (prefix.match(consonant)) {
pattern = vowel;
} else {
pattern = consonant;
}
}
n = Math.floor(Math.random() * 94) + 33;
char = String.fromCharCode(n);
if (memorable) {
char = char.toLowerCase();
}
if (!char.match(pattern)) {
return password(length, memorable, pattern, prefix);
}
return password(length, memorable, pattern, "" + prefix + char);
};
((typeof exports !== 'undefined') ? exports : root)[localName] = password;
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
module.exports = password;
}
}
// Establish the root object, `window` in the browser, or `global` on the server.
}(this));
},{}],160:[function(require,module,exports){
/*
Copyright (c) 2012-2014 Jeffrey Mealo
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------------------------------------------------
Based loosely on Luka Pusic's PHP Script: http://360percents.com/posts/php-random-user-agent-generator/
The license for that script is as follows:
"THE BEER-WARE LICENSE" (Revision 42):
<[email protected]> wrote this file. As long as you retain this notice you can do whatever you want with this stuff.
If we meet some day, and you think this stuff is worth it, you can buy me a beer in return. Luka Pusic
*/
function rnd(a, b) {
//calling rnd() with no arguments is identical to rnd(0, 100)
a = a || 0;
b = b || 100;
if (typeof b === 'number' && typeof a === 'number') {
//rnd(int min, int max) returns integer between min, max
return (function (min, max) {
if (min > max) {
throw new RangeError('expected min <= max; got min = ' + min + ', max = ' + max);
}
return Math.floor(Math.random() * (max - min + 1)) + min;
}(a, b));
}
if (Object.prototype.toString.call(a) === "[object Array]") {
//returns a random element from array (a), even weighting
return a[Math.floor(Math.random() * a.length)];
}
if (a && typeof a === 'object') {
//returns a random key from the passed object; keys are weighted by the decimal probability in their value
return (function (obj) {
var rand = rnd(0, 100) / 100, min = 0, max = 0, key, return_val;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
max = obj[key] + min;
return_val = key;
if (rand >= min && rand <= max) {
break;
}
min = min + obj[key];
}
}
return return_val;
}(a));
}
throw new TypeError('Invalid arguments passed to rnd. (' + (b ? a + ', ' + b : a) + ')');
}
function randomLang() {
return rnd(['AB', 'AF', 'AN', 'AR', 'AS', 'AZ', 'BE', 'BG', 'BN', 'BO', 'BR', 'BS', 'CA', 'CE', 'CO', 'CS',
'CU', 'CY', 'DA', 'DE', 'EL', 'EN', 'EO', 'ES', 'ET', 'EU', 'FA', 'FI', 'FJ', 'FO', 'FR', 'FY',
'GA', 'GD', 'GL', 'GV', 'HE', 'HI', 'HR', 'HT', 'HU', 'HY', 'ID', 'IS', 'IT', 'JA', 'JV', 'KA',
'KG', 'KO', 'KU', 'KW', 'KY', 'LA', 'LB', 'LI', 'LN', 'LT', 'LV', 'MG', 'MK', 'MN', 'MO', 'MS',
'MT', 'MY', 'NB', 'NE', 'NL', 'NN', 'NO', 'OC', 'PL', 'PT', 'RM', 'RO', 'RU', 'SC', 'SE', 'SK',
'SL', 'SO', 'SQ', 'SR', 'SV', 'SW', 'TK', 'TR', 'TY', 'UK', 'UR', 'UZ', 'VI', 'VO', 'YI', 'ZH']);
}
function randomBrowserAndOS() {
var browser = rnd({
chrome: .45132810566,
iexplorer: .27477061836,
firefox: .19384170608,
safari: .06186781118,
opera: .01574236955
}),
os = {
chrome: {win: .89, mac: .09 , lin: .02},
firefox: {win: .83, mac: .16, lin: .01},
opera: {win: .91, mac: .03 , lin: .06},
safari: {win: .04 , mac: .96 },
iexplorer: ['win']
};
return [browser, rnd(os[browser])];
}
function randomProc(arch) {
var procs = {
lin:['i686', 'x86_64'],
mac: {'Intel' : .48, 'PPC': .01, 'U; Intel':.48, 'U; PPC' :.01},
win:['', 'WOW64', 'Win64; x64']
};
return rnd(procs[arch]);
}
function randomRevision(dots) {
var return_val = '';
//generate a random revision
//dots = 2 returns .x.y where x & y are between 0 and 9
for (var x = 0; x < dots; x++) {
return_val += '.' + rnd(0, 9);
}
return return_val;
}
var version_string = {
net: function () {
return [rnd(1, 4), rnd(0, 9), rnd(10000, 99999), rnd(0, 9)].join('.');
},
nt: function () {
return rnd(5, 6) + '.' + rnd(0, 3);
},
ie: function () {
return rnd(7, 11);
},
trident: function () {
return rnd(3, 7) + '.' + rnd(0, 1);
},
osx: function (delim) {
return [10, rnd(5, 10), rnd(0, 9)].join(delim || '.');
},
chrome: function () {
return [rnd(13, 39), 0, rnd(800, 899), 0].join('.');
},
presto: function () {
return '2.9.' + rnd(160, 190);
},
presto2: function () {
return rnd(10, 12) + '.00';
},
safari: function () {
return rnd(531, 538) + '.' + rnd(0, 2) + '.' + rnd(0,2);
}
};
var browser = {
firefox: function firefox(arch) {
//https://developer.mozilla.org/en-US/docs/Gecko_user_agent_string_reference
var firefox_ver = rnd(5, 15) + randomRevision(2),
gecko_ver = 'Gecko/20100101 Firefox/' + firefox_ver,
proc = randomProc(arch),
os_ver = (arch === 'win') ? '(Windows NT ' + version_string.nt() + ((proc) ? '; ' + proc : '')
: (arch === 'mac') ? '(Macintosh; ' + proc + ' Mac OS X ' + version_string.osx()
: '(X11; Linux ' + proc;
return 'Mozilla/5.0 ' + os_ver + '; rv:' + firefox_ver.slice(0, -2) + ') ' + gecko_ver;
},
iexplorer: function iexplorer() {
var ver = version_string.ie();
if (ver >= 11) {
//http://msdn.microsoft.com/en-us/library/ie/hh869301(v=vs.85).aspx
return 'Mozilla/5.0 (Windows NT 6.' + rnd(1,3) + '; Trident/7.0; ' + rnd(['Touch; ', '']) + 'rv:11.0) like Gecko';
}
//http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx
return 'Mozilla/5.0 (compatible; MSIE ' + ver + '.0; Windows NT ' + version_string.nt() + '; Trident/' +
version_string.trident() + ((rnd(0, 1) === 1) ? '; .NET CLR ' + version_string.net() : '') + ')';
},
opera: function opera(arch) {
//http://www.opera.com/docs/history/
var presto_ver = ' Presto/' + version_string.presto() + ' Version/' + version_string.presto2() + ')',
os_ver = (arch === 'win') ? '(Windows NT ' + version_string.nt() + '; U; ' + randomLang() + presto_ver
: (arch === 'lin') ? '(X11; Linux ' + randomProc(arch) + '; U; ' + randomLang() + presto_ver
: '(Macintosh; Intel Mac OS X ' + version_string.osx() + ' U; ' + randomLang() + ' Presto/' +
version_string.presto() + ' Version/' + version_string.presto2() + ')';
return 'Opera/' + rnd(9, 14) + '.' + rnd(0, 99) + ' ' + os_ver;
},
safari: function safari(arch) {
var safari = version_string.safari(),
ver = rnd(4, 7) + '.' + rnd(0,1) + '.' + rnd(0,10),
os_ver = (arch === 'mac') ? '(Macintosh; ' + randomProc('mac') + ' Mac OS X '+ version_string.osx('_') + ' rv:' + rnd(2, 6) + '.0; '+ randomLang() + ') '
: '(Windows; U; Windows NT ' + version_string.nt() + ')';
return 'Mozilla/5.0 ' + os_ver + 'AppleWebKit/' + safari + ' (KHTML, like Gecko) Version/' + ver + ' Safari/' + safari;
},
chrome: function chrome(arch) {
var safari = version_string.safari(),
os_ver = (arch === 'mac') ? '(Macintosh; ' + randomProc('mac') + ' Mac OS X ' + version_string.osx('_') + ') '
: (arch === 'win') ? '(Windows; U; Windows NT ' + version_string.nt() + ')'
: '(X11; Linux ' + randomProc(arch);
return 'Mozilla/5.0 ' + os_ver + ' AppleWebKit/' + safari + ' (KHTML, like Gecko) Chrome/' + version_string.chrome() + ' Safari/' + safari;
}
};
exports.generate = function generate() {
var random = randomBrowserAndOS();
return browser[random[0]](random[1]);
};
},{}],161:[function(require,module,exports){
var ret = require('ret');
var DRange = require('discontinuous-range');
var types = ret.types;
/**
* If code is alphabetic, converts to other case.
* If not alphabetic, returns back code.
*
* @param {Number} code
* @return {Number}
*/
function toOtherCase(code) {
return code + (97 <= code && code <= 122 ? -32 :
65 <= code && code <= 90 ? 32 : 0);
}
/**
* Randomly returns a true or false value.
*
* @return {Boolean}
*/
function randBool() {
return !this.randInt(0, 1);
}
/**
* Randomly selects and returns a value from the array.
*
* @param {Array.<Object>} arr
* @return {Object}
*/
function randSelect(arr) {
if (arr instanceof DRange) {
return arr.index(this.randInt(0, arr.length - 1));
}
return arr[this.randInt(0, arr.length - 1)];
}
/**
* expands a token to a DiscontinuousRange of characters which has a
* length and an index function (for random selecting)
*
* @param {Object} token
* @return {DiscontinuousRange}
*/
function expand(token) {
if (token.type === ret.types.CHAR) return new DRange(token.value);
if (token.type === ret.types.RANGE) return new DRange(token.from, token.to);
if (token.type === ret.types.SET) {
var drange = new DRange();
for (var i = 0; i < token.set.length; i++) {
var subrange = expand.call(this, token.set[i]);
drange.add(subrange);
if (this.ignoreCase) {
for (var j = 0; j < subrange.length; j++) {
var code = subrange.index(j);
var otherCaseCode = toOtherCase(code);
if (code !== otherCaseCode) {
drange.add(otherCaseCode);
}
}
}
}
if (token.not) {
return this.defaultRange.clone().subtract(drange);
} else {
return drange;
}
}
throw new Error('unexpandable token type: ' + token.type);
}
/**
* @constructor
* @param {RegExp|String} regexp
* @param {String} m
*/
var RandExp = module.exports = function(regexp, m) {
this.defaultRange = this.defaultRange.clone();
if (regexp instanceof RegExp) {
this.ignoreCase = regexp.ignoreCase;
this.multiline = regexp.multiline;
if (typeof regexp.max === 'number') {
this.max = regexp.max;
}
regexp = regexp.source;
} else if (typeof regexp === 'string') {
this.ignoreCase = m && m.indexOf('i') !== -1;
this.multiline = m && m.indexOf('m') !== -1;
} else {
throw new Error('Expected a regexp or string');
}
this.tokens = ret(regexp);
};
// When a repetitional token has its max set to Infinite,
// randexp won't actually generate a random amount between min and Infinite
// instead it will see Infinite as min + 100.
RandExp.prototype.max = 100;
// Generates the random string.
RandExp.prototype.gen = function() {
return gen.call(this, this.tokens, []);
};
// Enables use of randexp with a shorter call.
RandExp.randexp = function(regexp, m) {
var randexp;
if (regexp._randexp === undefined) {
randexp = new RandExp(regexp, m);
regexp._randexp = randexp;
} else {
randexp = regexp._randexp;
if (typeof regexp.max === 'number') {
randexp.max = regexp.max;
}
if (regexp.defaultRange instanceof DRange) {
randexp.defaultRange = regexp.defaultRange;
}
if (typeof regexp.randInt === 'function') {
randexp.randInt = regexp.randInt;
}
}
return randexp.gen();
};
// This enables sugary /regexp/.gen syntax.
RandExp.sugar = function() {
/* jshint freeze:false */
RegExp.prototype.gen = function() {
return RandExp.randexp(this);
};
};
// This allows expanding to include additional characters
// for instance: RandExp.defaultRange.add(0, 65535);
RandExp.prototype.defaultRange = new DRange(32, 126);
/**
* Randomly generates and returns a number between a and b (inclusive).
*
* @param {Number} a
* @param {Number} b
* @return {Number}
*/
RandExp.prototype.randInt = function(a, b) {
return a + Math.floor(Math.random() * (1 + b - a));
};
/**
* Generate random string modeled after given tokens.
*
* @param {Object} token
* @param {Array.<String>} groups
* @return {String}
*/
function gen(token, groups) {
var stack, str, n, i, l;
switch (token.type) {
case types.ROOT:
case types.GROUP:
if (token.notFollowedBy) { return ''; }
// Insert placeholder until group string is generated.
if (token.remember && token.groupNumber === undefined) {
token.groupNumber = groups.push(null) - 1;
}
stack = token.options ?
randSelect.call(this, token.options) : token.stack;
str = '';
for (i = 0, l = stack.length; i < l; i++) {
str += gen.call(this, stack[i], groups);
}
if (token.remember) {
groups[token.groupNumber] = str;
}
return str;
case types.POSITION:
// Do nothing for now.
return '';
case types.SET:
var expanded_set = expand.call(this, token);
if (!expanded_set.length) return '';
return String.fromCharCode(randSelect.call(this, expanded_set));
case types.REPETITION:
// Randomly generate number between min and max.
n = this.randInt(token.min,
token.max === Infinity ? token.min + this.max : token.max);
str = '';
for (i = 0; i < n; i++) {
str += gen.call(this, token.value, groups);
}
return str;
case types.REFERENCE:
return groups[token.value - 1] || '';
case types.CHAR:
var code = this.ignoreCase && randBool.call(this) ?
toOtherCase(token.value) : token.value;
return String.fromCharCode(code);
}
}
},{"discontinuous-range":162,"ret":163}],162:[function(require,module,exports){
//protected helper class
function _SubRange(low, high) {
this.low = low;
this.high = high;
this.length = 1 + high - low;
}
_SubRange.prototype.overlaps = function (range) {
return !(this.high < range.low || this.low > range.high);
};
_SubRange.prototype.touches = function (range) {
return !(this.high + 1 < range.low || this.low - 1 > range.high);
};
//returns inclusive combination of _SubRanges as a _SubRange
_SubRange.prototype.add = function (range) {
return this.touches(range) && new _SubRange(Math.min(this.low, range.low), Math.max(this.high, range.high));
};
//returns subtraction of _SubRanges as an array of _SubRanges (there's a case where subtraction divides it in 2)
_SubRange.prototype.subtract = function (range) {
if (!this.overlaps(range)) return false;
if (range.low <= this.low && range.high >= this.high) return [];
if (range.low > this.low && range.high < this.high) return [new _SubRange(this.low, range.low - 1), new _SubRange(range.high + 1, this.high)];
if (range.low <= this.low) return [new _SubRange(range.high + 1, this.high)];
return [new _SubRange(this.low, range.low - 1)];
};
_SubRange.prototype.toString = function () {
if (this.low == this.high) return this.low.toString();
return this.low + '-' + this.high;
};
_SubRange.prototype.clone = function () {
return new _SubRange(this.low, this.high);
};
function DiscontinuousRange(a, b) {
if (this instanceof DiscontinuousRange) {
this.ranges = [];
this.length = 0;
if (a !== undefined) this.add(a, b);
} else {
return new DiscontinuousRange(a, b);
}
}
function _update_length(self) {
self.length = self.ranges.reduce(function (previous, range) {return previous + range.length}, 0);
}
DiscontinuousRange.prototype.add = function (a, b) {
var self = this;
function _add(subrange) {
var new_ranges = [];
var i = 0;
while (i < self.ranges.length && !subrange.touches(self.ranges[i])) {
new_ranges.push(self.ranges[i].clone());
i++;
}
while (i < self.ranges.length && subrange.touches(self.ranges[i])) {
subrange = subrange.add(self.ranges[i]);
i++;
}
new_ranges.push(subrange);
while (i < self.ranges.length) {
new_ranges.push(self.ranges[i].clone());
i++;
}
self.ranges = new_ranges;
_update_length(self);
}
if (a instanceof DiscontinuousRange) {
a.ranges.forEach(_add);
} else {
if (a instanceof _SubRange) {
_add(a);
} else {
if (b === undefined) b = a;
_add(new _SubRange(a, b));
}
}
return this;
};
DiscontinuousRange.prototype.subtract = function (a, b) {
var self = this;
function _subtract(subrange) {
var new_ranges = [];
var i = 0;
while (i < self.ranges.length && !subrange.overlaps(self.ranges[i])) {
new_ranges.push(self.ranges[i].clone());
i++;
}
while (i < self.ranges.length && subrange.overlaps(self.ranges[i])) {
new_ranges = new_ranges.concat(self.ranges[i].subtract(subrange));
i++;
}
while (i < self.ranges.length) {
new_ranges.push(self.ranges[i].clone());
i++;
}
self.ranges = new_ranges;
_update_length(self);
}
if (a instanceof DiscontinuousRange) {
a.ranges.forEach(_subtract);
} else {
if (a instanceof _SubRange) {
_subtract(a);
} else {
if (b === undefined) b = a;
_subtract(new _SubRange(a, b));
}
}
return this;
};
DiscontinuousRange.prototype.index = function (index) {
var i = 0;
while (i < this.ranges.length && this.ranges[i].length <= index) {
index -= this.ranges[i].length;
i++;
}
if (i >= this.ranges.length) return null;
return this.ranges[i].low + index;
};
DiscontinuousRange.prototype.toString = function () {
return '[ ' + this.ranges.join(', ') + ' ]'
};
DiscontinuousRange.prototype.clone = function () {
return new DiscontinuousRange(this);
};
module.exports = DiscontinuousRange;
},{}],163:[function(require,module,exports){
var util = require('./util');
var types = require('./types');
var sets = require('./sets');
var positions = require('./positions');
module.exports = function(regexpStr) {
var i = 0, l, c,
start = { type: types.ROOT, stack: []},
// Keep track of last clause/group and stack.
lastGroup = start,
last = start.stack,
groupStack = [];
var repeatErr = function(i) {
util.error(regexpStr, 'Nothing to repeat at column ' + (i - 1));
};
// Decode a few escaped characters.
var str = util.strToChars(regexpStr);
l = str.length;
// Iterate through each character in string.
while (i < l) {
c = str[i++];
switch (c) {
// Handle escaped characters, inclues a few sets.
case '\\':
c = str[i++];
switch (c) {
case 'b':
last.push(positions.wordBoundary());
break;
case 'B':
last.push(positions.nonWordBoundary());
break;
case 'w':
last.push(sets.words());
break;
case 'W':
last.push(sets.notWords());
break;
case 'd':
last.push(sets.ints());
break;
case 'D':
last.push(sets.notInts());
break;
case 's':
last.push(sets.whitespace());
break;
case 'S':
last.push(sets.notWhitespace());
break;
default:
// Check if c is integer.
// In which case it's a reference.
if (/\d/.test(c)) {
last.push({ type: types.REFERENCE, value: parseInt(c, 10) });
// Escaped character.
} else {
last.push({ type: types.CHAR, value: c.charCodeAt(0) });
}
}
break;
// Positionals.
case '^':
last.push(positions.begin());
break;
case '$':
last.push(positions.end());
break;
// Handle custom sets.
case '[':
// Check if this class is 'anti' i.e. [^abc].
var not;
if (str[i] === '^') {
not = true;
i++;
} else {
not = false;
}
// Get all the characters in class.
var classTokens = util.tokenizeClass(str.slice(i), regexpStr);
// Increase index by length of class.
i += classTokens[1];
last.push({
type: types.SET
, set: classTokens[0]
, not: not
});
break;
// Class of any character except \n.
case '.':
last.push(sets.anyChar());
break;
// Push group onto stack.
case '(':
// Create group.
var group = {
type: types.GROUP
, stack: []
, remember: true
};
c = str[i];
// if if this is a special kind of group.
if (c === '?') {
c = str[i + 1];
i += 2;
// Match if followed by.
if (c === '=') {
group.followedBy = true;
// Match if not followed by.
} else if (c === '!') {
group.notFollowedBy = true;
} else if (c !== ':') {
util.error(regexpStr,
'Invalid group, character \'' + c + '\' after \'?\' at column ' +
(i - 1));
}
group.remember = false;
}
// Insert subgroup into current group stack.
last.push(group);
// Remember the current group for when the group closes.
groupStack.push(lastGroup);
// Make this new group the current group.
lastGroup = group;
last = group.stack;
break;
// Pop group out of stack.
case ')':
if (groupStack.length === 0) {
util.error(regexpStr, 'Unmatched ) at column ' + (i - 1));
}
lastGroup = groupStack.pop();
// Check if this group has a PIPE.
// To get back the correct last stack.
last = lastGroup.options ? lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack;
break;
// Use pipe character to give more choices.
case '|':
// Create array where options are if this is the first PIPE
// in this clause.
if (!lastGroup.options) {
lastGroup.options = [lastGroup.stack];
delete lastGroup.stack;
}
// Create a new stack and add to options for rest of clause.
var stack = [];
lastGroup.options.push(stack);
last = stack;
break;
// Repetition.
// For every repetition, remove last element from last stack
// then insert back a RANGE object.
// This design is chosen because there could be more than
// one repetition symbols in a regex i.e. `a?+{2,3}`.
case '{':
var rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max;
if (rs !== null) {
min = parseInt(rs[1], 10);
max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min;
i += rs[0].length;
last.push({
type: types.REPETITION
, min: min
, max: max
, value: last.pop()
});
} else {
last.push({
type: types.CHAR
, value: 123
});
}
break;
case '?':
if (last.length === 0) {
repeatErr(i);
}
last.push({
type: types.REPETITION
, min: 0
, max: 1
, value: last.pop()
});
break;
case '+':
if (last.length === 0) {
repeatErr(i);
}
last.push({
type: types.REPETITION
, min: 1
, max: Infinity
, value: last.pop()
});
break;
case '*':
if (last.length === 0) {
repeatErr(i);
}
last.push({
type: types.REPETITION
, min: 0
, max: Infinity
, value: last.pop()
});
break;
// Default is a character that is not `\[](){}?+*^$`.
default:
last.push({
type: types.CHAR
, value: c.charCodeAt(0)
});
}
}
// Check if any groups have not been closed.
if (groupStack.length !== 0) {
util.error(regexpStr, 'Unterminated group');
}
return start;
};
module.exports.types = types;
},{"./positions":164,"./sets":165,"./types":166,"./util":167}],164:[function(require,module,exports){
var types = require('./types');
exports.wordBoundary = function() {
return { type: types.POSITION, value: 'b' };
};
exports.nonWordBoundary = function() {
return { type: types.POSITION, value: 'B' };
};
exports.begin = function() {
return { type: types.POSITION, value: '^' };
};
exports.end = function() {
return { type: types.POSITION, value: '$' };
};
},{"./types":166}],165:[function(require,module,exports){
var types = require('./types');
var INTS = function() {
return [{ type: types.RANGE , from: 48, to: 57 }];
};
var WORDS = function() {
return [
{ type: types.CHAR, value: 95 }
, { type: types.RANGE, from: 97, to: 122 }
, { type: types.RANGE, from: 65, to: 90 }
].concat(INTS());
};
var WHITESPACE = function() {
return [
{ type: types.CHAR, value: 9 }
, { type: types.CHAR, value: 10 }
, { type: types.CHAR, value: 11 }
, { type: types.CHAR, value: 12 }
, { type: types.CHAR, value: 13 }
, { type: types.CHAR, value: 32 }
, { type: types.CHAR, value: 160 }
, { type: types.CHAR, value: 5760 }
, { type: types.CHAR, value: 6158 }
, { type: types.CHAR, value: 8192 }
, { type: types.CHAR, value: 8193 }
, { type: types.CHAR, value: 8194 }
, { type: types.CHAR, value: 8195 }
, { type: types.CHAR, value: 8196 }
, { type: types.CHAR, value: 8197 }
, { type: types.CHAR, value: 8198 }
, { type: types.CHAR, value: 8199 }
, { type: types.CHAR, value: 8200 }
, { type: types.CHAR, value: 8201 }
, { type: types.CHAR, value: 8202 }
, { type: types.CHAR, value: 8232 }
, { type: types.CHAR, value: 8233 }
, { type: types.CHAR, value: 8239 }
, { type: types.CHAR, value: 8287 }
, { type: types.CHAR, value: 12288 }
, { type: types.CHAR, value: 65279 }
];
};
var NOTANYCHAR = function() {
return [
{ type: types.CHAR, value: 10 }
, { type: types.CHAR, value: 13 }
, { type: types.CHAR, value: 8232 }
, { type: types.CHAR, value: 8233 }
];
};
// predefined class objects
exports.words = function() {
return { type: types.SET, set: WORDS(), not: false };
};
exports.notWords = function() {
return { type: types.SET, set: WORDS(), not: true };
};
exports.ints = function() {
return { type: types.SET, set: INTS(), not: false };
};
exports.notInts = function() {
return { type: types.SET, set: INTS(), not: true };
};
exports.whitespace = function() {
return { type: types.SET, set: WHITESPACE(), not: false };
};
exports.notWhitespace = function() {
return { type: types.SET, set: WHITESPACE(), not: true };
};
exports.anyChar = function() {
return { type: types.SET, set: NOTANYCHAR(), not: true };
};
},{"./types":166}],166:[function(require,module,exports){
module.exports = {
ROOT : 0
, GROUP : 1
, POSITION : 2
, SET : 3
, RANGE : 4
, REPETITION : 5
, REFERENCE : 6
, CHAR : 7
};
},{}],167:[function(require,module,exports){
var types = require('./types');
var sets = require('./sets');
// All of these are private and only used by randexp.
// It's assumed that they will always be called with the correct input.
var CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?';
var SLSH = { '0': 0, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13 };
/**
* Finds character representations in str and convert all to
* their respective characters
*
* @param {String} str
* @return {String}
*/
exports.strToChars = function(str) {
var chars_regex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z\[\\\]\^?])|([0tnvfr]))/g;
str = str.replace(chars_regex, function(s, b, lbs, a16, b16, c8, dctrl, eslsh) {
if (lbs) {
return s;
}
var code = b ? 8 :
a16 ? parseInt(a16, 16) :
b16 ? parseInt(b16, 16) :
c8 ? parseInt(c8, 8) :
dctrl ? CTRL.indexOf(dctrl) :
eslsh ? SLSH[eslsh] : undefined;
var c = String.fromCharCode(code);
// Escape special regex characters.
if (/[\[\]{}\^$.|?*+()]/.test(c)) {
c = '\\' + c;
}
return c;
});
return str;
};
/**
* turns class into tokens
* reads str until it encounters a ] not preceeded by a \
*
* @param {String} str
* @param {String} regexpStr
* @return {Array.<Array.<Object>, Number>}
*/
exports.tokenizeClass = function(str, regexpStr) {
var tokens = []
, regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g
, rs, c
;
while ((rs = regexp.exec(str)) != null) {
if (rs[1]) {
tokens.push(sets.words());
} else if (rs[2]) {
tokens.push(sets.ints());
} else if (rs[3]) {
tokens.push(sets.whitespace());
} else if (rs[4]) {
tokens.push(sets.notWords());
} else if (rs[5]) {
tokens.push(sets.notInts());
} else if (rs[6]) {
tokens.push(sets.notWhitespace());
} else if (rs[7]) {
tokens.push({
type: types.RANGE
, from: (rs[8] || rs[9]).charCodeAt(0)
, to: rs[10].charCodeAt(0)
});
} else if (c = rs[12]) {
tokens.push({
type: types.CHAR
, value: c.charCodeAt(0)
});
} else {
return [tokens, regexp.lastIndex];
}
}
exports.error(regexpStr, 'Unterminated character class');
};
/**
* Shortcut to throw errors.
*
* @param {String} regexp
* @param {String} msg
*/
exports.error = function(regexp, msg) {
throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg);
};
},{"./sets":165,"./types":166}],"json-schema-faker":[function(require,module,exports){
module.exports = require('../lib/')
.extend('faker', function() {
try {
return require('faker/locale/en_AU');
} catch (e) {
return null;
}
});
},{"../lib/":19,"faker/locale/en_AU":157}]},{},["json-schema-faker"])("json-schema-faker")
}); | menuka94/cdnjs | ajax/libs/json-schema-faker/0.3.3/locale/en_AU.js | JavaScript | mit | 507,356 |
/*!
* Qoopido.js library v3.4.0, 2014-6-9
* https://github.com/dlueth/qoopido.js
* (c) 2014 Dirk Lueth
* Dual licensed under MIT and GPL
*/
!function(e){window.qoopido.register("support/element/canvas",e,["../../support"])}(function(e,t,o,n,s,a){"use strict";var r=e.support;return r.addTest("/element/canvas",function(e){var t=r.pool?r.pool.obtain("canvas"):a.createElement("canvas");t.getContext&&t.getContext("2d")?e.resolve():e.reject(),t.dispose&&t.dispose()})}); | honestree/cdnjs | ajax/libs/qoopido.js/3.4.0/support/element/canvas.js | JavaScript | mit | 469 |
/**
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize exports="node" -o ./compat/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <http://lodash.com/license>
*/
/* Native method shortcuts for methods with the same name as other `lodash` methods */
var nativeMax = Math.max,
nativeMin = Math.min;
/**
* Gets the index at which the last occurrence of `value` is found using strict
* equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used
* as the offset from the end of the collection.
*
* If a property name is provided for `callback` the created "_.pluck" style
* callback will return the property value of the given element.
*
* If an object is provided for `callback` the created "_.where" style callback
* will return `true` for elements that have the properties of the given object,
* else `false`.
*
* @static
* @memberOf _
* @category Arrays
* @param {Array} array The array to search.
* @param {*} value The value to search for.
* @param {number} [fromIndex=array.length-1] The index to search from.
* @returns {number} Returns the index of the matched value or `-1`.
* @example
*
* _.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
* // => 4
*
* _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3);
* // => 1
*/
function lastIndexOf(array, value, fromIndex) {
var index = array ? array.length : 0;
if (typeof fromIndex == 'number') {
index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1;
}
while (index--) {
if (array[index] === value) {
return index;
}
}
return -1;
}
module.exports = lastIndexOf;
| tspires/personal | zillow/node_modules/xml2js/node_modules/xmlbuilder/node_modules/lodash-node/compat/arrays/lastIndexOf.js | JavaScript | mit | 1,858 |
require('./angular-locale_lag-tz');
module.exports = 'ngLocale';
| DamascenoRafael/cos482-qualidade-de-software | www/src/main/webapp/bower_components/angular-i18n/lag-tz.js | JavaScript | mit | 65 |
/*
* # Semantic UI - 2.1.4
* https://github.com/Semantic-Org/Semantic-UI
* http://www.semantic-ui.com/
*
* Copyright 2014 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
/*!
* # Semantic UI 2.1.4 - Site
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
$.site = $.fn.site = function(parameters) {
var
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.site.settings, parameters)
: $.extend({}, $.site.settings),
namespace = settings.namespace,
error = settings.error,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
$document = $(document),
$module = $document,
element = this,
instance = $module.data(moduleNamespace),
module,
returnedValue
;
module = {
initialize: function() {
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of site', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
normalize: function() {
module.fix.console();
module.fix.requestAnimationFrame();
},
fix: {
console: function() {
module.debug('Normalizing window.console');
if (console === undefined || console.log === undefined) {
module.verbose('Console not available, normalizing events');
module.disable.console();
}
if (typeof console.group == 'undefined' || typeof console.groupEnd == 'undefined' || typeof console.groupCollapsed == 'undefined') {
module.verbose('Console group not available, normalizing events');
window.console.group = function() {};
window.console.groupEnd = function() {};
window.console.groupCollapsed = function() {};
}
if (typeof console.markTimeline == 'undefined') {
module.verbose('Mark timeline not available, normalizing events');
window.console.markTimeline = function() {};
}
},
consoleClear: function() {
module.debug('Disabling programmatic console clearing');
window.console.clear = function() {};
},
requestAnimationFrame: function() {
module.debug('Normalizing requestAnimationFrame');
if(window.requestAnimationFrame === undefined) {
module.debug('RequestAnimationFrame not available, normalizing event');
window.requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { setTimeout(callback, 0); }
;
}
}
},
moduleExists: function(name) {
return ($.fn[name] !== undefined && $.fn[name].settings !== undefined);
},
enabled: {
modules: function(modules) {
var
enabledModules = []
;
modules = modules || settings.modules;
$.each(modules, function(index, name) {
if(module.moduleExists(name)) {
enabledModules.push(name);
}
});
return enabledModules;
}
},
disabled: {
modules: function(modules) {
var
disabledModules = []
;
modules = modules || settings.modules;
$.each(modules, function(index, name) {
if(!module.moduleExists(name)) {
disabledModules.push(name);
}
});
return disabledModules;
}
},
change: {
setting: function(setting, value, modules, modifyExisting) {
modules = (typeof modules === 'string')
? (modules === 'all')
? settings.modules
: [modules]
: modules || settings.modules
;
modifyExisting = (modifyExisting !== undefined)
? modifyExisting
: true
;
$.each(modules, function(index, name) {
var
namespace = (module.moduleExists(name))
? $.fn[name].settings.namespace || false
: true,
$existingModules
;
if(module.moduleExists(name)) {
module.verbose('Changing default setting', setting, value, name);
$.fn[name].settings[setting] = value;
if(modifyExisting && namespace) {
$existingModules = $(':data(module-' + namespace + ')');
if($existingModules.length > 0) {
module.verbose('Modifying existing settings', $existingModules);
$existingModules[name]('setting', setting, value);
}
}
}
});
},
settings: function(newSettings, modules, modifyExisting) {
modules = (typeof modules === 'string')
? [modules]
: modules || settings.modules
;
modifyExisting = (modifyExisting !== undefined)
? modifyExisting
: true
;
$.each(modules, function(index, name) {
var
$existingModules
;
if(module.moduleExists(name)) {
module.verbose('Changing default setting', newSettings, name);
$.extend(true, $.fn[name].settings, newSettings);
if(modifyExisting && namespace) {
$existingModules = $(':data(module-' + namespace + ')');
if($existingModules.length > 0) {
module.verbose('Modifying existing settings', $existingModules);
$existingModules[name]('setting', newSettings);
}
}
}
});
}
},
enable: {
console: function() {
module.console(true);
},
debug: function(modules, modifyExisting) {
modules = modules || settings.modules;
module.debug('Enabling debug for modules', modules);
module.change.setting('debug', true, modules, modifyExisting);
},
verbose: function(modules, modifyExisting) {
modules = modules || settings.modules;
module.debug('Enabling verbose debug for modules', modules);
module.change.setting('verbose', true, modules, modifyExisting);
}
},
disable: {
console: function() {
module.console(false);
},
debug: function(modules, modifyExisting) {
modules = modules || settings.modules;
module.debug('Disabling debug for modules', modules);
module.change.setting('debug', false, modules, modifyExisting);
},
verbose: function(modules, modifyExisting) {
modules = modules || settings.modules;
module.debug('Disabling verbose debug for modules', modules);
module.change.setting('verbose', false, modules, modifyExisting);
}
},
console: function(enable) {
if(enable) {
if(instance.cache.console === undefined) {
module.error(error.console);
return;
}
module.debug('Restoring console function');
window.console = instance.cache.console;
}
else {
module.debug('Disabling console function');
instance.cache.console = window.console;
window.console = {
clear : function(){},
error : function(){},
group : function(){},
groupCollapsed : function(){},
groupEnd : function(){},
info : function(){},
log : function(){},
markTimeline : function(){},
warn : function(){}
};
}
},
destroy: function() {
module.verbose('Destroying previous site for', $module);
$module
.removeData(moduleNamespace)
;
},
cache: {},
setting: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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({
'Element' : element,
'Name' : message[0],
'Arguments' : [].slice.call(message, 1) || '',
'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( (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 = [];
}
},
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 {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
module.destroy();
}
module.initialize();
}
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.site.settings = {
name : 'Site',
namespace : 'site',
error : {
console : 'Console cannot be restored, most likely it was overwritten outside of module',
method : 'The method you called is not defined.'
},
debug : false,
verbose : false,
performance : true,
modules: [
'accordion',
'api',
'checkbox',
'dimmer',
'dropdown',
'embed',
'form',
'modal',
'nag',
'popup',
'rating',
'shape',
'sidebar',
'state',
'sticky',
'tab',
'transition',
'visit',
'visibility'
],
siteNamespace : 'site',
namespaceStub : {
cache : {},
config : {},
sections : {},
section : {},
utilities : {}
}
};
// allows for selection of elements with data attributes
$.extend($.expr[ ":" ], {
data: ($.expr.createPseudo)
? $.expr.createPseudo(function(dataName) {
return function(elem) {
return !!$.data(elem, dataName);
};
})
: function(elem, i, match) {
// support: jQuery < 1.8
return !!$.data(elem, match[ 3 ]);
}
});
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Form Validation
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.fn.form = function(parameters) {
var
$allModules = $(this),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
legacyParameters = arguments[1],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
$module = $(this),
element = this,
formErrors = [],
keyHeldDown = false,
// set at run-time
$field,
$group,
$message,
$prompt,
$submit,
$clear,
$reset,
settings,
validation,
metadata,
selector,
className,
error,
namespace,
moduleNamespace,
eventNamespace,
instance,
module
;
module = {
initialize: function() {
// settings grabbed at run time
module.get.settings();
if(methodInvoked) {
if(instance === undefined) {
module.instantiate();
}
module.invoke(query);
}
else {
module.verbose('Initializing form validation', $module, settings);
module.bindEvents();
module.set.defaults();
module.instantiate();
}
},
instantiate: function() {
module.verbose('Storing instance of module', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
destroy: function() {
module.verbose('Destroying previous module', instance);
module.removeEvents();
$module
.removeData(moduleNamespace)
;
},
refresh: function() {
module.verbose('Refreshing selector cache');
$field = $module.find(selector.field);
$group = $module.find(selector.group);
$message = $module.find(selector.message);
$prompt = $module.find(selector.prompt);
$submit = $module.find(selector.submit);
$clear = $module.find(selector.clear);
$reset = $module.find(selector.reset);
},
submit: function() {
module.verbose('Submitting form', $module);
$module
.submit()
;
},
attachEvents: function(selector, action) {
action = action || 'submit';
$(selector)
.on('click' + eventNamespace, function(event) {
module[action]();
event.preventDefault();
})
;
},
bindEvents: function() {
module.verbose('Attaching form events');
$module
.on('submit' + eventNamespace, module.validate.form)
.on('blur' + eventNamespace, selector.field, module.event.field.blur)
.on('click' + eventNamespace, selector.submit, module.submit)
.on('click' + eventNamespace, selector.reset, module.reset)
.on('click' + eventNamespace, selector.clear, module.clear)
;
if(settings.keyboardShortcuts) {
$module
.on('keydown' + eventNamespace, selector.field, module.event.field.keydown)
;
}
$field
.each(function() {
var
$input = $(this),
type = $input.prop('type'),
inputEvent = module.get.changeEvent(type, $input)
;
$(this)
.on(inputEvent + eventNamespace, module.event.field.change)
;
})
;
},
clear: function() {
$field
.each(function () {
var
$field = $(this),
$element = $field.parent(),
$fieldGroup = $field.closest($group),
$prompt = $fieldGroup.find(selector.prompt),
defaultValue = $field.data(metadata.defaultValue) || '',
isCheckbox = $element.is(selector.uiCheckbox),
isDropdown = $element.is(selector.uiDropdown),
isErrored = $fieldGroup.hasClass(className.error)
;
if(isErrored) {
module.verbose('Resetting error on field', $fieldGroup);
$fieldGroup.removeClass(className.error);
$prompt.remove();
}
if(isDropdown) {
module.verbose('Resetting dropdown value', $element, defaultValue);
$element.dropdown('clear');
}
else if(isCheckbox) {
$field.prop('checked', false);
}
else {
module.verbose('Resetting field value', $field, defaultValue);
$field.val('');
}
})
;
},
reset: function() {
$field
.each(function () {
var
$field = $(this),
$element = $field.parent(),
$fieldGroup = $field.closest($group),
$prompt = $fieldGroup.find(selector.prompt),
defaultValue = $field.data(metadata.defaultValue),
isCheckbox = $element.is(selector.uiCheckbox),
isDropdown = $element.is(selector.uiDropdown),
isErrored = $fieldGroup.hasClass(className.error)
;
if(defaultValue === undefined) {
return;
}
if(isErrored) {
module.verbose('Resetting error on field', $fieldGroup);
$fieldGroup.removeClass(className.error);
$prompt.remove();
}
if(isDropdown) {
module.verbose('Resetting dropdown value', $element, defaultValue);
$element.dropdown('restore defaults');
}
else if(isCheckbox) {
module.verbose('Resetting checkbox value', $element, defaultValue);
$field.prop('checked', defaultValue);
}
else {
module.verbose('Resetting field value', $field, defaultValue);
$field.val(defaultValue);
}
})
;
},
is: {
bracketedRule: function(rule) {
return (rule.type && rule.type.match(settings.regExp.bracket));
},
valid: function() {
var
allValid = true
;
module.verbose('Checking if form is valid');
$.each(validation, function(fieldName, field) {
if( !( module.validate.field(field, fieldName) ) ) {
allValid = false;
}
});
return allValid;
}
},
removeEvents: function() {
$module
.off(eventNamespace)
;
$field
.off(eventNamespace)
;
$submit
.off(eventNamespace)
;
$field
.off(eventNamespace)
;
},
event: {
field: {
keydown: function(event) {
var
$field = $(this),
key = event.which,
keyCode = {
enter : 13,
escape : 27
}
;
if( key == keyCode.escape) {
module.verbose('Escape key pressed blurring field');
$field
.blur()
;
}
if(!event.ctrlKey && key == keyCode.enter && $field.is(selector.input) && $field.not(selector.checkbox).length > 0 ) {
if(!keyHeldDown) {
$field
.one('keyup' + eventNamespace, module.event.field.keyup)
;
module.submit();
module.debug('Enter pressed on input submitting form');
}
keyHeldDown = true;
}
},
keyup: function() {
keyHeldDown = false;
},
blur: function(event) {
var
$field = $(this),
$fieldGroup = $field.closest($group),
validationRules = module.get.validation($field)
;
if( $fieldGroup.hasClass(className.error) ) {
module.debug('Revalidating field', $field, validationRules);
module.validate.form.call(module, event, true);
}
else if(settings.on == 'blur' || settings.on == 'change') {
module.validate.field( validationRules );
}
},
change: function(event) {
var
$field = $(this),
$fieldGroup = $field.closest($group)
;
if(settings.on == 'change' || ( $fieldGroup.hasClass(className.error) && settings.revalidate) ) {
clearTimeout(module.timer);
module.timer = setTimeout(function() {
module.debug('Revalidating field', $field, module.get.validation($field));
module.validate.form.call(module, event, true);
}, settings.delay);
}
}
}
},
get: {
ancillaryValue: function(rule) {
if(!rule.type || !module.is.bracketedRule(rule)) {
return false;
}
return rule.type.match(settings.regExp.bracket)[1] + '';
},
ruleName: function(rule) {
if( module.is.bracketedRule(rule) ) {
return rule.type.replace(rule.type.match(settings.regExp.bracket)[0], '');
}
return rule.type;
},
changeEvent: function(type, $input) {
if(type == 'checkbox' || type == 'radio' || type == 'hidden' || $input.is('select')) {
return 'change';
}
else {
return module.get.inputEvent();
}
},
inputEvent: function() {
return (document.createElement('input').oninput !== undefined)
? 'input'
: (document.createElement('input').onpropertychange !== undefined)
? 'propertychange'
: 'keyup'
;
},
prompt: function(rule, field) {
var
ruleName = module.get.ruleName(rule),
ancillary = module.get.ancillaryValue(rule),
prompt = rule.prompt || settings.prompt[ruleName] || settings.text.unspecifiedRule,
requiresValue = (prompt.search('{value}') !== -1),
requiresName = (prompt.search('{name}') !== -1),
$label,
$field,
name
;
if(requiresName || requiresValue) {
$field = module.get.field(field.identifier);
}
if(requiresValue) {
prompt = prompt.replace('{value}', $field.val());
}
if(requiresName) {
$label = $field.closest(selector.group).find('label').eq(0);
name = ($label.size() == 1)
? $label.text()
: $field.prop('placeholder') || settings.text.unspecifiedField
;
prompt = prompt.replace('{name}', name);
}
prompt = prompt.replace('{identifier}', field.identifier);
prompt = prompt.replace('{ruleValue}', ancillary);
if(!rule.prompt) {
module.verbose('Using default validation prompt for type', prompt, ruleName);
}
return prompt;
},
settings: function() {
if($.isPlainObject(parameters)) {
var
keys = Object.keys(parameters),
isLegacySettings = (keys.length > 0)
? (parameters[keys[0]].identifier !== undefined && parameters[keys[0]].rules !== undefined)
: false,
ruleKeys
;
if(isLegacySettings) {
// 1.x (ducktyped)
settings = $.extend(true, {}, $.fn.form.settings, legacyParameters);
validation = $.extend({}, $.fn.form.settings.defaults, parameters);
module.error(settings.error.oldSyntax, element);
module.verbose('Extending settings from legacy parameters', validation, settings);
}
else {
// 2.x
if(parameters.fields) {
ruleKeys = Object.keys(parameters.fields);
if( typeof parameters.fields[ruleKeys[0]] == 'string' || $.isArray(parameters.fields[ruleKeys[0]]) ) {
$.each(parameters.fields, function(name, rules) {
if(typeof rules == 'string') {
rules = [rules];
}
parameters.fields[name] = {
rules: []
};
$.each(rules, function(index, rule) {
parameters.fields[name].rules.push({ type: rule });
});
});
}
}
settings = $.extend(true, {}, $.fn.form.settings, parameters);
validation = $.extend({}, $.fn.form.settings.defaults, settings.fields);
module.verbose('Extending settings', validation, settings);
}
}
else {
settings = $.fn.form.settings;
validation = $.fn.form.settings.defaults;
module.verbose('Using default form validation', validation, settings);
}
// shorthand
namespace = settings.namespace;
metadata = settings.metadata;
selector = settings.selector;
className = settings.className;
error = settings.error;
moduleNamespace = 'module-' + namespace;
eventNamespace = '.' + namespace;
// grab instance
instance = $module.data(moduleNamespace);
// refresh selector cache
module.refresh();
},
field: function(identifier) {
module.verbose('Finding field with identifier', identifier);
if( $field.filter('#' + identifier).length > 0 ) {
return $field.filter('#' + identifier);
}
else if( $field.filter('[name="' + identifier +'"]').length > 0 ) {
return $field.filter('[name="' + identifier +'"]');
}
else if( $field.filter('[name="' + identifier +'[]"]').length > 0 ) {
return $field.filter('[name="' + identifier +'[]"]');
}
else if( $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]').length > 0 ) {
return $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]');
}
return $('<input/>');
},
fields: function(fields) {
var
$fields = $()
;
$.each(fields, function(index, name) {
$fields = $fields.add( module.get.field(name) );
});
return $fields;
},
validation: function($field) {
var
fieldValidation,
identifier
;
if(!validation) {
return false;
}
$.each(validation, function(fieldName, field) {
identifier = field.identifier || fieldName;
if( module.get.field(identifier)[0] == $field[0] ) {
field.identifier = identifier;
fieldValidation = field;
}
});
return fieldValidation || false;
},
value: function (field) {
var
fields = [],
results
;
fields.push(field);
results = module.get.values.call(element, fields);
return results[field];
},
values: function (fields) {
var
$fields = $.isArray(fields)
? module.get.fields(fields)
: $field,
values = {}
;
$fields.each(function(index, field) {
var
$field = $(field),
type = $field.prop('type'),
name = $field.prop('name'),
value = $field.val(),
isCheckbox = $field.is(selector.checkbox),
isRadio = $field.is(selector.radio),
isMultiple = (name.indexOf('[]') !== -1),
isChecked = (isCheckbox)
? $field.is(':checked')
: false
;
if(name) {
if(isMultiple) {
name = name.replace('[]', '');
if(!values[name]) {
values[name] = [];
}
if(isCheckbox) {
if(isChecked) {
values[name].push(value || true);
}
else {
values[name].push(false);
}
}
else {
values[name].push(value);
}
}
else {
if(isRadio) {
if(isChecked) {
values[name] = value;
}
}
else if(isCheckbox) {
if(isChecked) {
values[name] = value || true;
}
else {
values[name] = false;
}
}
else {
values[name] = value;
}
}
}
});
return values;
}
},
has: {
field: function(identifier) {
module.verbose('Checking for existence of a field with identifier', identifier);
if(typeof identifier !== 'string') {
module.error(error.identifier, identifier);
}
if( $field.filter('#' + identifier).length > 0 ) {
return true;
}
else if( $field.filter('[name="' + identifier +'"]').length > 0 ) {
return true;
}
else if( $field.filter('[data-' + metadata.validate + '="'+ identifier +'"]').length > 0 ) {
return true;
}
return false;
}
},
add: {
prompt: function(identifier, errors) {
var
$field = module.get.field(identifier),
$fieldGroup = $field.closest($group),
$prompt = $fieldGroup.children(selector.prompt),
promptExists = ($prompt.length !== 0)
;
errors = (typeof errors == 'string')
? [errors]
: errors
;
module.verbose('Adding field error state', identifier);
$fieldGroup
.addClass(className.error)
;
if(settings.inline) {
if(!promptExists) {
$prompt = settings.templates.prompt(errors);
$prompt
.appendTo($fieldGroup)
;
}
$prompt
.html(errors[0])
;
if(!promptExists) {
if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
module.verbose('Displaying error with css transition', settings.transition);
$prompt.transition(settings.transition + ' in', settings.duration);
}
else {
module.verbose('Displaying error with fallback javascript animation');
$prompt
.fadeIn(settings.duration)
;
}
}
else {
module.verbose('Inline errors are disabled, no inline error added', identifier);
}
}
},
errors: function(errors) {
module.debug('Adding form error messages', errors);
module.set.error();
$message
.html( settings.templates.error(errors) )
;
}
},
remove: {
prompt: function(identifier) {
var
$field = module.get.field(identifier),
$fieldGroup = $field.closest($group),
$prompt = $fieldGroup.children(selector.prompt)
;
$fieldGroup
.removeClass(className.error)
;
if(settings.inline && $prompt.is(':visible')) {
module.verbose('Removing prompt for field', identifier);
if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
$prompt.transition(settings.transition + ' out', settings.duration, function() {
$prompt.remove();
});
}
else {
$prompt
.fadeOut(settings.duration, function(){
$prompt.remove();
})
;
}
}
}
},
set: {
success: function() {
$module
.removeClass(className.error)
.addClass(className.success)
;
},
defaults: function () {
$field
.each(function () {
var
$field = $(this),
isCheckbox = ($field.filter(selector.checkbox).length > 0),
value = (isCheckbox)
? $field.is(':checked')
: $field.val()
;
$field.data(metadata.defaultValue, value);
})
;
},
error: function() {
$module
.removeClass(className.success)
.addClass(className.error)
;
},
value: function (field, value) {
var
fields = {}
;
fields[field] = value;
return module.set.values.call(element, fields);
},
values: function (fields) {
if($.isEmptyObject(fields)) {
return;
}
$.each(fields, function(key, value) {
var
$field = module.get.field(key),
$element = $field.parent(),
isMultiple = $.isArray(value),
isCheckbox = $element.is(selector.uiCheckbox),
isDropdown = $element.is(selector.uiDropdown),
isRadio = ($field.is(selector.radio) && isCheckbox),
fieldExists = ($field.length > 0),
$multipleField
;
if(fieldExists) {
if(isMultiple && isCheckbox) {
module.verbose('Selecting multiple', value, $field);
$element.checkbox('uncheck');
$.each(value, function(index, value) {
$multipleField = $field.filter('[value="' + value + '"]');
$element = $multipleField.parent();
if($multipleField.length > 0) {
$element.checkbox('check');
}
});
}
else if(isRadio) {
module.verbose('Selecting radio value', value, $field);
$field.filter('[value="' + value + '"]')
.parent(selector.uiCheckbox)
.checkbox('check')
;
}
else if(isCheckbox) {
module.verbose('Setting checkbox value', value, $element);
if(value === true) {
$element.checkbox('check');
}
else {
$element.checkbox('uncheck');
}
}
else if(isDropdown) {
module.verbose('Setting dropdown value', value, $element);
$element.dropdown('set selected', value);
}
else {
module.verbose('Setting field value', value, $field);
$field.val(value);
}
}
});
}
},
validate: {
form: function(event, ignoreCallbacks) {
var
values = module.get.values(),
apiRequest
;
// input keydown event will fire submit repeatedly by browser default
if(keyHeldDown) {
return false;
}
// reset errors
formErrors = [];
if( module.is.valid() ) {
module.debug('Form has no validation errors, submitting');
module.set.success();
if(ignoreCallbacks !== true) {
return settings.onSuccess.call(element, event, values);
}
}
else {
module.debug('Form has errors');
module.set.error();
if(!settings.inline) {
module.add.errors(formErrors);
}
// prevent ajax submit
if($module.data('moduleApi') !== undefined) {
event.stopImmediatePropagation();
}
if(ignoreCallbacks !== true) {
return settings.onFailure.call(element, formErrors, values);
}
}
},
// takes a validation object and returns whether field passes validation
field: function(field, fieldName) {
var
identifier = field.identifier || fieldName,
$field = module.get.field(identifier),
fieldValid = true,
fieldErrors = []
;
if(!field.identifier) {
module.debug('Using field name as identifier', identifier);
field.identifier = identifier;
}
if($field.prop('disabled')) {
module.debug('Field is disabled. Skipping', identifier);
fieldValid = true;
}
else if(field.optional && $.trim($field.val()) === ''){
module.debug('Field is optional and empty. Skipping', identifier);
fieldValid = true;
}
else if(field.rules !== undefined) {
$.each(field.rules, function(index, rule) {
if( module.has.field(identifier) && !( module.validate.rule(field, rule) ) ) {
module.debug('Field is invalid', identifier, rule.type);
fieldErrors.push(module.get.prompt(rule, field));
fieldValid = false;
}
});
}
if(fieldValid) {
module.remove.prompt(identifier, fieldErrors);
settings.onValid.call($field);
}
else {
formErrors = formErrors.concat(fieldErrors);
module.add.prompt(identifier, fieldErrors);
settings.onInvalid.call($field, fieldErrors);
return false;
}
return true;
},
// takes validation rule and returns whether field passes rule
rule: function(field, rule) {
var
$field = module.get.field(field.identifier),
type = rule.type,
value = $field.val(),
isValid = true,
ancillary = module.get.ancillaryValue(rule),
ruleName = module.get.ruleName(rule),
ruleFunction = settings.rules[ruleName]
;
if( !$.isFunction(ruleFunction) ) {
module.error(error.noRule, ruleName);
return;
}
// cast to string avoiding encoding special values
value = (value === undefined || value === '' || value === null)
? ''
: $.trim(value + '')
;
return ruleFunction.call($field, value, ancillary);
}
},
setting: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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 = [];
}
},
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($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
module.initialize();
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.form.settings = {
name : 'Form',
namespace : 'form',
debug : false,
verbose : false,
performance : true,
fields : false,
keyboardShortcuts : true,
on : 'submit',
inline : false,
delay : 200,
revalidate : true,
transition : 'scale',
duration : 200,
onValid : function() {},
onInvalid : function() {},
onSuccess : function() { return true; },
onFailure : function() { return false; },
metadata : {
defaultValue : 'default',
validate : 'validate'
},
regExp: {
bracket : /\[(.*)\]/i,
decimal : /^\-?\d*(\.\d+)?$/,
email : "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?",
escape : /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,
flags : /^\/(.*)\/(.*)?/,
integer : /^\-?\d+$/,
number : /^\-?\d*(\.\d+)?$/,
url : /(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/i
},
text: {
unspecifiedRule : 'Please enter a valid value',
unspecifiedField : 'This field'
},
prompt: {
empty : '{name} must have a value',
checked : '{name} must be checked',
email : '{name} must be a valid e-mail',
url : '{name} must be a valid url',
regExp : '{name} is not formatted correctly',
integer : '{name} must be an integer',
decimal : '{name} must be a decimal number',
number : '{name} must be set to a number',
is : '{name} must be "{ruleValue}"',
isExactly : '{name} must be exactly "{ruleValue}"',
not : '{name} cannot be set to "{ruleValue}"',
notExactly : '{name} cannot be set to exactly "{ruleValue}"',
contain : '{name} cannot contain "{ruleValue}"',
containExactly : '{name} cannot contain exactly "{ruleValue}"',
doesntContain : '{name} must contain "{ruleValue}"',
doesntContainExactly : '{name} must contain exactly "{ruleValue}"',
minLength : '{name} must be at least {ruleValue} characters',
length : '{name} must be at least {ruleValue} characters',
exactLength : '{name} must be exactly {ruleValue} characters',
maxLength : '{name} cannot be longer than {ruleValue} characters',
match : '{name} must match {ruleValue} field',
different : '{name} must have a different value than {ruleValue} field',
creditCard : '{name} must be a valid credit card number',
minCount : '{name} must have at least {ruleValue} choices',
exactCount : '{name} must have exactly {ruleValue} choices',
maxCount : '{name} must have {ruleValue} or less choices'
},
selector : {
checkbox : 'input[type="checkbox"], input[type="radio"]',
clear : '.clear',
field : 'input, textarea, select',
group : '.field',
input : 'input',
message : '.error.message',
prompt : '.prompt.label',
radio : 'input[type="radio"]',
reset : '.reset:not([type="reset"])',
submit : '.submit:not([type="submit"])',
uiCheckbox : '.ui.checkbox',
uiDropdown : '.ui.dropdown'
},
className : {
error : 'error',
label : 'ui prompt label',
pressed : 'down',
success : 'success'
},
error: {
identifier : 'You must specify a string identifier for each field',
method : 'The method you called is not defined.',
noRule : 'There is no rule matching the one you specified',
oldSyntax : 'Starting in 2.0 forms now only take a single settings object. Validation settings converted to new syntax automatically.'
},
templates: {
// template that produces error message
error: function(errors) {
var
html = '<ul class="list">'
;
$.each(errors, function(index, value) {
html += '<li>' + value + '</li>';
});
html += '</ul>';
return $(html);
},
// template that produces label
prompt: function(errors) {
return $('<div/>')
.addClass('ui basic red pointing prompt label')
.html(errors[0])
;
}
},
rules: {
// is not empty or blank string
empty: function(value) {
return !(value === undefined || '' === value || $.isArray(value) && value.length === 0);
},
// checkbox checked
checked: function() {
return ($(this).filter(':checked').length > 0);
},
// is most likely an email
email: function(value){
var
emailRegExp = new RegExp($.fn.form.settings.regExp.email, 'i')
;
return emailRegExp.test(value);
},
// value is most likely url
url: function(value) {
return $.fn.form.settings.regExp.url.test(value);
},
// matches specified regExp
regExp: function(value, regExp) {
var
regExpParts = regExp.match($.fn.form.settings.regExp.flags),
flags
;
// regular expression specified as /baz/gi (flags)
if(regExpParts) {
regExp = (regExpParts.length >= 2)
? regExpParts[1]
: regExp
;
flags = (regExpParts.length >= 3)
? regExpParts[2]
: ''
;
}
return value.match( new RegExp(regExp, flags) );
},
// is valid integer or matches range
integer: function(value, range) {
var
intRegExp = $.fn.form.settings.regExp.integer,
min,
max,
parts
;
if(range === undefined || range === '' || range === '..') {
// do nothing
}
else if(range.indexOf('..') == -1) {
if(intRegExp.test(range)) {
min = max = range - 0;
}
}
else {
parts = range.split('..', 2);
if(intRegExp.test(parts[0])) {
min = parts[0] - 0;
}
if(intRegExp.test(parts[1])) {
max = parts[1] - 0;
}
}
return (
intRegExp.test(value) &&
(min === undefined || value >= min) &&
(max === undefined || value <= max)
);
},
// is valid number (with decimal)
decimal: function(value) {
return $.fn.form.settings.regExp.decimal.test(value);
},
// is valid number
number: function(value) {
return $.fn.form.settings.regExp.number.test(value);
},
// is value (case insensitive)
is: function(value, text) {
text = (typeof text == 'string')
? text.toLowerCase()
: text
;
value = (typeof value == 'string')
? value.toLowerCase()
: value
;
return (value == text);
},
// is value
isExactly: function(value, text) {
return (value == text);
},
// value is not another value (case insensitive)
not: function(value, notValue) {
value = (typeof value == 'string')
? value.toLowerCase()
: value
;
notValue = (typeof notValue == 'string')
? notValue.toLowerCase()
: notValue
;
return (value != notValue);
},
// value is not another value (case sensitive)
notExactly: function(value, notValue) {
return (value != notValue);
},
// value contains text (insensitive)
contains: function(value, text) {
// escape regex characters
text = text.replace($.fn.form.settings.regExp.escape, "\\$&");
return (value.search( new RegExp(text, 'i') ) !== -1);
},
// value contains text (case sensitive)
containsExactly: function(value, text) {
// escape regex characters
text = text.replace($.fn.form.settings.regExp.escape, "\\$&");
return (value.search( new RegExp(text) ) !== -1);
},
// value contains text (insensitive)
doesntContain: function(value, text) {
// escape regex characters
text = text.replace($.fn.form.settings.regExp.escape, "\\$&");
return (value.search( new RegExp(text, 'i') ) === -1);
},
// value contains text (case sensitive)
doesntContainExactly: function(value, text) {
// escape regex characters
text = text.replace($.fn.form.settings.regExp.escape, "\\$&");
return (value.search( new RegExp(text) ) === -1);
},
// is at least string length
minLength: function(value, requiredLength) {
return (value !== undefined)
? (value.length >= requiredLength)
: false
;
},
// see rls notes for 2.0.6 (this is a duplicate of minLength)
length: function(value, requiredLength) {
return (value !== undefined)
? (value.length >= requiredLength)
: false
;
},
// is exactly length
exactLength: function(value, requiredLength) {
return (value !== undefined)
? (value.length == requiredLength)
: false
;
},
// is less than length
maxLength: function(value, maxLength) {
return (value !== undefined)
? (value.length <= maxLength)
: false
;
},
// matches another field
match: function(value, identifier) {
var
$form = $(this),
matchingValue
;
if( $('[data-validate="'+ identifier +'"]').length > 0 ) {
matchingValue = $('[data-validate="'+ identifier +'"]').val();
}
else if($('#' + identifier).length > 0) {
matchingValue = $('#' + identifier).val();
}
else if($('[name="' + identifier +'"]').length > 0) {
matchingValue = $('[name="' + identifier + '"]').val();
}
else if( $('[name="' + identifier +'[]"]').length > 0 ) {
matchingValue = $('[name="' + identifier +'[]"]');
}
return (matchingValue !== undefined)
? ( value.toString() == matchingValue.toString() )
: false
;
},
// different than another field
different: function(value, identifier) {
// use either id or name of field
var
$form = $(this),
matchingValue
;
if( $('[data-validate="'+ identifier +'"]').length > 0 ) {
matchingValue = $('[data-validate="'+ identifier +'"]').val();
}
else if($('#' + identifier).length > 0) {
matchingValue = $('#' + identifier).val();
}
else if($('[name="' + identifier +'"]').length > 0) {
matchingValue = $('[name="' + identifier + '"]').val();
}
else if( $('[name="' + identifier +'[]"]').length > 0 ) {
matchingValue = $('[name="' + identifier +'[]"]');
}
return (matchingValue !== undefined)
? ( value.toString() !== matchingValue.toString() )
: false
;
},
creditCard: function(cardNumber, cardTypes) {
var
cards = {
visa: {
pattern : /^4/,
length : [16]
},
amex: {
pattern : /^3[47]/,
length : [15]
},
mastercard: {
pattern : /^5[1-5]/,
length : [16]
},
discover: {
pattern : /^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)/,
length : [16]
},
unionPay: {
pattern : /^(62|88)/,
length : [16, 17, 18, 19]
},
jcb: {
pattern : /^35(2[89]|[3-8][0-9])/,
length : [16]
},
maestro: {
pattern : /^(5018|5020|5038|6304|6759|676[1-3])/,
length : [12, 13, 14, 15, 16, 17, 18, 19]
},
dinersClub: {
pattern : /^(30[0-5]|^36)/,
length : [14]
},
laser: {
pattern : /^(6304|670[69]|6771)/,
length : [16, 17, 18, 19]
},
visaElectron: {
pattern : /^(4026|417500|4508|4844|491(3|7))/,
length : [16]
}
},
valid = {},
validCard = false,
requiredTypes = (typeof cardTypes == 'string')
? cardTypes.split(',')
: false,
unionPay,
validation
;
if(typeof cardNumber !== 'string' || cardNumber.length === 0) {
return;
}
// verify card types
if(requiredTypes) {
$.each(requiredTypes, function(index, type){
// verify each card type
validation = cards[type];
if(validation) {
valid = {
length : ($.inArray(cardNumber.length, validation.length) !== -1),
pattern : (cardNumber.search(validation.pattern) !== -1)
};
if(valid.length && valid.pattern) {
validCard = true;
}
}
});
if(!validCard) {
return false;
}
}
// skip luhn for UnionPay
unionPay = {
number : ($.inArray(cardNumber.length, cards.unionPay.length) !== -1),
pattern : (cardNumber.search(cards.unionPay.pattern) !== -1)
};
if(unionPay.number && unionPay.pattern) {
return true;
}
// verify luhn, adapted from <https://gist.github.com/2134376>
var
length = cardNumber.length,
multiple = 0,
producedValue = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 2, 4, 6, 8, 1, 3, 5, 7, 9]
],
sum = 0
;
while (length--) {
sum += producedValue[multiple][parseInt(cardNumber.charAt(length), 10)];
multiple ^= 1;
}
return (sum % 10 === 0 && sum > 0);
},
minCount: function(value, minCount) {
if(minCount == 0) {
return true;
}
if(minCount == 1) {
return (value !== '');
}
return (value.split(',').length >= minCount);
},
exactCount: function(value, exactCount) {
if(exactCount == 0) {
return (value === '');
}
if(exactCount == 1) {
return (value !== '' && value.search(',') === -1);
}
return (value.split(',').length == exactCount);
},
maxCount: function(value, maxCount) {
if(maxCount == 0) {
return false;
}
if(maxCount == 1) {
return (value.search(',') === -1);
}
return (value.split(',').length <= maxCount);
}
}
};
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Accordion
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ($, window, document, undefined) {
"use strict";
$.fn.accordion = function(parameters) {
var
$allModules = $(this),
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { setTimeout(callback, 0); },
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.accordion.settings, parameters)
: $.extend({}, $.fn.accordion.settings),
className = settings.className,
namespace = settings.namespace,
selector = settings.selector,
error = settings.error,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
moduleSelector = $allModules.selector || '',
$module = $(this),
$title = $module.find(selector.title),
$content = $module.find(selector.content),
element = this,
instance = $module.data(moduleNamespace),
observer,
module
;
module = {
initialize: function() {
module.debug('Initializing', $module);
module.bind.events();
if(settings.observeChanges) {
module.observeChanges();
}
module.instantiate();
},
instantiate: function() {
instance = module;
$module
.data(moduleNamespace, module)
;
},
destroy: function() {
module.debug('Destroying previous instance', $module);
$module
.off(eventNamespace)
.removeData(moduleNamespace)
;
},
refresh: function() {
$title = $module.find(selector.title);
$content = $module.find(selector.content);
},
observeChanges: function() {
if('MutationObserver' in window) {
observer = new MutationObserver(function(mutations) {
module.debug('DOM tree modified, updating selector cache');
module.refresh();
});
observer.observe(element, {
childList : true,
subtree : true
});
module.debug('Setting up mutation observer', observer);
}
},
bind: {
events: function() {
module.debug('Binding delegated events');
$module
.on(settings.on + eventNamespace, selector.trigger, module.event.click)
;
}
},
event: {
click: function() {
module.toggle.call(this);
}
},
toggle: function(query) {
var
$activeTitle = (query !== undefined)
? (typeof query === 'number')
? $title.eq(query)
: $(query).closest(selector.title)
: $(this).closest(selector.title),
$activeContent = $activeTitle.next($content),
isAnimating = $activeContent.hasClass(className.animating),
isActive = $activeContent.hasClass(className.active),
isOpen = (isActive && !isAnimating),
isOpening = (!isActive && isAnimating)
;
module.debug('Toggling visibility of content', $activeTitle);
if(isOpen || isOpening) {
if(settings.collapsible) {
module.close.call($activeTitle);
}
else {
module.debug('Cannot close accordion content collapsing is disabled');
}
}
else {
module.open.call($activeTitle);
}
},
open: function(query) {
var
$activeTitle = (query !== undefined)
? (typeof query === 'number')
? $title.eq(query)
: $(query).closest(selector.title)
: $(this).closest(selector.title),
$activeContent = $activeTitle.next($content),
isAnimating = $activeContent.hasClass(className.animating),
isActive = $activeContent.hasClass(className.active),
isOpen = (isActive || isAnimating)
;
if(isOpen) {
module.debug('Accordion already open, skipping', $activeContent);
return;
}
module.debug('Opening accordion content', $activeTitle);
settings.onOpening.call($activeContent);
if(settings.exclusive) {
module.closeOthers.call($activeTitle);
}
$activeTitle
.addClass(className.active)
;
$activeContent
.stop(true, true)
.addClass(className.animating)
;
if(settings.animateChildren) {
if($.fn.transition !== undefined && $module.transition('is supported')) {
$activeContent
.children()
.transition({
animation : 'fade in',
queue : false,
useFailSafe : true,
debug : settings.debug,
verbose : settings.verbose,
duration : settings.duration
})
;
}
else {
$activeContent
.children()
.stop(true, true)
.animate({
opacity: 1
}, settings.duration, module.resetOpacity)
;
}
}
$activeContent
.slideDown(settings.duration, settings.easing, function() {
$activeContent
.removeClass(className.animating)
.addClass(className.active)
;
module.reset.display.call(this);
settings.onOpen.call(this);
settings.onChange.call(this);
})
;
},
close: function(query) {
var
$activeTitle = (query !== undefined)
? (typeof query === 'number')
? $title.eq(query)
: $(query).closest(selector.title)
: $(this).closest(selector.title),
$activeContent = $activeTitle.next($content),
isAnimating = $activeContent.hasClass(className.animating),
isActive = $activeContent.hasClass(className.active),
isOpening = (!isActive && isAnimating),
isClosing = (isActive && isAnimating)
;
if((isActive || isOpening) && !isClosing) {
module.debug('Closing accordion content', $activeContent);
settings.onClosing.call($activeContent);
$activeTitle
.removeClass(className.active)
;
$activeContent
.stop(true, true)
.addClass(className.animating)
;
if(settings.animateChildren) {
if($.fn.transition !== undefined && $module.transition('is supported')) {
$activeContent
.children()
.transition({
animation : 'fade out',
queue : false,
useFailSafe : true,
debug : settings.debug,
verbose : settings.verbose,
duration : settings.duration
})
;
}
else {
$activeContent
.children()
.stop(true, true)
.animate({
opacity: 0
}, settings.duration, module.resetOpacity)
;
}
}
$activeContent
.slideUp(settings.duration, settings.easing, function() {
$activeContent
.removeClass(className.animating)
.removeClass(className.active)
;
module.reset.display.call(this);
settings.onClose.call(this);
settings.onChange.call(this);
})
;
}
},
closeOthers: function(index) {
var
$activeTitle = (index !== undefined)
? $title.eq(index)
: $(this).closest(selector.title),
$parentTitles = $activeTitle.parents(selector.content).prev(selector.title),
$activeAccordion = $activeTitle.closest(selector.accordion),
activeSelector = selector.title + '.' + className.active + ':visible',
activeContent = selector.content + '.' + className.active + ':visible',
$openTitles,
$nestedTitles,
$openContents
;
if(settings.closeNested) {
$openTitles = $activeAccordion.find(activeSelector).not($parentTitles);
$openContents = $openTitles.next($content);
}
else {
$openTitles = $activeAccordion.find(activeSelector).not($parentTitles);
$nestedTitles = $activeAccordion.find(activeContent).find(activeSelector).not($parentTitles);
$openTitles = $openTitles.not($nestedTitles);
$openContents = $openTitles.next($content);
}
if( ($openTitles.length > 0) ) {
module.debug('Exclusive enabled, closing other content', $openTitles);
$openTitles
.removeClass(className.active)
;
$openContents
.removeClass(className.animating)
.stop(true, true)
;
if(settings.animateChildren) {
if($.fn.transition !== undefined && $module.transition('is supported')) {
$openContents
.children()
.transition({
animation : 'fade out',
useFailSafe : true,
debug : settings.debug,
verbose : settings.verbose,
duration : settings.duration
})
;
}
else {
$openContents
.children()
.stop(true, true)
.animate({
opacity: 0
}, settings.duration, module.resetOpacity)
;
}
}
$openContents
.slideUp(settings.duration , settings.easing, function() {
$(this).removeClass(className.active);
module.reset.display.call(this);
})
;
}
},
reset: {
display: function() {
module.verbose('Removing inline display from element', this);
$(this).css('display', '');
if( $(this).attr('style') === '') {
$(this)
.attr('style', '')
.removeAttr('style')
;
}
},
opacity: function() {
module.verbose('Removing inline opacity from element', this);
$(this).css('opacity', '');
if( $(this).attr('style') === '') {
$(this)
.attr('style', '')
.removeAttr('style')
;
}
},
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
settings[name] = value;
}
else {
return settings[name];
}
},
internal: function(name, value) {
module.debug('Changing internal', name, value);
if(value !== undefined) {
if( $.isPlainObject(name) ) {
$.extend(true, module, name);
}
else {
module[name] = value;
}
}
else {
return module[name];
}
},
debug: function() {
if(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.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() {
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( (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 = [];
}
},
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 {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.accordion.settings = {
name : 'Accordion',
namespace : 'accordion',
debug : false,
verbose : false,
performance : true,
on : 'click', // event on title that opens accordion
observeChanges : true, // whether accordion should automatically refresh on DOM insertion
exclusive : true, // whether a single accordion content panel should be open at once
collapsible : true, // whether accordion content can be closed
closeNested : false, // whether nested content should be closed when a panel is closed
animateChildren : true, // whether children opacity should be animated
duration : 350, // duration of animation
easing : 'easeOutQuad', // easing equation for animation
onOpening : function(){}, // callback before open animation
onOpen : function(){}, // callback after open animation
onClosing : function(){}, // callback before closing animation
onClose : function(){}, // callback after closing animation
onChange : function(){}, // callback after closing or opening animation
error: {
method : 'The method you called is not defined'
},
className : {
active : 'active',
animating : 'animating'
},
selector : {
accordion : '.accordion',
title : '.title',
trigger : '.title',
content : '.content'
}
};
// Adds easing
$.extend( $.easing, {
easeOutQuad: function (x, t, b, c, d) {
return -c *(t/=d)*(t-2) + b;
}
});
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Checkbox
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.fn.checkbox = function(parameters) {
var
$allModules = $(this),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
settings = $.extend(true, {}, $.fn.checkbox.settings, parameters),
className = settings.className,
namespace = settings.namespace,
selector = settings.selector,
error = settings.error,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
$module = $(this),
$label = $(this).children(selector.label),
$input = $(this).children(selector.input),
input = $input[0],
initialLoad = false,
shortcutPressed = false,
instance = $module.data(moduleNamespace),
observer,
element = this,
module
;
module = {
initialize: function() {
module.verbose('Initializing checkbox', settings);
module.create.label();
module.bind.events();
module.set.tabbable();
module.hide.input();
module.observeChanges();
module.instantiate();
module.setup();
},
instantiate: function() {
module.verbose('Storing instance of module', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
destroy: function() {
module.verbose('Destroying module');
module.unbind.events();
module.show.input();
$module.removeData(moduleNamespace);
},
fix: {
reference: function() {
if( $module.is(selector.input) ) {
module.debug('Behavior called on <input> adjusting invoked element');
$module = $module.closest(selector.checkbox);
module.refresh();
}
}
},
setup: function() {
module.set.initialLoad();
if( module.is.indeterminate() ) {
module.debug('Initial value is indeterminate');
module.indeterminate();
}
else if( module.is.checked() ) {
module.debug('Initial value is checked');
module.check();
}
else {
module.debug('Initial value is unchecked');
module.uncheck();
}
module.remove.initialLoad();
},
refresh: function() {
$label = $module.children(selector.label);
$input = $module.children(selector.input);
input = $input[0];
},
hide: {
input: function() {
module.verbose('Modfying <input> z-index to be unselectable');
$input.addClass(className.hidden);
}
},
show: {
input: function() {
module.verbose('Modfying <input> z-index to be selectable');
$input.removeClass(className.hidden);
}
},
observeChanges: function() {
if('MutationObserver' in window) {
observer = new MutationObserver(function(mutations) {
module.debug('DOM tree modified, updating selector cache');
module.refresh();
});
observer.observe(element, {
childList : true,
subtree : true
});
module.debug('Setting up mutation observer', observer);
}
},
attachEvents: function(selector, event) {
var
$element = $(selector)
;
event = $.isFunction(module[event])
? module[event]
: module.toggle
;
if($element.length > 0) {
module.debug('Attaching checkbox events to element', selector, event);
$element
.on('click' + eventNamespace, event)
;
}
else {
module.error(error.notFound);
}
},
event: {
click: function(event) {
var
$target = $(event.target)
;
if( $target.is(selector.input) ) {
module.verbose('Using default check action on initialized checkbox');
return;
}
if( $target.is(selector.link) ) {
module.debug('Clicking link inside checkbox, skipping toggle');
return;
}
module.toggle();
$input.focus();
event.preventDefault();
},
keydown: function(event) {
var
key = event.which,
keyCode = {
enter : 13,
space : 32,
escape : 27
}
;
if(key == keyCode.escape) {
module.verbose('Escape key pressed blurring field');
$input.blur();
shortcutPressed = true;
}
else if(!event.ctrlKey && ( key == keyCode.space || key == keyCode.enter) ) {
module.verbose('Enter/space key pressed, toggling checkbox');
module.toggle();
shortcutPressed = true;
}
else {
shortcutPressed = false;
}
},
keyup: function(event) {
if(shortcutPressed) {
event.preventDefault();
}
}
},
check: function() {
if( !module.should.allowCheck() ) {
return;
}
module.debug('Checking checkbox', $input);
module.set.checked();
if( !module.should.ignoreCallbacks() ) {
settings.onChecked.call(input);
settings.onChange.call(input);
}
},
uncheck: function() {
if( !module.should.allowUncheck() ) {
return;
}
module.debug('Unchecking checkbox');
module.set.unchecked();
if( !module.should.ignoreCallbacks() ) {
settings.onUnchecked.call(input);
settings.onChange.call(input);
}
},
indeterminate: function() {
if( module.should.allowIndeterminate() ) {
module.debug('Checkbox is already indeterminate');
return;
}
module.debug('Making checkbox indeterminate');
module.set.indeterminate();
if( !module.should.ignoreCallbacks() ) {
settings.onIndeterminate.call(input);
settings.onChange.call(input);
}
},
determinate: function() {
if( module.should.allowDeterminate() ) {
module.debug('Checkbox is already determinate');
return;
}
module.debug('Making checkbox determinate');
module.set.determinate();
if( !module.should.ignoreCallbacks() ) {
settings.onDeterminate.call(input);
settings.onChange.call(input);
}
},
enable: function() {
if( module.is.enabled() ) {
module.debug('Checkbox is already enabled');
return;
}
module.debug('Enabling checkbox');
module.set.enabled();
settings.onEnable.call(input);
},
disable: function() {
if( module.is.disabled() ) {
module.debug('Checkbox is already disabled');
return;
}
module.debug('Disabling checkbox');
module.set.disabled();
settings.onDisable.call(input);
},
get: {
radios: function() {
var
name = module.get.name()
;
return $('input[name="' + name + '"]').closest(selector.checkbox);
},
otherRadios: function() {
return module.get.radios().not($module);
},
name: function() {
return $input.attr('name');
}
},
is: {
initialLoad: function() {
return initialLoad;
},
radio: function() {
return ($input.hasClass(className.radio) || $input.attr('type') == 'radio');
},
indeterminate: function() {
return $input.prop('indeterminate') !== undefined && $input.prop('indeterminate');
},
checked: function() {
return $input.prop('checked') !== undefined && $input.prop('checked');
},
disabled: function() {
return $input.prop('disabled') !== undefined && $input.prop('disabled');
},
enabled: function() {
return !module.is.disabled();
},
determinate: function() {
return !module.is.indeterminate();
},
unchecked: function() {
return !module.is.checked();
}
},
should: {
allowCheck: function() {
if(module.is.determinate() && module.is.checked() && !module.should.forceCallbacks() ) {
module.debug('Should not allow check, checkbox is already checked');
return false;
}
if(settings.beforeChecked.apply(input) === false) {
module.debug('Should not allow check, beforeChecked cancelled');
return false;
}
return true;
},
allowUncheck: function() {
if(module.is.determinate() && module.is.unchecked() && !module.should.forceCallbacks() ) {
module.debug('Should not allow uncheck, checkbox is already unchecked');
return false;
}
if(settings.beforeUnchecked.apply(input) === false) {
module.debug('Should not allow uncheck, beforeUnchecked cancelled');
return false;
}
return true;
},
allowIndeterminate: function() {
if(module.is.indeterminate() && !module.should.forceCallbacks() ) {
module.debug('Should not allow indeterminate, checkbox is already indeterminate');
return false;
}
if(settings.beforeIndeterminate.apply(input) === false) {
module.debug('Should not allow indeterminate, beforeIndeterminate cancelled');
return false;
}
return true;
},
allowDeterminate: function() {
if(module.is.determinate() && !module.should.forceCallbacks() ) {
module.debug('Should not allow determinate, checkbox is already determinate');
return false;
}
if(settings.beforeDeterminate.apply(input) === false) {
module.debug('Should not allow determinate, beforeDeterminate cancelled');
return false;
}
return true;
},
forceCallbacks: function() {
return (module.is.initialLoad() && settings.fireOnInit);
},
ignoreCallbacks: function() {
return (initialLoad && !settings.fireOnInit);
}
},
can: {
change: function() {
return !( $module.hasClass(className.disabled) || $module.hasClass(className.readOnly) || $input.prop('disabled') || $input.prop('readonly') );
},
uncheck: function() {
return (typeof settings.uncheckable === 'boolean')
? settings.uncheckable
: !module.is.radio()
;
}
},
set: {
initialLoad: function() {
initialLoad = true;
},
checked: function() {
module.verbose('Setting class to checked');
$module
.removeClass(className.indeterminate)
.addClass(className.checked)
;
if( module.is.radio() ) {
module.uncheckOthers();
}
if(!module.is.indeterminate() && module.is.checked()) {
module.debug('Input is already checked, skipping input property change');
return;
}
module.verbose('Setting state to checked', input);
$input
.prop('indeterminate', false)
.prop('checked', true)
;
module.trigger.change();
},
unchecked: function() {
module.verbose('Removing checked class');
$module
.removeClass(className.indeterminate)
.removeClass(className.checked)
;
if(!module.is.indeterminate() && module.is.unchecked() ) {
module.debug('Input is already unchecked');
return;
}
module.debug('Setting state to unchecked');
$input
.prop('indeterminate', false)
.prop('checked', false)
;
module.trigger.change();
},
indeterminate: function() {
module.verbose('Setting class to indeterminate');
$module
.addClass(className.indeterminate)
;
if( module.is.indeterminate() ) {
module.debug('Input is already indeterminate, skipping input property change');
return;
}
module.debug('Setting state to indeterminate');
$input
.prop('indeterminate', true)
;
module.trigger.change();
},
determinate: function() {
module.verbose('Removing indeterminate class');
$module
.removeClass(className.indeterminate)
;
if( module.is.determinate() ) {
module.debug('Input is already determinate, skipping input property change');
return;
}
module.debug('Setting state to determinate');
$input
.prop('indeterminate', false)
;
},
disabled: function() {
module.verbose('Setting class to disabled');
$module
.addClass(className.disabled)
;
if( module.is.disabled() ) {
module.debug('Input is already disabled, skipping input property change');
return;
}
module.debug('Setting state to disabled');
$input
.prop('disabled', 'disabled')
;
module.trigger.change();
},
enabled: function() {
module.verbose('Removing disabled class');
$module.removeClass(className.disabled);
if( module.is.enabled() ) {
module.debug('Input is already enabled, skipping input property change');
return;
}
module.debug('Setting state to enabled');
$input
.prop('disabled', false)
;
module.trigger.change();
},
tabbable: function() {
module.verbose('Adding tabindex to checkbox');
if( $input.attr('tabindex') === undefined) {
$input.attr('tabindex', 0);
}
}
},
remove: {
initialLoad: function() {
initialLoad = false;
}
},
trigger: {
change: function() {
module.verbose('Triggering change event from programmatic change');
$input
.trigger('change')
;
}
},
create: {
label: function() {
if($input.prevAll(selector.label).length > 0) {
$input.prev(selector.label).detach().insertAfter($input);
module.debug('Moving existing label', $label);
}
else if( !module.has.label() ) {
$label = $('<label>').insertAfter($input);
module.debug('Creating label', $label);
}
}
},
has: {
label: function() {
return ($label.length > 0);
}
},
bind: {
events: function() {
module.verbose('Attaching checkbox events');
$module
.on('click' + eventNamespace, module.event.click)
.on('keydown' + eventNamespace, selector.input, module.event.keydown)
.on('keyup' + eventNamespace, selector.input, module.event.keyup)
;
}
},
unbind: {
events: function() {
module.debug('Removing events');
$module
.off(eventNamespace)
;
}
},
uncheckOthers: function() {
var
$radios = module.get.otherRadios()
;
module.debug('Unchecking other radios', $radios);
$radios.removeClass(className.checked);
},
toggle: function() {
if( !module.can.change() ) {
if(!module.is.radio()) {
module.debug('Checkbox is read-only or disabled, ignoring toggle');
}
return;
}
if( module.is.indeterminate() || module.is.unchecked() ) {
module.debug('Currently unchecked');
module.check();
}
else if( module.is.checked() && module.can.uncheck() ) {
module.debug('Currently checked');
module.uncheck();
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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( (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 = [];
}
},
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 {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.checkbox.settings = {
name : 'Checkbox',
namespace : 'checkbox',
debug : false,
verbose : true,
performance : true,
// delegated event context
uncheckable : 'auto',
fireOnInit : false,
onChange : function(){},
beforeChecked : function(){},
beforeUnchecked : function(){},
beforeDeterminate : function(){},
beforeIndeterminate : function(){},
onChecked : function(){},
onUnchecked : function(){},
onDeterminate : function() {},
onIndeterminate : function() {},
onEnabled : function(){},
onDisabled : function(){},
className : {
checked : 'checked',
indeterminate : 'indeterminate',
disabled : 'disabled',
hidden : 'hidden',
radio : 'radio',
readOnly : 'read-only'
},
error : {
method : 'The method you called is not defined'
},
selector : {
checkbox : '.ui.checkbox',
label : 'label, .box',
input : 'input[type="checkbox"], input[type="radio"]',
link : 'a[href]'
}
};
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Dimmer
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.fn.dimmer = function(parameters) {
var
$allModules = $(this),
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.dimmer.settings, parameters)
: $.extend({}, $.fn.dimmer.settings),
selector = settings.selector,
namespace = settings.namespace,
className = settings.className,
error = settings.error,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
moduleSelector = $allModules.selector || '',
clickEvent = ('ontouchstart' in document.documentElement)
? 'touchstart'
: 'click',
$module = $(this),
$dimmer,
$dimmable,
element = this,
instance = $module.data(moduleNamespace),
module
;
module = {
preinitialize: function() {
if( module.is.dimmer() ) {
$dimmable = $module.parent();
$dimmer = $module;
}
else {
$dimmable = $module;
if( module.has.dimmer() ) {
if(settings.dimmerName) {
$dimmer = $dimmable.find(selector.dimmer).filter('.' + settings.dimmerName);
}
else {
$dimmer = $dimmable.find(selector.dimmer);
}
}
else {
$dimmer = module.create();
}
}
},
initialize: function() {
module.debug('Initializing dimmer', settings);
module.bind.events();
module.set.dimmable();
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of module', module);
instance = module;
$module
.data(moduleNamespace, instance)
;
},
destroy: function() {
module.verbose('Destroying previous module', $dimmer);
module.unbind.events();
module.remove.variation();
$dimmable
.off(eventNamespace)
;
},
bind: {
events: function() {
if(settings.on == 'hover') {
$dimmable
.on('mouseenter' + eventNamespace, module.show)
.on('mouseleave' + eventNamespace, module.hide)
;
}
else if(settings.on == 'click') {
$dimmable
.on(clickEvent + eventNamespace, module.toggle)
;
}
if( module.is.page() ) {
module.debug('Setting as a page dimmer', $dimmable);
module.set.pageDimmer();
}
if( module.is.closable() ) {
module.verbose('Adding dimmer close event', $dimmer);
$dimmable
.on(clickEvent + eventNamespace, selector.dimmer, module.event.click)
;
}
}
},
unbind: {
events: function() {
$module
.removeData(moduleNamespace)
;
}
},
event: {
click: function(event) {
module.verbose('Determining if event occured on dimmer', event);
if( $dimmer.find(event.target).length === 0 || $(event.target).is(selector.content) ) {
module.hide();
event.stopImmediatePropagation();
}
}
},
addContent: function(element) {
var
$content = $(element)
;
module.debug('Add content to dimmer', $content);
if($content.parent()[0] !== $dimmer[0]) {
$content.detach().appendTo($dimmer);
}
},
create: function() {
var
$element = $( settings.template.dimmer() )
;
if(settings.variation) {
module.debug('Creating dimmer with variation', settings.variation);
$element.addClass(settings.variation);
}
if(settings.dimmerName) {
module.debug('Creating named dimmer', settings.dimmerName);
$element.addClass(settings.dimmerName);
}
$element
.appendTo($dimmable)
;
return $element;
},
show: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
module.debug('Showing dimmer', $dimmer, settings);
if( (!module.is.dimmed() || module.is.animating()) && module.is.enabled() ) {
module.animate.show(callback);
settings.onShow.call(element);
settings.onChange.call(element);
}
else {
module.debug('Dimmer is already shown or disabled');
}
},
hide: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if( module.is.dimmed() || module.is.animating() ) {
module.debug('Hiding dimmer', $dimmer);
module.animate.hide(callback);
settings.onHide.call(element);
settings.onChange.call(element);
}
else {
module.debug('Dimmer is not visible');
}
},
toggle: function() {
module.verbose('Toggling dimmer visibility', $dimmer);
if( !module.is.dimmed() ) {
module.show();
}
else {
module.hide();
}
},
animate: {
show: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if(settings.useCSS && $.fn.transition !== undefined && $dimmer.transition('is supported')) {
if(settings.opacity !== 'auto') {
module.set.opacity();
}
$dimmer
.transition({
animation : settings.transition + ' in',
queue : false,
duration : module.get.duration(),
useFailSafe : true,
onStart : function() {
module.set.dimmed();
},
onComplete : function() {
module.set.active();
callback();
}
})
;
}
else {
module.verbose('Showing dimmer animation with javascript');
module.set.dimmed();
if(settings.opacity == 'auto') {
settings.opacity = 0.8;
}
$dimmer
.stop()
.css({
opacity : 0,
width : '100%',
height : '100%'
})
.fadeTo(module.get.duration(), settings.opacity, function() {
$dimmer.removeAttr('style');
module.set.active();
callback();
})
;
}
},
hide: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if(settings.useCSS && $.fn.transition !== undefined && $dimmer.transition('is supported')) {
module.verbose('Hiding dimmer with css');
$dimmer
.transition({
animation : settings.transition + ' out',
queue : false,
duration : module.get.duration(),
useFailSafe : true,
onStart : function() {
module.remove.dimmed();
},
onComplete : function() {
module.remove.active();
callback();
}
})
;
}
else {
module.verbose('Hiding dimmer with javascript');
module.remove.dimmed();
$dimmer
.stop()
.fadeOut(module.get.duration(), function() {
module.remove.active();
$dimmer.removeAttr('style');
callback();
})
;
}
}
},
get: {
dimmer: function() {
return $dimmer;
},
duration: function() {
if(typeof settings.duration == 'object') {
if( module.is.active() ) {
return settings.duration.hide;
}
else {
return settings.duration.show;
}
}
return settings.duration;
}
},
has: {
dimmer: function() {
if(settings.dimmerName) {
return ($module.find(selector.dimmer).filter('.' + settings.dimmerName).length > 0);
}
else {
return ( $module.find(selector.dimmer).length > 0 );
}
}
},
is: {
active: function() {
return $dimmer.hasClass(className.active);
},
animating: function() {
return ( $dimmer.is(':animated') || $dimmer.hasClass(className.animating) );
},
closable: function() {
if(settings.closable == 'auto') {
if(settings.on == 'hover') {
return false;
}
return true;
}
return settings.closable;
},
dimmer: function() {
return $module.hasClass(className.dimmer);
},
dimmable: function() {
return $module.hasClass(className.dimmable);
},
dimmed: function() {
return $dimmable.hasClass(className.dimmed);
},
disabled: function() {
return $dimmable.hasClass(className.disabled);
},
enabled: function() {
return !module.is.disabled();
},
page: function () {
return $dimmable.is('body');
},
pageDimmer: function() {
return $dimmer.hasClass(className.pageDimmer);
}
},
can: {
show: function() {
return !$dimmer.hasClass(className.disabled);
}
},
set: {
opacity: function(opacity) {
var
color = $dimmer.css('background-color'),
colorArray = color.split(','),
isRGBA = (colorArray && colorArray.length == 4)
;
opacity = settings.opacity || opacity;
if(isRGBA) {
colorArray[3] = opacity + ')';
color = colorArray.join(',');
}
else {
color = 'rgba(0, 0, 0, ' + opacity + ')';
}
module.debug('Setting opacity to', opacity);
$dimmer.css('background-color', color);
},
active: function() {
$dimmer.addClass(className.active);
},
dimmable: function() {
$dimmable.addClass(className.dimmable);
},
dimmed: function() {
$dimmable.addClass(className.dimmed);
},
pageDimmer: function() {
$dimmer.addClass(className.pageDimmer);
},
disabled: function() {
$dimmer.addClass(className.disabled);
},
variation: function(variation) {
variation = variation || settings.variation;
if(variation) {
$dimmer.addClass(variation);
}
}
},
remove: {
active: function() {
$dimmer
.removeClass(className.active)
;
},
dimmed: function() {
$dimmable.removeClass(className.dimmed);
},
disabled: function() {
$dimmer.removeClass(className.disabled);
},
variation: function(variation) {
variation = variation || settings.variation;
if(variation) {
$dimmer.removeClass(variation);
}
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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 = [];
}
},
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 {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
module.preinitialize();
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.dimmer.settings = {
name : 'Dimmer',
namespace : 'dimmer',
debug : false,
verbose : false,
performance : true,
// name to distinguish between multiple dimmers in context
dimmerName : false,
// whether to add a variation type
variation : false,
// whether to bind close events
closable : 'auto',
// whether to use css animations
useCSS : true,
// css animation to use
transition : 'fade',
// event to bind to
on : false,
// overriding opacity value
opacity : 'auto',
// transition durations
duration : {
show : 500,
hide : 500
},
onChange : function(){},
onShow : function(){},
onHide : function(){},
error : {
method : 'The method you called is not defined.'
},
className : {
active : 'active',
animating : 'animating',
dimmable : 'dimmable',
dimmed : 'dimmed',
dimmer : 'dimmer',
disabled : 'disabled',
hide : 'hide',
pageDimmer : 'page',
show : 'show'
},
selector: {
dimmer : '> .ui.dimmer',
content : '.ui.dimmer > .content, .ui.dimmer > .content > .center'
},
template: {
dimmer: function() {
return $('<div />').attr('class', 'ui dimmer');
}
}
};
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Dropdown
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.fn.dropdown = function(parameters) {
var
$allModules = $(this),
$document = $(document),
moduleSelector = $allModules.selector || '',
hasTouch = ('ontouchstart' in document.documentElement),
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function(elementIndex) {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.dropdown.settings, parameters)
: $.extend({}, $.fn.dropdown.settings),
className = settings.className,
message = settings.message,
fields = settings.fields,
metadata = settings.metadata,
namespace = settings.namespace,
regExp = settings.regExp,
selector = settings.selector,
error = settings.error,
templates = settings.templates,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
$module = $(this),
$context = $(settings.context),
$text = $module.find(selector.text),
$search = $module.find(selector.search),
$input = $module.find(selector.input),
$icon = $module.find(selector.icon),
$combo = ($module.prev().find(selector.text).length > 0)
? $module.prev().find(selector.text)
: $module.prev(),
$menu = $module.children(selector.menu),
$item = $menu.find(selector.item),
activated = false,
itemActivated = false,
internalChange = false,
element = this,
instance = $module.data(moduleNamespace),
initialLoad,
pageLostFocus,
elementNamespace,
id,
selectObserver,
menuObserver,
module
;
module = {
initialize: function() {
module.debug('Initializing dropdown', settings);
if( module.is.alreadySetup() ) {
module.setup.reference();
}
else {
module.setup.layout();
module.refreshData();
module.save.defaults();
module.restore.selected();
module.create.id();
module.bind.events();
module.observeChanges();
module.instantiate();
}
},
instantiate: function() {
module.verbose('Storing instance of dropdown', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
destroy: function() {
module.verbose('Destroying previous dropdown', $module);
module.remove.tabbable();
$module
.off(eventNamespace)
.removeData(moduleNamespace)
;
$menu
.off(eventNamespace)
;
$document
.off(elementNamespace)
;
if(selectObserver) {
selectObserver.disconnect();
}
if(menuObserver) {
menuObserver.disconnect();
}
},
observeChanges: function() {
if('MutationObserver' in window) {
selectObserver = new MutationObserver(function(mutations) {
module.debug('<select> modified, recreating menu');
module.setup.select();
});
menuObserver = new MutationObserver(function(mutations) {
module.debug('Menu modified, updating selector cache');
module.refresh();
});
if(module.has.input()) {
selectObserver.observe($input[0], {
childList : true,
subtree : true
});
}
if(module.has.menu()) {
menuObserver.observe($menu[0], {
childList : true,
subtree : true
});
}
module.debug('Setting up mutation observer', selectObserver, menuObserver);
}
},
create: {
id: function() {
id = (Math.random().toString(16) + '000000000').substr(2, 8);
elementNamespace = '.' + id;
module.verbose('Creating unique id for element', id);
},
userChoice: function(values) {
var
$userChoices,
$userChoice,
isUserValue,
html
;
values = values || module.get.userValues();
if(!values) {
return false;
}
values = $.isArray(values)
? values
: [values]
;
$.each(values, function(index, value) {
if(module.get.item(value) === false) {
html = settings.templates.addition( module.add.variables(message.addResult, value) );
$userChoice = $('<div />')
.html(html)
.attr('data-' + metadata.value, value)
.attr('data-' + metadata.text, value)
.addClass(className.addition)
.addClass(className.item)
;
$userChoices = ($userChoices === undefined)
? $userChoice
: $userChoices.add($userChoice)
;
module.verbose('Creating user choices for value', value, $userChoice);
}
});
return $userChoices;
},
userLabels: function(value) {
var
userValues = module.get.userValues()
;
if(userValues) {
module.debug('Adding user labels', userValues);
$.each(userValues, function(index, value) {
module.verbose('Adding custom user value');
module.add.label(value, value);
});
}
},
menu: function() {
$menu = $('<div />')
.addClass(className.menu)
.appendTo($module)
;
}
},
search: function(query) {
query = (query !== undefined)
? query
: module.get.query()
;
module.verbose('Searching for query', query);
module.filter(query);
},
select: {
firstUnfiltered: function() {
module.verbose('Selecting first non-filtered element');
module.remove.selectedItem();
$item
.not(selector.unselectable)
.eq(0)
.addClass(className.selected)
;
},
nextAvailable: function($selected) {
$selected = $selected.eq(0);
var
$nextAvailable = $selected.nextAll(selector.item).not(selector.unselectable).eq(0),
$prevAvailable = $selected.prevAll(selector.item).not(selector.unselectable).eq(0),
hasNext = ($nextAvailable.length > 0)
;
if(hasNext) {
module.verbose('Moving selection to', $nextAvailable);
$nextAvailable.addClass(className.selected);
}
else {
module.verbose('Moving selection to', $prevAvailable);
$prevAvailable.addClass(className.selected);
}
}
},
setup: {
api: function() {
var
apiSettings = {
debug : settings.debug,
on : false
}
;
module.verbose('First request, initializing API');
$module
.api(apiSettings)
;
},
layout: function() {
if( $module.is('select') ) {
module.setup.select();
module.setup.returnedObject();
}
if( !module.has.menu() ) {
module.create.menu();
}
if( module.is.search() && !module.has.search() ) {
module.verbose('Adding search input');
$search = $('<input />')
.addClass(className.search)
.insertBefore($text)
;
}
if(settings.allowTab) {
module.set.tabbable();
}
},
select: function() {
var
selectValues = module.get.selectValues()
;
module.debug('Dropdown initialized on a select', selectValues);
if( $module.is('select') ) {
$input = $module;
}
// see if select is placed correctly already
if($input.parent(selector.dropdown).length > 0) {
module.debug('UI dropdown already exists. Creating dropdown menu only');
$module = $input.closest(selector.dropdown);
if( !module.has.menu() ) {
module.create.menu();
}
$menu = $module.children(selector.menu);
module.setup.menu(selectValues);
}
else {
module.debug('Creating entire dropdown from select');
$module = $('<div />')
.attr('class', $input.attr('class') )
.addClass(className.selection)
.addClass(className.dropdown)
.html( templates.dropdown(selectValues) )
.insertBefore($input)
;
if($input.hasClass(className.multiple) && $input.prop('multiple') === false) {
module.error(error.missingMultiple);
$input.prop('multiple', true);
}
if($input.is('[multiple]')) {
module.set.multiple();
}
if ($input.prop('disabled')) {
module.debug('Disabling dropdown')
$module.addClass(className.disabled)
}
$input
.removeAttr('class')
.detach()
.prependTo($module)
;
}
module.refresh();
},
menu: function(values) {
$menu.html( templates.menu(values, fields));
$item = $menu.find(selector.item);
},
reference: function() {
module.debug('Dropdown behavior was called on select, replacing with closest dropdown');
// replace module reference
$module = $module.parent(selector.dropdown);
module.refresh();
module.setup.returnedObject();
// invoke method in context of current instance
if(methodInvoked) {
instance = module;
module.invoke(query);
}
},
returnedObject: function() {
var
$firstModules = $allModules.slice(0, elementIndex),
$lastModules = $allModules.slice(elementIndex + 1)
;
// adjust all modules to use correct reference
$allModules = $firstModules.add($module).add($lastModules);
}
},
refresh: function() {
module.refreshSelectors();
module.refreshData();
},
refreshSelectors: function() {
module.verbose('Refreshing selector cache');
$text = $module.find(selector.text);
$search = $module.find(selector.search);
$input = $module.find(selector.input);
$icon = $module.find(selector.icon);
$combo = ($module.prev().find(selector.text).length > 0)
? $module.prev().find(selector.text)
: $module.prev()
;
$menu = $module.children(selector.menu);
$item = $menu.find(selector.item);
},
refreshData: function() {
module.verbose('Refreshing cached metadata');
$item
.removeData(metadata.text)
.removeData(metadata.value)
;
$module
.removeData(metadata.defaultText)
.removeData(metadata.defaultValue)
.removeData(metadata.placeholderText)
;
},
toggle: function() {
module.verbose('Toggling menu visibility');
if( !module.is.active() ) {
module.show();
}
else {
module.hide();
}
},
show: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if( module.can.show() && !module.is.active() ) {
module.debug('Showing dropdown');
if(module.is.multiple() && !module.has.search() && module.is.allFiltered()) {
return true;
}
if(module.has.message() && !module.has.maxSelections()) {
module.remove.message();
}
if(settings.onShow.call(element) !== false) {
module.animate.show(function() {
if( module.can.click() ) {
module.bind.intent();
}
module.set.visible();
callback.call(element);
});
}
}
},
hide: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if( module.is.active() ) {
module.debug('Hiding dropdown');
if(settings.onHide.call(element) !== false) {
module.animate.hide(function() {
module.remove.visible();
callback.call(element);
});
}
}
},
hideOthers: function() {
module.verbose('Finding other dropdowns to hide');
$allModules
.not($module)
.has(selector.menu + '.' + className.visible)
.dropdown('hide')
;
},
hideMenu: function() {
module.verbose('Hiding menu instantaneously');
module.remove.active();
module.remove.visible();
$menu.transition('hide');
},
hideSubMenus: function() {
var
$subMenus = $menu.children(selector.item).find(selector.menu)
;
module.verbose('Hiding sub menus', $subMenus);
$subMenus.transition('hide');
},
bind: {
events: function() {
if(hasTouch) {
module.bind.touchEvents();
}
module.bind.keyboardEvents();
module.bind.inputEvents();
module.bind.mouseEvents();
},
touchEvents: function() {
module.debug('Touch device detected binding additional touch events');
if( module.is.searchSelection() ) {
// do nothing special yet
}
else if( module.is.single() ) {
$module
.on('touchstart' + eventNamespace, module.event.test.toggle)
;
}
$menu
.on('touchstart' + eventNamespace, selector.item, module.event.item.mouseenter)
;
},
keyboardEvents: function() {
module.verbose('Binding keyboard events');
$module
.on('keydown' + eventNamespace, module.event.keydown)
;
if( module.has.search() ) {
$module
.on(module.get.inputEvent() + eventNamespace, selector.search, module.event.input)
;
}
if( module.is.multiple() ) {
$document
.on('keydown' + elementNamespace, module.event.document.keydown)
;
}
},
inputEvents: function() {
module.verbose('Binding input change events');
$module
.on('change' + eventNamespace, selector.input, module.event.change)
;
},
mouseEvents: function() {
module.verbose('Binding mouse events');
if(module.is.multiple()) {
$module
.on('click' + eventNamespace, selector.label, module.event.label.click)
.on('click' + eventNamespace, selector.remove, module.event.remove.click)
;
}
if( module.is.searchSelection() ) {
$module
.on('mousedown' + eventNamespace, selector.menu, module.event.menu.mousedown)
.on('mouseup' + eventNamespace, selector.menu, module.event.menu.mouseup)
.on('click' + eventNamespace, selector.icon, module.event.icon.click)
.on('click' + eventNamespace, selector.search, module.show)
.on('focus' + eventNamespace, selector.search, module.event.search.focus)
.on('blur' + eventNamespace, selector.search, module.event.search.blur)
.on('click' + eventNamespace, selector.text, module.event.text.focus)
;
if(module.is.multiple()) {
$module
.on('click' + eventNamespace, module.event.click)
;
}
}
else {
if(settings.on == 'click') {
$module
.on('click' + eventNamespace, selector.icon, module.event.icon.click)
.on('click' + eventNamespace, module.event.test.toggle)
;
}
else if(settings.on == 'hover') {
$module
.on('mouseenter' + eventNamespace, module.delay.show)
.on('mouseleave' + eventNamespace, module.delay.hide)
;
}
else {
$module
.on(settings.on + eventNamespace, module.toggle)
;
}
$module
.on('mousedown' + eventNamespace, module.event.mousedown)
.on('mouseup' + eventNamespace, module.event.mouseup)
.on('focus' + eventNamespace, module.event.focus)
.on('blur' + eventNamespace, module.event.blur)
;
}
$menu
.on('mouseenter' + eventNamespace, selector.item, module.event.item.mouseenter)
.on('mouseleave' + eventNamespace, selector.item, module.event.item.mouseleave)
.on('click' + eventNamespace, selector.item, module.event.item.click)
;
},
intent: function() {
module.verbose('Binding hide intent event to document');
if(hasTouch) {
$document
.on('touchstart' + elementNamespace, module.event.test.touch)
.on('touchmove' + elementNamespace, module.event.test.touch)
;
}
$document
.on('click' + elementNamespace, module.event.test.hide)
;
}
},
unbind: {
intent: function() {
module.verbose('Removing hide intent event from document');
if(hasTouch) {
$document
.off('touchstart' + elementNamespace)
.off('touchmove' + elementNamespace)
;
}
$document
.off('click' + elementNamespace)
;
}
},
filter: function(query) {
var
searchTerm = (query !== undefined)
? query
: module.get.query(),
afterFiltered = function() {
if(module.is.multiple()) {
module.filterActive();
}
module.select.firstUnfiltered();
if( module.has.allResultsFiltered() ) {
if( settings.onNoResults.call(element, searchTerm) ) {
if(!settings.allowAdditions) {
module.verbose('All items filtered, showing message', searchTerm);
module.add.message(message.noResults);
}
}
else {
module.verbose('All items filtered, hiding dropdown', searchTerm);
module.hideMenu();
}
}
else {
module.remove.message();
}
if(settings.allowAdditions) {
module.add.userSuggestion(query);
}
if(module.is.searchSelection() && module.can.show() && module.is.focusedOnSearch() ) {
module.show();
}
}
;
if(settings.useLabels && module.has.maxSelections()) {
return;
}
if(settings.apiSettings) {
if( module.can.useAPI() ) {
module.queryRemote(searchTerm, function() {
afterFiltered();
});
}
else {
module.error(error.noAPI);
}
}
else {
module.filterItems(searchTerm);
afterFiltered();
}
},
queryRemote: function(query, callback) {
var
apiSettings = {
errorDuration : false,
throttle : settings.throttle,
urlData : {
query: query
},
onError: function() {
module.add.message(message.serverError);
callback();
},
onFailure: function() {
module.add.message(message.serverError);
callback();
},
onSuccess : function(response) {
module.remove.message();
module.setup.menu({
values: response.results
});
callback();
}
}
;
if( !$module.api('get request') ) {
module.setup.api();
}
apiSettings = $.extend(true, {}, apiSettings, settings.apiSettings);
$module
.api('setting', apiSettings)
.api('query')
;
},
filterItems: function(query) {
var
searchTerm = (query !== undefined)
? query
: module.get.query(),
$results = $(),
escapedTerm = module.escape.regExp(searchTerm),
beginsWithRegExp = new RegExp('^' + escapedTerm, 'igm')
;
// avoid loop if we're matching nothing
if( !module.has.query() ) {
$results = $item;
}
else {
module.verbose('Searching for matching values', searchTerm);
$item
.each(function(){
var
$choice = $(this),
text,
value
;
if(settings.match == 'both' || settings.match == 'text') {
text = String(module.get.choiceText($choice, false));
if(text.search(beginsWithRegExp) !== -1) {
$results = $results.add($choice);
return true;
}
else if(settings.fullTextSearch && module.fuzzySearch(searchTerm, text)) {
$results = $results.add($choice);
return true;
}
}
if(settings.match == 'both' || settings.match == 'value') {
value = String(module.get.choiceValue($choice, text));
if(value.search(beginsWithRegExp) !== -1) {
$results = $results.add($choice);
return true;
}
else if(settings.fullTextSearch && module.fuzzySearch(searchTerm, value)) {
$results = $results.add($choice);
return true;
}
}
})
;
}
module.debug('Showing only matched items', searchTerm);
module.remove.filteredItem();
$item
.not($results)
.addClass(className.filtered)
;
},
fuzzySearch: function(query, term) {
var
termLength = term.length,
queryLength = query.length
;
query = query.toLowerCase();
term = term.toLowerCase();
if(queryLength > termLength) {
return false;
}
if(queryLength === termLength) {
return (query === term);
}
search: for (var characterIndex = 0, nextCharacterIndex = 0; characterIndex < queryLength; characterIndex++) {
var
queryCharacter = query.charCodeAt(characterIndex)
;
while(nextCharacterIndex < termLength) {
if(term.charCodeAt(nextCharacterIndex++) === queryCharacter) {
continue search;
}
}
return false;
}
return true;
},
filterActive: function() {
if(settings.useLabels) {
$item.filter('.' + className.active)
.addClass(className.filtered)
;
}
},
focusSearch: function() {
if( module.is.search() && !module.is.focusedOnSearch() ) {
$search[0].focus();
}
},
forceSelection: function() {
var
$currentlySelected = $item.not(className.filtered).filter('.' + className.selected).eq(0),
$activeItem = $item.not(className.filtered).filter('.' + className.active).eq(0),
$selectedItem = ($currentlySelected.length > 0)
? $currentlySelected
: $activeItem,
hasSelected = ($selectedItem.size() > 0)
;
if( hasSelected && module.has.query() ) {
module.debug('Forcing partial selection to selected item', $selectedItem);
module.event.item.click.call($selectedItem);
}
else {
module.hide();
}
},
event: {
change: function() {
if(!internalChange) {
module.debug('Input changed, updating selection');
module.set.selected();
}
},
focus: function() {
if(settings.showOnFocus && !activated && module.is.hidden() && !pageLostFocus) {
module.show();
}
},
click: function(event) {
var
$target = $(event.target)
;
// focus search
if($target.is($module) && !module.is.focusedOnSearch()) {
module.focusSearch();
}
},
blur: function(event) {
pageLostFocus = (document.activeElement === this);
if(!activated && !pageLostFocus) {
module.remove.activeLabel();
module.hide();
}
},
// prevents focus callback from occurring on mousedown
mousedown: function() {
activated = true;
},
mouseup: function() {
activated = false;
},
search: {
focus: function() {
activated = true;
if(module.is.multiple()) {
module.remove.activeLabel();
}
if(settings.showOnFocus) {
module.show();
}
},
blur: function(event) {
pageLostFocus = (document.activeElement === this);
if(!itemActivated && !pageLostFocus) {
if(module.is.multiple()) {
module.remove.activeLabel();
module.hide();
}
else if(settings.forceSelection) {
module.forceSelection();
}
else {
module.hide();
}
}
else if(pageLostFocus) {
if(settings.forceSelection) {
module.forceSelection();
}
}
}
},
icon: {
click: function(event) {
module.toggle();
event.stopPropagation();
}
},
text: {
focus: function(event) {
activated = true;
module.focusSearch();
}
},
input: function(event) {
if(module.is.multiple() || module.is.searchSelection()) {
module.set.filtered();
}
clearTimeout(module.timer);
module.timer = setTimeout(module.search, settings.delay.search);
},
label: {
click: function(event) {
var
$label = $(this),
$labels = $module.find(selector.label),
$activeLabels = $labels.filter('.' + className.active),
$nextActive = $label.nextAll('.' + className.active),
$prevActive = $label.prevAll('.' + className.active),
$range = ($nextActive.length > 0)
? $label.nextUntil($nextActive).add($activeLabels).add($label)
: $label.prevUntil($prevActive).add($activeLabels).add($label)
;
if(event.shiftKey) {
$activeLabels.removeClass(className.active);
$range.addClass(className.active);
}
else if(event.ctrlKey) {
$label.toggleClass(className.active);
}
else {
$activeLabels.removeClass(className.active);
$label.addClass(className.active);
}
settings.onLabelSelect.apply(this, $labels.filter('.' + className.active));
}
},
remove: {
click: function() {
var
$label = $(this).parent()
;
if( $label.hasClass(className.active) ) {
// remove all selected labels
module.remove.activeLabels();
}
else {
// remove this label only
module.remove.activeLabels( $label );
}
}
},
test: {
toggle: function(event) {
var
toggleBehavior = (module.is.multiple())
? module.show
: module.toggle
;
if( module.determine.eventOnElement(event, toggleBehavior) ) {
event.preventDefault();
}
},
touch: function(event) {
module.determine.eventOnElement(event, function() {
if(event.type == 'touchstart') {
module.timer = setTimeout(function() {
module.hide();
}, settings.delay.touch);
}
else if(event.type == 'touchmove') {
clearTimeout(module.timer);
}
});
event.stopPropagation();
},
hide: function(event) {
module.determine.eventInModule(event, module.hide);
}
},
menu: {
mousedown: function() {
itemActivated = true;
},
mouseup: function() {
itemActivated = false;
}
},
item: {
mouseenter: function(event) {
var
$subMenu = $(this).children(selector.menu),
$otherMenus = $(this).siblings(selector.item).children(selector.menu)
;
if( $subMenu.length > 0 ) {
clearTimeout(module.itemTimer);
module.itemTimer = setTimeout(function() {
module.verbose('Showing sub-menu', $subMenu);
$.each($otherMenus, function() {
module.animate.hide(false, $(this));
});
module.animate.show(false, $subMenu);
}, settings.delay.show);
event.preventDefault();
}
},
mouseleave: function(event) {
var
$subMenu = $(this).children(selector.menu)
;
if($subMenu.length > 0) {
clearTimeout(module.itemTimer);
module.itemTimer = setTimeout(function() {
module.verbose('Hiding sub-menu', $subMenu);
module.animate.hide(false, $subMenu);
}, settings.delay.hide);
}
},
touchend: function() {
},
click: function (event) {
var
$choice = $(this),
$target = (event)
? $(event.target)
: $(''),
$subMenu = $choice.find(selector.menu),
text = module.get.choiceText($choice),
value = module.get.choiceValue($choice, text),
hasSubMenu = ($subMenu.length > 0),
isBubbledEvent = ($subMenu.find($target).length > 0)
;
if(!isBubbledEvent && (!hasSubMenu || settings.allowCategorySelection)) {
if(!settings.useLabels) {
module.remove.filteredItem();
module.remove.searchTerm();
module.set.scrollPosition($choice);
}
module.determine.selectAction.call(this, text, value);
}
}
},
document: {
// label selection should occur even when element has no focus
keydown: function(event) {
var
pressedKey = event.which,
keys = module.get.shortcutKeys(),
isShortcutKey = module.is.inObject(pressedKey, keys)
;
if(isShortcutKey) {
var
$label = $module.find(selector.label),
$activeLabel = $label.filter('.' + className.active),
activeValue = $activeLabel.data(metadata.value),
labelIndex = $label.index($activeLabel),
labelCount = $label.length,
hasActiveLabel = ($activeLabel.length > 0),
hasMultipleActive = ($activeLabel.length > 1),
isFirstLabel = (labelIndex === 0),
isLastLabel = (labelIndex + 1 == labelCount),
isSearch = module.is.searchSelection(),
isFocusedOnSearch = module.is.focusedOnSearch(),
isFocused = module.is.focused(),
caretAtStart = (isFocusedOnSearch && module.get.caretPosition() === 0),
$nextLabel
;
if(isSearch && !hasActiveLabel && !isFocusedOnSearch) {
return;
}
if(pressedKey == keys.leftArrow) {
// activate previous label
if((isFocused || caretAtStart) && !hasActiveLabel) {
module.verbose('Selecting previous label');
$label.last().addClass(className.active);
}
else if(hasActiveLabel) {
if(!event.shiftKey) {
module.verbose('Selecting previous label');
$label.removeClass(className.active);
}
else {
module.verbose('Adding previous label to selection');
}
if(isFirstLabel && !hasMultipleActive) {
$activeLabel.addClass(className.active);
}
else {
$activeLabel.prev(selector.siblingLabel)
.addClass(className.active)
.end()
;
}
event.preventDefault();
}
}
else if(pressedKey == keys.rightArrow) {
// activate first label
if(isFocused && !hasActiveLabel) {
$label.first().addClass(className.active);
}
// activate next label
if(hasActiveLabel) {
if(!event.shiftKey) {
module.verbose('Selecting next label');
$label.removeClass(className.active);
}
else {
module.verbose('Adding next label to selection');
}
if(isLastLabel) {
if(isSearch) {
if(!isFocusedOnSearch) {
module.focusSearch();
}
else {
$label.removeClass(className.active);
}
}
else if(hasMultipleActive) {
$activeLabel.next(selector.siblingLabel).addClass(className.active);
}
else {
$activeLabel.addClass(className.active);
}
}
else {
$activeLabel.next(selector.siblingLabel).addClass(className.active);
}
event.preventDefault();
}
}
else if(pressedKey == keys.deleteKey || pressedKey == keys.backspace) {
if(hasActiveLabel) {
module.verbose('Removing active labels');
if(isLastLabel) {
if(isSearch && !isFocusedOnSearch) {
module.focusSearch();
}
}
$activeLabel.last().next(selector.siblingLabel).addClass(className.active);
module.remove.activeLabels($activeLabel);
event.preventDefault();
}
else if(caretAtStart && !hasActiveLabel && pressedKey == keys.backspace) {
module.verbose('Removing last label on input backspace');
$activeLabel = $label.last().addClass(className.active);
module.remove.activeLabels($activeLabel);
}
}
else {
$activeLabel.removeClass(className.active);
}
}
}
},
keydown: function(event) {
var
pressedKey = event.which,
keys = module.get.shortcutKeys(),
isShortcutKey = module.is.inObject(pressedKey, keys)
;
if(isShortcutKey) {
var
$currentlySelected = $item.not(selector.unselectable).filter('.' + className.selected).eq(0),
$activeItem = $menu.children('.' + className.active).eq(0),
$selectedItem = ($currentlySelected.length > 0)
? $currentlySelected
: $activeItem,
$visibleItems = ($selectedItem.length > 0)
? $selectedItem.siblings(':not(.' + className.filtered +')').andSelf()
: $menu.children(':not(.' + className.filtered +')'),
$subMenu = $selectedItem.children(selector.menu),
$parentMenu = $selectedItem.closest(selector.menu),
inVisibleMenu = ($parentMenu.hasClass(className.visible) || $parentMenu.hasClass(className.animating) || $parentMenu.parent(selector.menu).length > 0),
hasSubMenu = ($subMenu.length> 0),
hasSelectedItem = ($selectedItem.length > 0),
selectedIsSelectable = ($selectedItem.not(selector.unselectable).length > 0),
delimiterPressed = (pressedKey == keys.delimiter && settings.allowAdditions && module.is.multiple()),
$nextItem,
isSubMenuItem,
newIndex
;
// visible menu keyboard shortcuts
if( module.is.visible() ) {
// enter (select or open sub-menu)
if(pressedKey == keys.enter || delimiterPressed) {
if(pressedKey == keys.enter && hasSelectedItem && hasSubMenu && !settings.allowCategorySelection) {
module.verbose('Pressed enter on unselectable category, opening sub menu');
pressedKey = keys.rightArrow;
}
else if(selectedIsSelectable) {
module.verbose('Selecting item from keyboard shortcut', $selectedItem);
module.event.item.click.call($selectedItem, event);
if(module.is.searchSelection()) {
module.remove.searchTerm();
}
}
event.preventDefault();
}
// left arrow (hide sub-menu)
if(pressedKey == keys.leftArrow) {
isSubMenuItem = ($parentMenu[0] !== $menu[0]);
if(isSubMenuItem) {
module.verbose('Left key pressed, closing sub-menu');
module.animate.hide(false, $parentMenu);
$selectedItem
.removeClass(className.selected)
;
$parentMenu
.closest(selector.item)
.addClass(className.selected)
;
event.preventDefault();
}
}
// right arrow (show sub-menu)
if(pressedKey == keys.rightArrow) {
if(hasSubMenu) {
module.verbose('Right key pressed, opening sub-menu');
module.animate.show(false, $subMenu);
$selectedItem
.removeClass(className.selected)
;
$subMenu
.find(selector.item).eq(0)
.addClass(className.selected)
;
event.preventDefault();
}
}
// up arrow (traverse menu up)
if(pressedKey == keys.upArrow) {
$nextItem = (hasSelectedItem && inVisibleMenu)
? $selectedItem.prevAll(selector.item + ':not(' + selector.unselectable + ')').eq(0)
: $item.eq(0)
;
if($visibleItems.index( $nextItem ) < 0) {
module.verbose('Up key pressed but reached top of current menu');
event.preventDefault();
return;
}
else {
module.verbose('Up key pressed, changing active item');
$selectedItem
.removeClass(className.selected)
;
$nextItem
.addClass(className.selected)
;
module.set.scrollPosition($nextItem);
}
event.preventDefault();
}
// down arrow (traverse menu down)
if(pressedKey == keys.downArrow) {
$nextItem = (hasSelectedItem && inVisibleMenu)
? $nextItem = $selectedItem.nextAll(selector.item + ':not(' + selector.unselectable + ')').eq(0)
: $item.eq(0)
;
if($nextItem.length === 0) {
module.verbose('Down key pressed but reached bottom of current menu');
event.preventDefault();
return;
}
else {
module.verbose('Down key pressed, changing active item');
$item
.removeClass(className.selected)
;
$nextItem
.addClass(className.selected)
;
module.set.scrollPosition($nextItem);
}
event.preventDefault();
}
// page down (show next page)
if(pressedKey == keys.pageUp) {
module.scrollPage('up');
event.preventDefault();
}
if(pressedKey == keys.pageDown) {
module.scrollPage('down');
event.preventDefault();
}
// escape (close menu)
if(pressedKey == keys.escape) {
module.verbose('Escape key pressed, closing dropdown');
module.hide();
}
}
else {
// delimiter key
if(delimiterPressed) {
event.preventDefault();
}
// down arrow (open menu)
if(pressedKey == keys.downArrow) {
module.verbose('Down key pressed, showing dropdown');
module.show();
event.preventDefault();
}
}
}
else {
if( module.is.selection() && !module.is.search() ) {
module.set.selectedLetter( String.fromCharCode(pressedKey) );
}
}
}
},
determine: {
selectAction: function(text, value) {
module.verbose('Determining action', settings.action);
if( $.isFunction( module.action[settings.action] ) ) {
module.verbose('Triggering preset action', settings.action, text, value);
module.action[ settings.action ].call(this, text, value);
}
else if( $.isFunction(settings.action) ) {
module.verbose('Triggering user action', settings.action, text, value);
settings.action.call(this, text, value);
}
else {
module.error(error.action, settings.action);
}
},
eventInModule: function(event, callback) {
var
$target = $(event.target),
inDocument = ($target.closest(document.documentElement).length > 0),
inModule = ($target.closest($module).length > 0)
;
callback = $.isFunction(callback)
? callback
: function(){}
;
if(inDocument && !inModule) {
module.verbose('Triggering event', callback);
callback();
return true;
}
else {
module.verbose('Event occurred in dropdown, canceling callback');
return false;
}
},
eventOnElement: function(event, callback) {
var
$target = $(event.target),
$label = $target.closest(selector.siblingLabel),
notOnLabel = ($module.find($label).length === 0),
notInMenu = ($target.closest($menu).length === 0)
;
callback = $.isFunction(callback)
? callback
: function(){}
;
if(notOnLabel && notInMenu) {
module.verbose('Triggering event', callback);
callback();
return true;
}
else {
module.verbose('Event occurred in dropdown menu, canceling callback');
return false;
}
}
},
action: {
nothing: function() {},
activate: function(text, value) {
value = (value !== undefined)
? value
: text
;
if( module.can.activate( $(this) ) ) {
module.set.selected(value, $(this));
if(module.is.multiple() && !module.is.allFiltered()) {
return;
}
else {
module.hideAndClear();
}
}
},
select: function(text, value) {
// mimics action.activate but does not select text
module.action.activate.call(this);
},
combo: function(text, value) {
value = (value !== undefined)
? value
: text
;
module.set.selected(value, $(this));
module.hideAndClear();
},
hide: function(text, value) {
module.set.value(value);
module.hideAndClear();
}
},
get: {
id: function() {
return id;
},
defaultText: function() {
return $module.data(metadata.defaultText);
},
defaultValue: function() {
return $module.data(metadata.defaultValue);
},
placeholderText: function() {
return $module.data(metadata.placeholderText) || '';
},
text: function() {
return $text.text();
},
query: function() {
return $.trim($search.val());
},
searchWidth: function(characterCount) {
return (characterCount * settings.glyphWidth) + 'em';
},
selectionCount: function() {
var
values = module.get.values(),
count
;
count = ( module.is.multiple() )
? $.isArray(values)
? values.length
: 0
: (module.get.value() !== '')
? 1
: 0
;
return count;
},
transition: function($subMenu) {
return (settings.transition == 'auto')
? module.is.upward($subMenu)
? 'slide up'
: 'slide down'
: settings.transition
;
},
userValues: function() {
var
values = module.get.values()
;
if(!values) {
return false;
}
values = $.isArray(values)
? values
: [values]
;
return $.grep(values, function(value) {
return (module.get.item(value) === false);
});
},
uniqueArray: function(array) {
return $.grep(array, function (value, index) {
return $.inArray(value, array) === index;
});
},
caretPosition: function() {
var
input = $search.get(0),
range,
rangeLength
;
if('selectionStart' in input) {
return input.selectionStart;
}
else if (document.selection) {
input.focus();
range = document.selection.createRange();
rangeLength = range.text.length;
range.moveStart('character', -input.value.length);
return range.text.length - rangeLength;
}
},
shortcutKeys: function() {
return {
backspace : 8,
delimiter : 188, // comma
deleteKey : 46,
enter : 13,
escape : 27,
pageUp : 33,
pageDown : 34,
leftArrow : 37,
upArrow : 38,
rightArrow : 39,
downArrow : 40
};
},
value: function() {
var
value = ($input.length > 0)
? $input.val()
: $module.data(metadata.value)
;
// prevents placeholder element from being selected when multiple
if($.isArray(value) && value.length === 1 && value[0] === '') {
return '';
}
return value;
},
values: function() {
var
value = module.get.value()
;
if(value === '') {
return '';
}
return ( !module.has.selectInput() && module.is.multiple() )
? (typeof value == 'string') // delimited string
? value.split(settings.delimiter)
: ''
: value
;
},
remoteValues: function() {
var
values = module.get.values(),
remoteValues = false
;
if(values) {
if(typeof values == 'string') {
values = [values];
}
remoteValues = {};
$.each(values, function(index, value) {
var
name = module.read.remoteData(value)
;
module.verbose('Restoring value from session data', name, value);
remoteValues[value] = (name)
? name
: value
;
});
}
return remoteValues;
},
choiceText: function($choice, preserveHTML) {
preserveHTML = (preserveHTML !== undefined)
? preserveHTML
: settings.preserveHTML
;
if($choice) {
if($choice.find(selector.menu).length > 0) {
module.verbose('Retreiving text of element with sub-menu');
$choice = $choice.clone();
$choice.find(selector.menu).remove();
$choice.find(selector.menuIcon).remove();
}
return ($choice.data(metadata.text) !== undefined)
? $choice.data(metadata.text)
: (preserveHTML)
? $.trim($choice.html())
: $.trim($choice.text())
;
}
},
choiceValue: function($choice, choiceText) {
choiceText = choiceText || module.get.choiceText($choice);
if(!$choice) {
return false;
}
return ($choice.data(metadata.value) !== undefined)
? String( $choice.data(metadata.value) )
: (typeof choiceText === 'string')
? $.trim(choiceText.toLowerCase())
: String(choiceText)
;
},
inputEvent: function() {
var
input = $search[0]
;
if(input) {
return (input.oninput !== undefined)
? 'input'
: (input.onpropertychange !== undefined)
? 'propertychange'
: 'keyup'
;
}
return false;
},
selectValues: function() {
var
select = {}
;
select.values = [];
$module
.find('option')
.each(function() {
var
$option = $(this),
name = $option.html(),
disabled = $option.attr('disabled'),
value = ( $option.attr('value') !== undefined )
? $option.attr('value')
: name
;
if(settings.placeholder === 'auto' && value === '') {
select.placeholder = name;
}
else {
select.values.push({
name : name,
value : value,
disabled : disabled
});
}
})
;
if(settings.placeholder && settings.placeholder !== 'auto') {
module.debug('Setting placeholder value to', settings.placeholder);
select.placeholder = settings.placeholder;
}
if(settings.sortSelect) {
select.values.sort(function(a, b) {
return (a.name > b.name)
? 1
: -1
;
});
module.debug('Retrieved and sorted values from select', select);
}
else {
module.debug('Retreived values from select', select);
}
return select;
},
activeItem: function() {
return $item.filter('.' + className.active);
},
selectedItem: function() {
var
$selectedItem = $item.not(selector.unselectable).filter('.' + className.selected)
;
return ($selectedItem.length > 0)
? $selectedItem
: $item.eq(0)
;
},
itemWithAdditions: function(value) {
var
$items = module.get.item(value),
$userItems = module.create.userChoice(value),
hasUserItems = ($userItems && $userItems.length > 0)
;
if(hasUserItems) {
$items = ($items.length > 0)
? $items.add($userItems)
: $userItems
;
}
return $items;
},
item: function(value, strict) {
var
$selectedItem = false,
shouldSearch,
isMultiple
;
value = (value !== undefined)
? value
: ( module.get.values() !== undefined)
? module.get.values()
: module.get.text()
;
shouldSearch = (isMultiple)
? (value.length > 0)
: (value !== undefined && value !== null)
;
isMultiple = (module.is.multiple() && $.isArray(value));
strict = (value === '' || value === 0)
? true
: strict || false
;
if(shouldSearch) {
$item
.each(function() {
var
$choice = $(this),
optionText = module.get.choiceText($choice),
optionValue = module.get.choiceValue($choice, optionText)
;
// safe early exit
if(optionValue === null || optionValue === undefined) {
return;
}
if(isMultiple) {
if($.inArray( String(optionValue), value) !== -1 || $.inArray(optionText, value) !== -1) {
$selectedItem = ($selectedItem)
? $selectedItem.add($choice)
: $choice
;
}
}
else if(strict) {
module.verbose('Ambiguous dropdown value using strict type check', $choice, value);
if( optionValue === value || optionText === value) {
$selectedItem = $choice;
return true;
}
}
else {
if( String(optionValue) == String(value) || optionText == value) {
module.verbose('Found select item by value', optionValue, value);
$selectedItem = $choice;
return true;
}
}
})
;
}
return $selectedItem;
}
},
check: {
maxSelections: function(selectionCount) {
if(settings.maxSelections) {
selectionCount = (selectionCount !== undefined)
? selectionCount
: module.get.selectionCount()
;
if(selectionCount >= settings.maxSelections) {
module.debug('Maximum selection count reached');
if(settings.useLabels) {
$item.addClass(className.filtered);
module.add.message(message.maxSelections);
}
return true;
}
else {
module.verbose('No longer at maximum selection count');
module.remove.message();
module.remove.filteredItem();
if(module.is.searchSelection()) {
module.filterItems();
}
return false;
}
}
return true;
}
},
restore: {
defaults: function() {
module.clear();
module.restore.defaultText();
module.restore.defaultValue();
},
defaultText: function() {
var
defaultText = module.get.defaultText(),
placeholderText = module.get.placeholderText
;
if(defaultText === placeholderText) {
module.debug('Restoring default placeholder text', defaultText);
module.set.placeholderText(defaultText);
}
else {
module.debug('Restoring default text', defaultText);
module.set.text(defaultText);
}
},
defaultValue: function() {
var
defaultValue = module.get.defaultValue()
;
if(defaultValue !== undefined) {
module.debug('Restoring default value', defaultValue);
if(defaultValue !== '') {
module.set.value(defaultValue);
module.set.selected();
}
else {
module.remove.activeItem();
module.remove.selectedItem();
}
}
},
labels: function() {
if(settings.allowAdditions) {
if(!settings.useLabels) {
module.error(error.labels);
settings.useLabels = true;
}
module.debug('Restoring selected values');
module.create.userLabels();
}
module.check.maxSelections();
},
selected: function() {
module.restore.values();
if(module.is.multiple()) {
module.debug('Restoring previously selected values and labels');
module.restore.labels();
}
else {
module.debug('Restoring previously selected values');
}
},
values: function() {
// prevents callbacks from occuring on initial load
module.set.initialLoad();
if(settings.apiSettings) {
if(settings.saveRemoteData) {
module.restore.remoteValues();
}
else {
module.clearValue();
}
}
else {
module.set.selected();
}
module.remove.initialLoad();
},
remoteValues: function() {
var
values = module.get.remoteValues()
;
module.debug('Recreating selected from session data', values);
if(values) {
if( module.is.single() ) {
$.each(values, function(value, name) {
module.set.text(name);
});
}
else {
$.each(values, function(value, name) {
module.add.label(value, name);
});
}
}
}
},
read: {
remoteData: function(value) {
var
name
;
if(window.Storage === undefined) {
module.error(error.noStorage);
return;
}
name = sessionStorage.getItem(value);
return (name !== undefined)
? name
: false
;
}
},
save: {
defaults: function() {
module.save.defaultText();
module.save.placeholderText();
module.save.defaultValue();
},
defaultValue: function() {
var
value = module.get.value()
;
module.verbose('Saving default value as', value);
$module.data(metadata.defaultValue, value);
},
defaultText: function() {
var
text = module.get.text()
;
module.verbose('Saving default text as', text);
$module.data(metadata.defaultText, text);
},
placeholderText: function() {
var
text
;
if(settings.placeholder !== false && $text.hasClass(className.placeholder)) {
text = module.get.text();
module.verbose('Saving placeholder text as', text);
$module.data(metadata.placeholderText, text);
}
},
remoteData: function(name, value) {
if(window.Storage === undefined) {
module.error(error.noStorage);
return;
}
module.verbose('Saving remote data to session storage', value, name);
sessionStorage.setItem(value, name);
}
},
clear: function() {
if(module.is.multiple()) {
module.remove.labels();
}
else {
module.remove.activeItem();
module.remove.selectedItem();
}
module.set.placeholderText();
module.clearValue();
},
clearValue: function() {
module.set.value('');
},
scrollPage: function(direction, $selectedItem) {
var
$currentItem = $selectedItem || module.get.selectedItem(),
$menu = $currentItem.closest(selector.menu),
menuHeight = $menu.outerHeight(),
currentScroll = $menu.scrollTop(),
itemHeight = $item.eq(0).outerHeight(),
itemsPerPage = Math.floor(menuHeight / itemHeight),
maxScroll = $menu.prop('scrollHeight'),
newScroll = (direction == 'up')
? currentScroll - (itemHeight * itemsPerPage)
: currentScroll + (itemHeight * itemsPerPage),
$selectableItem = $item.not(selector.unselectable),
isWithinRange,
$nextSelectedItem,
elementIndex
;
elementIndex = (direction == 'up')
? $selectableItem.index($currentItem) - itemsPerPage
: $selectableItem.index($currentItem) + itemsPerPage
;
isWithinRange = (direction == 'up')
? (elementIndex >= 0)
: (elementIndex < $selectableItem.length)
;
$nextSelectedItem = (isWithinRange)
? $selectableItem.eq(elementIndex)
: (direction == 'up')
? $selectableItem.first()
: $selectableItem.last()
;
if($nextSelectedItem.length > 0) {
module.debug('Scrolling page', direction, $nextSelectedItem);
$currentItem
.removeClass(className.selected)
;
$nextSelectedItem
.addClass(className.selected)
;
$menu
.scrollTop(newScroll)
;
}
},
set: {
filtered: function() {
var
isMultiple = module.is.multiple(),
isSearch = module.is.searchSelection(),
isSearchMultiple = (isMultiple && isSearch),
searchValue = (isSearch)
? module.get.query()
: '',
hasSearchValue = (typeof searchValue === 'string' && searchValue.length > 0),
searchWidth = module.get.searchWidth(searchValue.length),
valueIsSet = searchValue !== ''
;
if(isMultiple && hasSearchValue) {
module.verbose('Adjusting input width', searchWidth, settings.glyphWidth);
$search.css('width', searchWidth);
}
if(hasSearchValue || (isSearchMultiple && valueIsSet)) {
module.verbose('Hiding placeholder text');
$text.addClass(className.filtered);
}
else if(!isMultiple || (isSearchMultiple && !valueIsSet)) {
module.verbose('Showing placeholder text');
$text.removeClass(className.filtered);
}
},
loading: function() {
$module.addClass(className.loading);
},
placeholderText: function(text) {
text = text || module.get.placeholderText();
module.debug('Setting placeholder text', text);
module.set.text(text);
$text.addClass(className.placeholder);
},
tabbable: function() {
if( module.has.search() ) {
module.debug('Added tabindex to searchable dropdown');
$search
.val('')
.attr('tabindex', 0)
;
$menu
.attr('tabindex', -1)
;
}
else {
module.debug('Added tabindex to dropdown');
if(!$module.attr('tabindex') ) {
$module
.attr('tabindex', 0)
;
$menu
.attr('tabindex', -1)
;
}
}
},
initialLoad: function() {
module.verbose('Setting initial load');
initialLoad = true;
},
activeItem: function($item) {
if( settings.allowAdditions && $item.filter(selector.addition).length > 0 ) {
$item.addClass(className.filtered);
}
else {
$item.addClass(className.active);
}
},
scrollPosition: function($item, forceScroll) {
var
edgeTolerance = 5,
$menu,
hasActive,
offset,
itemHeight,
itemOffset,
menuOffset,
menuScroll,
menuHeight,
abovePage,
belowPage
;
$item = $item || module.get.selectedItem();
$menu = $item.closest(selector.menu);
hasActive = ($item && $item.length > 0);
forceScroll = (forceScroll !== undefined)
? forceScroll
: false
;
if($item && $menu.length > 0 && hasActive) {
itemOffset = $item.position().top;
$menu.addClass(className.loading);
menuScroll = $menu.scrollTop();
menuOffset = $menu.offset().top;
itemOffset = $item.offset().top;
offset = menuScroll - menuOffset + itemOffset;
if(!forceScroll) {
menuHeight = $menu.height();
belowPage = menuScroll + menuHeight < (offset + edgeTolerance);
abovePage = ((offset - edgeTolerance) < menuScroll);
}
module.debug('Scrolling to active item', offset);
if(forceScroll || abovePage || belowPage) {
$menu.scrollTop(offset);
}
$menu.removeClass(className.loading);
}
},
text: function(text) {
if(settings.action !== 'select') {
if(settings.action == 'combo') {
module.debug('Changing combo button text', text, $combo);
if(settings.preserveHTML) {
$combo.html(text);
}
else {
$combo.text(text);
}
}
else {
if(text !== module.get.placeholderText()) {
$text.removeClass(className.placeholder);
}
module.debug('Changing text', text, $text);
$text
.removeClass(className.filtered)
;
if(settings.preserveHTML) {
$text.html(text);
}
else {
$text.text(text);
}
}
}
},
selectedLetter: function(letter) {
var
$selectedItem = $item.filter('.' + className.selected),
alreadySelectedLetter = $selectedItem.length > 0 && module.has.firstLetter($selectedItem, letter),
$nextValue = false,
$nextItem
;
// check next of same letter
if(alreadySelectedLetter) {
$nextItem = $selectedItem.nextAll($item).eq(0);
if( module.has.firstLetter($nextItem, letter) ) {
$nextValue = $nextItem;
}
}
// check all values
if(!$nextValue) {
$item
.each(function(){
if(module.has.firstLetter($(this), letter)) {
$nextValue = $(this);
return false;
}
})
;
}
// set next value
if($nextValue) {
module.verbose('Scrolling to next value with letter', letter);
module.set.scrollPosition($nextValue);
$selectedItem.removeClass(className.selected);
$nextValue.addClass(className.selected);
}
},
direction: function($menu) {
if(settings.direction == 'auto') {
if(module.is.onScreen($menu)) {
module.remove.upward($menu);
}
else {
module.set.upward($menu);
}
}
else if(settings.direction == 'upward') {
module.set.upward($menu);
}
},
upward: function($menu) {
var $element = $menu || $module;
$element.addClass(className.upward);
},
value: function(value, text, $selected) {
var
hasInput = ($input.length > 0),
isAddition = !module.has.value(value),
currentValue = module.get.values(),
stringValue = (value !== undefined)
? String(value)
: value,
newValue
;
if(hasInput) {
if(stringValue == currentValue) {
module.verbose('Skipping value update already same value', value, currentValue);
if(!module.is.initialLoad()) {
return;
}
}
if( module.is.single() && module.has.selectInput() && module.can.extendSelect() ) {
module.debug('Adding user option', value);
module.add.optionValue(value);
}
module.debug('Updating input value', value, currentValue);
internalChange = true;
$input
.val(value)
;
if(settings.fireOnInit === false && module.is.initialLoad()) {
module.debug('Input native change event ignored on initial load');
}
else {
$input.trigger('change');
}
internalChange = false;
}
else {
module.verbose('Storing value in metadata', value, $input);
if(value !== currentValue) {
$module.data(metadata.value, stringValue);
}
}
if(settings.fireOnInit === false && module.is.initialLoad()) {
module.verbose('No callback on initial load', settings.onChange);
}
else {
settings.onChange.call(element, value, text, $selected);
}
},
active: function() {
$module
.addClass(className.active)
;
},
multiple: function() {
$module.addClass(className.multiple);
},
visible: function() {
$module.addClass(className.visible);
},
exactly: function(value, $selectedItem) {
module.debug('Setting selected to exact values');
module.clear();
module.set.selected(value, $selectedItem);
},
selected: function(value, $selectedItem) {
var
isMultiple = module.is.multiple(),
$userSelectedItem
;
$selectedItem = (settings.allowAdditions)
? $selectedItem || module.get.itemWithAdditions(value)
: $selectedItem || module.get.item(value)
;
if(!$selectedItem) {
return;
}
module.debug('Setting selected menu item to', $selectedItem);
if(module.is.single()) {
module.remove.activeItem();
module.remove.selectedItem();
}
else if(settings.useLabels) {
module.remove.selectedItem();
}
// select each item
$selectedItem
.each(function() {
var
$selected = $(this),
selectedText = module.get.choiceText($selected),
selectedValue = module.get.choiceValue($selected, selectedText),
isFiltered = $selected.hasClass(className.filtered),
isActive = $selected.hasClass(className.active),
isUserValue = $selected.hasClass(className.addition),
shouldAnimate = (isMultiple && $selectedItem.length == 1)
;
if(isMultiple) {
if(!isActive || isUserValue) {
if(settings.apiSettings && settings.saveRemoteData) {
module.save.remoteData(selectedText, selectedValue);
}
if(settings.useLabels) {
module.add.value(selectedValue, selectedText, $selected);
module.add.label(selectedValue, selectedText, shouldAnimate);
module.set.activeItem($selected);
module.filterActive();
module.select.nextAvailable($selectedItem);
}
else {
module.add.value(selectedValue, selectedText, $selected);
module.set.text(module.add.variables(message.count));
module.set.activeItem($selected);
}
}
else if(!isFiltered) {
module.debug('Selected active value, removing label');
module.remove.selected(selectedValue);
}
}
else {
if(settings.apiSettings && settings.saveRemoteData) {
module.save.remoteData(selectedText, selectedValue);
}
module.set.text(selectedText);
module.set.value(selectedValue, selectedText, $selected);
$selected
.addClass(className.active)
.addClass(className.selected)
;
}
})
;
}
},
add: {
label: function(value, text, shouldAnimate) {
var
$next = module.is.searchSelection()
? $search
: $text,
$label
;
$label = $('<a />')
.addClass(className.label)
.attr('data-value', value)
.html(templates.label(value, text))
;
$label = settings.onLabelCreate.call($label, value, text);
if(module.has.label(value)) {
module.debug('Label already exists, skipping', value);
return;
}
if(settings.label.variation) {
$label.addClass(settings.label.variation);
}
if(shouldAnimate === true) {
module.debug('Animating in label', $label);
$label
.addClass(className.hidden)
.insertBefore($next)
.transition(settings.label.transition, settings.label.duration)
;
}
else {
module.debug('Adding selection label', $label);
$label
.insertBefore($next)
;
}
},
message: function(message) {
var
$message = $menu.children(selector.message),
html = settings.templates.message(module.add.variables(message))
;
if($message.length > 0) {
$message
.html(html)
;
}
else {
$message = $('<div/>')
.html(html)
.addClass(className.message)
.appendTo($menu)
;
}
},
optionValue: function(value) {
var
$option = $input.find('option[value="' + value + '"]'),
hasOption = ($option.length > 0)
;
if(hasOption) {
return;
}
// temporarily disconnect observer
if(selectObserver) {
selectObserver.disconnect();
module.verbose('Temporarily disconnecting mutation observer', value);
}
if( module.is.single() ) {
module.verbose('Removing previous user addition');
$input.find('option.' + className.addition).remove();
}
$('<option/>')
.prop('value', value)
.addClass(className.addition)
.html(value)
.appendTo($input)
;
module.verbose('Adding user addition as an <option>', value);
if(selectObserver) {
selectObserver.observe($input[0], {
childList : true,
subtree : true
});
}
},
userSuggestion: function(value) {
var
$addition = $menu.children(selector.addition),
$existingItem = module.get.item(value),
alreadyHasValue = $existingItem && $existingItem.not(selector.addition).length,
hasUserSuggestion = $addition.length > 0,
html
;
if(settings.useLabels && module.has.maxSelections()) {
return;
}
if(value === '' || alreadyHasValue) {
$addition.remove();
return;
}
$item
.removeClass(className.selected)
;
if(hasUserSuggestion) {
html = settings.templates.addition( module.add.variables(message.addResult, value) );
$addition
.html(html)
.attr('data-' + metadata.value, value)
.attr('data-' + metadata.text, value)
.removeClass(className.filtered)
.addClass(className.selected)
;
module.verbose('Replacing user suggestion with new value', $addition);
}
else {
$addition = module.create.userChoice(value);
$addition
.prependTo($menu)
.addClass(className.selected)
;
module.verbose('Adding item choice to menu corresponding with user choice addition', $addition);
}
},
variables: function(message, term) {
var
hasCount = (message.search('{count}') !== -1),
hasMaxCount = (message.search('{maxCount}') !== -1),
hasTerm = (message.search('{term}') !== -1),
values,
count,
query
;
module.verbose('Adding templated variables to message', message);
if(hasCount) {
count = module.get.selectionCount();
message = message.replace('{count}', count);
}
if(hasMaxCount) {
count = module.get.selectionCount();
message = message.replace('{maxCount}', settings.maxSelections);
}
if(hasTerm) {
query = term || module.get.query();
message = message.replace('{term}', query);
}
return message;
},
value: function(addedValue, addedText, $selectedItem) {
var
currentValue = module.get.values(),
newValue
;
if(addedValue === '') {
module.debug('Cannot select blank values from multiselect');
return;
}
// extend current array
if($.isArray(currentValue)) {
newValue = currentValue.concat([addedValue]);
newValue = module.get.uniqueArray(newValue);
}
else {
newValue = [addedValue];
}
// add values
if( module.has.selectInput() ) {
if(module.can.extendSelect()) {
module.debug('Adding value to select', addedValue, newValue, $input);
module.add.optionValue(addedValue);
}
}
else {
newValue = newValue.join(settings.delimiter);
module.debug('Setting hidden input to delimited value', newValue, $input);
}
if(settings.fireOnInit === false && module.is.initialLoad()) {
module.verbose('Skipping onadd callback on initial load', settings.onAdd);
}
else {
settings.onAdd.call(element, addedValue, addedText, $selectedItem);
}
module.set.value(newValue, addedValue, addedText, $selectedItem);
module.check.maxSelections();
}
},
remove: {
active: function() {
$module.removeClass(className.active);
},
activeLabel: function() {
$module.find(selector.label).removeClass(className.active);
},
loading: function() {
$module.removeClass(className.loading);
},
initialLoad: function() {
initialLoad = false;
},
upward: function($menu) {
var $element = $menu || $module;
$element.removeClass(className.upward);
},
visible: function() {
$module.removeClass(className.visible);
},
activeItem: function() {
$item.removeClass(className.active);
},
filteredItem: function() {
if(settings.useLabels && module.has.maxSelections() ) {
return;
}
if(settings.useLabels && module.is.multiple()) {
$item.not('.' + className.active).removeClass(className.filtered);
}
else {
$item.removeClass(className.filtered);
}
},
optionValue: function(value) {
var
$option = $input.find('option[value="' + value + '"]'),
hasOption = ($option.length > 0)
;
if(!hasOption || !$option.hasClass(className.addition)) {
return;
}
// temporarily disconnect observer
if(selectObserver) {
selectObserver.disconnect();
module.verbose('Temporarily disconnecting mutation observer', value);
}
$option.remove();
module.verbose('Removing user addition as an <option>', value);
if(selectObserver) {
selectObserver.observe($input[0], {
childList : true,
subtree : true
});
}
},
message: function() {
$menu.children(selector.message).remove();
},
searchTerm: function() {
module.verbose('Cleared search term');
$search.val('');
module.set.filtered();
},
selected: function(value, $selectedItem) {
$selectedItem = (settings.allowAdditions)
? $selectedItem || module.get.itemWithAdditions(value)
: $selectedItem || module.get.item(value)
;
if(!$selectedItem) {
return false;
}
$selectedItem
.each(function() {
var
$selected = $(this),
selectedText = module.get.choiceText($selected),
selectedValue = module.get.choiceValue($selected, selectedText)
;
if(module.is.multiple()) {
if(settings.useLabels) {
module.remove.value(selectedValue, selectedText, $selected);
module.remove.label(selectedValue);
}
else {
module.remove.value(selectedValue, selectedText, $selected);
if(module.get.selectionCount() === 0) {
module.set.placeholderText();
}
else {
module.set.text(module.add.variables(message.count));
}
}
}
else {
module.remove.value(selectedValue, selectedText, $selected);
}
$selected
.removeClass(className.filtered)
.removeClass(className.active)
;
if(settings.useLabels) {
$selected.removeClass(className.selected);
}
})
;
},
selectedItem: function() {
$item.removeClass(className.selected);
},
value: function(removedValue, removedText, $removedItem) {
var
values = module.get.values(),
newValue
;
if( module.has.selectInput() ) {
module.verbose('Input is <select> removing selected option', removedValue);
newValue = module.remove.arrayValue(removedValue, values);
module.remove.optionValue(removedValue);
}
else {
module.verbose('Removing from delimited values', removedValue);
newValue = module.remove.arrayValue(removedValue, values);
newValue = newValue.join(settings.delimiter);
}
if(settings.fireOnInit === false && module.is.initialLoad()) {
module.verbose('No callback on initial load', settings.onRemove);
}
else {
settings.onRemove.call(element, removedValue, removedText, $removedItem);
}
module.set.value(newValue, removedText, $removedItem);
module.check.maxSelections();
},
arrayValue: function(removedValue, values) {
if( !$.isArray(values) ) {
values = [values];
}
values = $.grep(values, function(value){
return (removedValue != value);
});
module.verbose('Removed value from delimited string', removedValue, values);
return values;
},
label: function(value, shouldAnimate) {
var
$labels = $module.find(selector.label),
$removedLabel = $labels.filter('[data-value="' + value +'"]')
;
module.verbose('Removing label', $removedLabel);
$removedLabel.remove();
},
activeLabels: function($activeLabels) {
$activeLabels = $activeLabels || $module.find(selector.label).filter('.' + className.active);
module.verbose('Removing active label selections', $activeLabels);
module.remove.labels($activeLabels);
},
labels: function($labels) {
$labels = $labels || $module.find(selector.label);
module.verbose('Removing labels', $labels);
$labels
.each(function(){
var
value = $(this).data(metadata.value),
stringValue = (value !== undefined)
? String(value)
: value,
isUserValue = module.is.userValue(stringValue)
;
if(isUserValue) {
module.remove.value(stringValue);
module.remove.label(stringValue);
}
else {
// selected will also remove label
module.remove.selected(stringValue);
}
})
;
},
tabbable: function() {
if( module.has.search() ) {
module.debug('Searchable dropdown initialized');
$search
.attr('tabindex', '-1')
;
$menu
.attr('tabindex', '-1')
;
}
else {
module.debug('Simple selection dropdown initialized');
$module
.attr('tabindex', '-1')
;
$menu
.attr('tabindex', '-1')
;
}
}
},
has: {
search: function() {
return ($search.length > 0);
},
selectInput: function() {
return ( $input.is('select') );
},
firstLetter: function($item, letter) {
var
text,
firstLetter
;
if(!$item || $item.length === 0 || typeof letter !== 'string') {
return false;
}
text = module.get.choiceText($item, false);
letter = letter.toLowerCase();
firstLetter = String(text).charAt(0).toLowerCase();
return (letter == firstLetter);
},
input: function() {
return ($input.length > 0);
},
items: function() {
return ($item.length > 0);
},
menu: function() {
return ($menu.length > 0);
},
message: function() {
return ($menu.children(selector.message).length !== 0);
},
label: function(value) {
var
$labels = $module.find(selector.label)
;
return ($labels.filter('[data-value="' + value +'"]').length > 0);
},
maxSelections: function() {
return (settings.maxSelections && module.get.selectionCount() >= settings.maxSelections);
},
allResultsFiltered: function() {
return ($item.filter(selector.unselectable).length === $item.length);
},
query: function() {
return (module.get.query() !== '');
},
value: function(value) {
var
values = module.get.values(),
hasValue = $.isArray(values)
? values && ($.inArray(value, values) !== -1)
: (values == value)
;
return (hasValue)
? true
: false
;
}
},
is: {
active: function() {
return $module.hasClass(className.active);
},
alreadySetup: function() {
return ($module.is('select') && $module.parent(selector.dropdown).length > 0 && $module.prev().length === 0);
},
animating: function($subMenu) {
return ($subMenu)
? $subMenu.transition && $subMenu.transition('is animating')
: $menu.transition && $menu.transition('is animating')
;
},
disabled: function() {
return $module.hasClass(className.disabled);
},
focused: function() {
return (document.activeElement === $module[0]);
},
focusedOnSearch: function() {
return (document.activeElement === $search[0]);
},
allFiltered: function() {
return( (module.is.multiple() || module.has.search()) && !module.has.message() && module.has.allResultsFiltered() );
},
hidden: function($subMenu) {
return !module.is.visible($subMenu);
},
initialLoad: function() {
return initialLoad;
},
onScreen: function($subMenu) {
var
$currentMenu = $subMenu || $menu,
canOpenDownward = true,
onScreen = {},
calculations
;
$currentMenu.addClass(className.loading);
calculations = {
context: {
scrollTop : $context.scrollTop(),
height : $context.outerHeight()
},
menu : {
offset: $currentMenu.offset(),
height: $currentMenu.outerHeight()
}
};
onScreen = {
above : (calculations.context.scrollTop) <= calculations.menu.offset.top - calculations.menu.height,
below : (calculations.context.scrollTop + calculations.context.height) >= calculations.menu.offset.top + calculations.menu.height
};
if(onScreen.below) {
module.verbose('Dropdown can fit in context downward', onScreen);
canOpenDownward = true;
}
else if(!onScreen.below && !onScreen.above) {
module.verbose('Dropdown cannot fit in either direction, favoring downward', onScreen);
canOpenDownward = true;
}
else {
module.verbose('Dropdown cannot fit below, opening upward', onScreen);
canOpenDownward = false;
}
$currentMenu.removeClass(className.loading);
return canOpenDownward;
},
inObject: function(needle, object) {
var
found = false
;
$.each(object, function(index, property) {
if(property == needle) {
found = true;
return true;
}
});
return found;
},
multiple: function() {
return $module.hasClass(className.multiple);
},
single: function() {
return !module.is.multiple();
},
selectMutation: function(mutations) {
var
selectChanged = false
;
$.each(mutations, function(index, mutation) {
if(mutation.target && $(mutation.target).is('select')) {
selectChanged = true;
return true;
}
});
return selectChanged;
},
search: function() {
return $module.hasClass(className.search);
},
searchSelection: function() {
return ( module.has.search() && $search.parent(selector.dropdown).length === 1 );
},
selection: function() {
return $module.hasClass(className.selection);
},
userValue: function(value) {
return ($.inArray(value, module.get.userValues()) !== -1);
},
upward: function($menu) {
var $element = $menu || $module;
return $element.hasClass(className.upward);
},
visible: function($subMenu) {
return ($subMenu)
? $subMenu.hasClass(className.visible)
: $menu.hasClass(className.visible)
;
}
},
can: {
activate: function($item) {
if(settings.useLabels) {
return true;
}
if(!module.has.maxSelections()) {
return true;
}
if(module.has.maxSelections() && $item.hasClass(className.active)) {
return true;
}
return false;
},
click: function() {
return (hasTouch || settings.on == 'click');
},
extendSelect: function() {
return settings.allowAdditions || settings.apiSettings;
},
show: function() {
return !module.is.disabled() && (module.has.items() || module.has.message());
},
useAPI: function() {
return $.fn.api !== undefined;
}
},
animate: {
show: function(callback, $subMenu) {
var
$currentMenu = $subMenu || $menu,
start = ($subMenu)
? function() {}
: function() {
module.hideSubMenus();
module.hideOthers();
module.set.active();
},
transition
;
callback = $.isFunction(callback)
? callback
: function(){}
;
module.verbose('Doing menu show animation', $currentMenu);
module.set.direction($subMenu);
transition = module.get.transition($subMenu);
if( module.is.selection() ) {
module.set.scrollPosition(module.get.selectedItem(), true);
}
if( module.is.hidden($currentMenu) || module.is.animating($currentMenu) ) {
if(transition == 'none') {
start();
$currentMenu.transition('show');
callback.call(element);
}
else if($.fn.transition !== undefined && $module.transition('is supported')) {
$currentMenu
.transition({
animation : transition + ' in',
debug : settings.debug,
verbose : settings.verbose,
duration : settings.duration,
queue : true,
onStart : start,
onComplete : function() {
callback.call(element);
}
})
;
}
else {
module.error(error.noTransition, transition);
}
}
},
hide: function(callback, $subMenu) {
var
$currentMenu = $subMenu || $menu,
duration = ($subMenu)
? (settings.duration * 0.9)
: settings.duration,
start = ($subMenu)
? function() {}
: function() {
if( module.can.click() ) {
module.unbind.intent();
}
module.remove.active();
},
transition = module.get.transition($subMenu)
;
callback = $.isFunction(callback)
? callback
: function(){}
;
if( module.is.visible($currentMenu) || module.is.animating($currentMenu) ) {
module.verbose('Doing menu hide animation', $currentMenu);
if(transition == 'none') {
start();
$currentMenu.transition('hide');
callback.call(element);
}
else if($.fn.transition !== undefined && $module.transition('is supported')) {
$currentMenu
.transition({
animation : transition + ' out',
duration : settings.duration,
debug : settings.debug,
verbose : settings.verbose,
queue : true,
onStart : start,
onComplete : function() {
if(settings.direction == 'auto') {
module.remove.upward($subMenu);
}
callback.call(element);
}
})
;
}
else {
module.error(error.transition);
}
}
}
},
hideAndClear: function() {
module.remove.searchTerm();
if( module.has.maxSelections() ) {
return;
}
if(module.has.search()) {
module.hide(function() {
module.remove.filteredItem();
});
}
else {
module.hide();
}
},
delay: {
show: function() {
module.verbose('Delaying show event to ensure user intent');
clearTimeout(module.timer);
module.timer = setTimeout(module.show, settings.delay.show);
},
hide: function() {
module.verbose('Delaying hide event to ensure user intent');
clearTimeout(module.timer);
module.timer = setTimeout(module.hide, settings.delay.hide);
}
},
escape: {
regExp: function(text) {
text = String(text);
return text.replace(regExp.escape, '\\$&');
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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( (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 = [];
}
},
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 {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: $allModules
;
};
$.fn.dropdown.settings = {
debug : false,
verbose : false,
performance : true,
on : 'click', // what event should show menu action on item selection
action : 'activate', // action on item selection (nothing, activate, select, combo, hide, function(){})
apiSettings : false,
saveRemoteData : true, // Whether remote name/value pairs should be stored in sessionStorage to allow remote data to be restored on page refresh
throttle : 200, // How long to wait after last user input to search remotely
context : window, // Context to use when determining if on screen
direction : 'auto', // Whether dropdown should always open in one direction
keepOnScreen : true, // Whether dropdown should check whether it is on screen before showing
match : 'both', // what to match against with search selection (both, text, or label)
fullTextSearch : false, // search anywhere in value
placeholder : 'auto', // whether to convert blank <select> values to placeholder text
preserveHTML : true, // preserve html when selecting value
sortSelect : false, // sort selection on init
forceSelection : true, // force a choice on blur with search selection
allowAdditions : false, // whether multiple select should allow user added values
maxSelections : false, // When set to a number limits the number of selections to this count
useLabels : true, // whether multiple select should filter currently active selections from choices
delimiter : ',', // when multiselect uses normal <input> the values will be delimited with this character
showOnFocus : true, // show menu on focus
allowTab : true, // add tabindex to element
allowCategorySelection : false, // allow elements with sub-menus to be selected
fireOnInit : false, // Whether callbacks should fire when initializing dropdown values
transition : 'auto', // auto transition will slide down or up based on direction
duration : 200, // duration of transition
glyphWidth : 1.0714, // widest glyph width in em (W is 1.0714 em) used to calculate multiselect input width
// label settings on multi-select
label: {
transition : 'scale',
duration : 200,
variation : false
},
// delay before event
delay : {
hide : 300,
show : 200,
search : 20,
touch : 50
},
/* Callbacks */
onChange : function(value, text, $selected){},
onAdd : function(value, text, $selected){},
onRemove : function(value, text, $selected){},
onLabelSelect : function($selectedLabels){},
onLabelCreate : function(value, text) { return $(this); },
onNoResults : function(searchTerm) { return true; },
onShow : function(){},
onHide : function(){},
/* Component */
name : 'Dropdown',
namespace : 'dropdown',
message: {
addResult : 'Add <b>{term}</b>',
count : '{count} selected',
maxSelections : 'Max {maxCount} selections',
noResults : 'No results found.',
serverError : 'There was an error contacting the server'
},
error : {
action : 'You called a dropdown action that was not defined',
alreadySetup : 'Once a select has been initialized behaviors must be called on the created ui dropdown',
labels : 'Allowing user additions currently requires the use of labels.',
missingMultiple : '<select> requires multiple property to be set to correctly preserve multiple values',
method : 'The method you called is not defined.',
noAPI : 'The API module is required to load resources remotely',
noStorage : 'Saving remote data requires session storage',
noTransition : 'This module requires ui transitions <https://github.com/Semantic-Org/UI-Transition>'
},
regExp : {
escape : /[-[\]{}()*+?.,\\^$|#\s]/g,
},
metadata : {
defaultText : 'defaultText',
defaultValue : 'defaultValue',
placeholderText : 'placeholder',
text : 'text',
value : 'value'
},
// property names for remote query
fields: {
values : 'values', // grouping for all dropdown values
name : 'name', // displayed dropdown text
value : 'value' // actual dropdown value
},
selector : {
addition : '.addition',
dropdown : '.ui.dropdown',
icon : '> .dropdown.icon',
input : '> input[type="hidden"], > select',
item : '.item',
label : '> .label',
remove : '> .label > .delete.icon',
siblingLabel : '.label',
menu : '.menu',
message : '.message',
menuIcon : '.dropdown.icon',
search : 'input.search, .menu > .search > input',
text : '> .text:not(.icon)',
unselectable : '.disabled, .filtered'
},
className : {
active : 'active',
addition : 'addition',
animating : 'animating',
disabled : 'disabled',
dropdown : 'ui dropdown',
filtered : 'filtered',
hidden : 'hidden transition',
item : 'item',
label : 'ui label',
loading : 'loading',
menu : 'menu',
message : 'message',
multiple : 'multiple',
placeholder : 'default',
search : 'search',
selected : 'selected',
selection : 'selection',
upward : 'upward',
visible : 'visible'
}
};
/* Templates */
$.fn.dropdown.settings.templates = {
// generates dropdown from select values
dropdown: function(select) {
var
placeholder = select.placeholder || false,
values = select.values || {},
html = ''
;
html += '<i class="dropdown icon"></i>';
if(select.placeholder) {
html += '<div class="default text">' + placeholder + '</div>';
}
else {
html += '<div class="text"></div>';
}
html += '<div class="menu">';
$.each(select.values, function(index, option) {
html += (option.disabled)
? '<div class="disabled item" data-value="' + option.value + '">' + option.name + '</div>'
: '<div class="item" data-value="' + option.value + '">' + option.name + '</div>'
;
});
html += '</div>';
return html;
},
// generates just menu from select
menu: function(response, fields) {
var
values = response.values || {},
html = ''
;
$.each(response[fields.values], function(index, option) {
html += '<div class="item" data-value="' + option[fields.value] + '">' + option[fields.name] + '</div>';
});
return html;
},
// generates label for multiselect
label: function(value, text) {
return text + '<i class="delete icon"></i>';
},
// generates messages like "No results"
message: function(message) {
return message;
},
// generates user addition to selection menu
addition: function(choice) {
return choice;
}
};
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Video
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ($, window, document, undefined) {
"use strict";
$.fn.embed = function(parameters) {
var
$allModules = $(this),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.embed.settings, parameters)
: $.extend({}, $.fn.embed.settings),
selector = settings.selector,
className = settings.className,
sources = settings.sources,
error = settings.error,
metadata = settings.metadata,
namespace = settings.namespace,
templates = settings.templates,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
$window = $(window),
$module = $(this),
$placeholder = $module.find(selector.placeholder),
$icon = $module.find(selector.icon),
$embed = $module.find(selector.embed),
element = this,
instance = $module.data(moduleNamespace),
module
;
module = {
initialize: function() {
module.debug('Initializing embed');
module.determine.autoplay();
module.create();
module.bind.events();
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of module', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
destroy: function() {
module.verbose('Destroying previous instance of embed');
module.reset();
$module
.removeData(moduleNamespace)
.off(eventNamespace)
;
},
refresh: function() {
module.verbose('Refreshing selector cache');
$placeholder = $module.find(selector.placeholder);
$icon = $module.find(selector.icon);
$embed = $module.find(selector.embed);
},
bind: {
events: function() {
if( module.has.placeholder() ) {
module.debug('Adding placeholder events');
$module
.on('click' + eventNamespace, selector.placeholder, module.createAndShow)
.on('click' + eventNamespace, selector.icon, module.createAndShow)
;
}
}
},
create: function() {
var
placeholder = module.get.placeholder()
;
if(placeholder) {
module.createPlaceholder();
}
else {
module.createAndShow();
}
},
createPlaceholder: function(placeholder) {
var
icon = module.get.icon(),
url = module.get.url(),
embed = module.generate.embed(url)
;
placeholder = placeholder || module.get.placeholder();
$module.html( templates.placeholder(placeholder, icon) );
module.debug('Creating placeholder for embed', placeholder, icon);
},
createEmbed: function(url) {
module.refresh();
url = url || module.get.url();
$embed = $('<div/>')
.addClass(className.embed)
.html( module.generate.embed(url) )
.appendTo($module)
;
settings.onCreate.call(element, url);
module.debug('Creating embed object', $embed);
},
createAndShow: function() {
module.createEmbed();
module.show();
},
// sets new embed
change: function(source, id, url) {
module.debug('Changing video to ', source, id, url);
$module
.data(metadata.source, source)
.data(metadata.id, id)
.data(metadata.url, url)
;
module.create();
},
// clears embed
reset: function() {
module.debug('Clearing embed and showing placeholder');
module.remove.active();
module.remove.embed();
module.showPlaceholder();
settings.onReset.call(element);
},
// shows current embed
show: function() {
module.debug('Showing embed');
module.set.active();
settings.onDisplay.call(element);
},
hide: function() {
module.debug('Hiding embed');
module.showPlaceholder();
},
showPlaceholder: function() {
module.debug('Showing placeholder image');
module.remove.active();
settings.onPlaceholderDisplay.call(element);
},
get: {
id: function() {
return settings.id || $module.data(metadata.id);
},
placeholder: function() {
return settings.placeholder || $module.data(metadata.placeholder);
},
icon: function() {
return (settings.icon)
? settings.icon
: ($module.data(metadata.icon) !== undefined)
? $module.data(metadata.icon)
: module.determine.icon()
;
},
source: function(url) {
return (settings.source)
? settings.source
: ($module.data(metadata.source) !== undefined)
? $module.data(metadata.source)
: module.determine.source()
;
},
type: function() {
var source = module.get.source();
return (sources[source] !== undefined)
? sources[source].type
: false
;
},
url: function() {
return (settings.url)
? settings.url
: ($module.data(metadata.url) !== undefined)
? $module.data(metadata.url)
: module.determine.url()
;
}
},
determine: {
autoplay: function() {
if(module.should.autoplay()) {
settings.autoplay = true;
}
},
source: function(url) {
var
matchedSource = false
;
url = url || module.get.url();
if(url) {
$.each(sources, function(name, source) {
if(url.search(source.domain) !== -1) {
matchedSource = name;
return false;
}
});
}
return matchedSource;
},
icon: function() {
var
source = module.get.source()
;
return (sources[source] !== undefined)
? sources[source].icon
: false
;
},
url: function() {
var
id = settings.id || $module.data(metadata.id),
source = settings.source || $module.data(metadata.source),
url
;
url = (sources[source] !== undefined)
? sources[source].url.replace('{id}', id)
: false
;
if(url) {
$module.data(metadata.url, url);
}
return url;
}
},
set: {
active: function() {
$module.addClass(className.active);
}
},
remove: {
active: function() {
$module.removeClass(className.active);
},
embed: function() {
$embed.empty();
}
},
encode: {
parameters: function(parameters) {
var
urlString = [],
index
;
for (index in parameters) {
urlString.push( encodeURIComponent(index) + '=' + encodeURIComponent( parameters[index] ) );
}
return urlString.join('&');
}
},
generate: {
embed: function(url) {
module.debug('Generating embed html');
var
source = module.get.source(),
html,
parameters
;
url = module.get.url(url);
if(url) {
parameters = module.generate.parameters(source);
html = templates.iframe(url, parameters);
}
else {
module.error(error.noURL, $module);
}
return html;
},
parameters: function(source, extraParameters) {
var
parameters = (sources[source] && sources[source].parameters !== undefined)
? sources[source].parameters(settings)
: {}
;
extraParameters = extraParameters || settings.parameters;
if(extraParameters) {
parameters = $.extend({}, parameters, extraParameters);
}
parameters = settings.onEmbed(parameters);
return module.encode.parameters(parameters);
}
},
has: {
placeholder: function() {
return settings.placeholder || $module.data(metadata.placeholder);
}
},
should: {
autoplay: function() {
return (settings.autoplay === 'auto')
? (settings.placeholder || $module.data(metadata.placeholder) !== undefined)
: settings.autoplay
;
}
},
is: {
video: function() {
return module.get.type() == 'video';
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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 = [];
}
},
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 {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.embed.settings = {
name : 'Embed',
namespace : 'embed',
debug : false,
verbose : false,
performance : true,
icon : false,
source : false,
url : false,
id : false,
// standard video settings
autoplay : 'auto',
color : '#444444',
hd : true,
brandedUI : false,
// additional parameters to include with the embed
parameters: false,
onDisplay : function() {},
onPlaceholderDisplay : function() {},
onReset : function() {},
onCreate : function(url) {},
onEmbed : function(parameters) {
return parameters;
},
metadata : {
id : 'id',
icon : 'icon',
placeholder : 'placeholder',
source : 'source',
url : 'url'
},
error : {
noURL : 'No URL specified',
method : 'The method you called is not defined'
},
className : {
active : 'active',
embed : 'embed'
},
selector : {
embed : '.embed',
placeholder : '.placeholder',
icon : '.icon'
},
sources: {
youtube: {
name : 'youtube',
type : 'video',
icon : 'video play',
domain : 'youtube.com',
url : '//www.youtube.com/embed/{id}',
parameters: function(settings) {
return {
autohide : !settings.brandedUI,
autoplay : settings.autoplay,
color : settings.colors || undefined,
hq : settings.hd,
jsapi : settings.api,
modestbranding : !settings.brandedUI
};
}
},
vimeo: {
name : 'vimeo',
type : 'video',
icon : 'video play',
domain : 'vimeo.com',
url : '//player.vimeo.com/video/{id}',
parameters: function(settings) {
return {
api : settings.api,
autoplay : settings.autoplay,
byline : settings.brandedUI,
color : settings.colors || undefined,
portrait : settings.brandedUI,
title : settings.brandedUI
};
}
}
},
templates: {
iframe : function(url, parameters) {
return ''
+ '<iframe src="' + url + '?' + parameters + '"'
+ ' width="100%" height="100%"'
+ ' frameborder="0" scrolling="no" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'
;
},
placeholder : function(image, icon) {
var
html = ''
;
if(icon) {
html += '<i class="' + icon + ' icon"></i>';
}
if(image) {
html += '<img class="placeholder" src="' + image + '">';
}
return html;
}
},
// NOT YET IMPLEMENTED
api : true,
onPause : function() {},
onPlay : function() {},
onStop : function() {}
};
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Modal
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.fn.modal = function(parameters) {
var
$allModules = $(this),
$window = $(window),
$document = $(document),
$body = $('body'),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { setTimeout(callback, 0); },
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.modal.settings, parameters)
: $.extend({}, $.fn.modal.settings),
selector = settings.selector,
className = settings.className,
namespace = settings.namespace,
error = settings.error,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
$module = $(this),
$context = $(settings.context),
$close = $module.find(selector.close),
$allModals,
$otherModals,
$focusedElement,
$dimmable,
$dimmer,
element = this,
instance = $module.data(moduleNamespace),
elementNamespace,
id,
observer,
module
;
module = {
initialize: function() {
module.verbose('Initializing dimmer', $context);
module.create.id();
module.create.dimmer();
module.refreshModals();
module.bind.events();
if(settings.observeChanges) {
module.observeChanges();
}
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of modal');
instance = module;
$module
.data(moduleNamespace, instance)
;
},
create: {
dimmer: function() {
var
defaultSettings = {
debug : settings.debug,
dimmerName : 'modals',
duration : {
show : settings.duration,
hide : settings.duration
}
},
dimmerSettings = $.extend(true, defaultSettings, settings.dimmerSettings)
;
if(settings.inverted) {
dimmerSettings.variation = (dimmerSettings.variation !== undefined)
? dimmerSettings.variation + ' inverted'
: 'inverted'
;
}
if($.fn.dimmer === undefined) {
module.error(error.dimmer);
return;
}
module.debug('Creating dimmer with settings', dimmerSettings);
$dimmable = $context.dimmer(dimmerSettings);
if(settings.detachable) {
module.verbose('Modal is detachable, moving content into dimmer');
$dimmable.dimmer('add content', $module);
}
else {
module.set.undetached();
}
if(settings.blurring) {
$dimmable.addClass(className.blurring);
}
$dimmer = $dimmable.dimmer('get dimmer');
},
id: function() {
id = (Math.random().toString(16) + '000000000').substr(2,8);
elementNamespace = '.' + id;
module.verbose('Creating unique id for element', id);
}
},
destroy: function() {
module.verbose('Destroying previous modal');
$module
.removeData(moduleNamespace)
.off(eventNamespace)
;
$window.off(elementNamespace);
$close.off(eventNamespace);
$context.dimmer('destroy');
},
observeChanges: function() {
if('MutationObserver' in window) {
observer = new MutationObserver(function(mutations) {
module.debug('DOM tree modified, refreshing');
module.refresh();
});
observer.observe(element, {
childList : true,
subtree : true
});
module.debug('Setting up mutation observer', observer);
}
},
refresh: function() {
module.remove.scrolling();
module.cacheSizes();
module.set.screenHeight();
module.set.type();
module.set.position();
},
refreshModals: function() {
$otherModals = $module.siblings(selector.modal);
$allModals = $otherModals.add($module);
},
attachEvents: function(selector, event) {
var
$toggle = $(selector)
;
event = $.isFunction(module[event])
? module[event]
: module.toggle
;
if($toggle.length > 0) {
module.debug('Attaching modal events to element', selector, event);
$toggle
.off(eventNamespace)
.on('click' + eventNamespace, event)
;
}
else {
module.error(error.notFound, selector);
}
},
bind: {
events: function() {
module.verbose('Attaching events');
$module
.on('click' + eventNamespace, selector.close, module.event.close)
.on('click' + eventNamespace, selector.approve, module.event.approve)
.on('click' + eventNamespace, selector.deny, module.event.deny)
;
$window
.on('resize' + elementNamespace, module.event.resize)
;
}
},
get: {
id: function() {
return (Math.random().toString(16) + '000000000').substr(2,8);
}
},
event: {
approve: function() {
if(settings.onApprove.call(element, $(this)) === false) {
module.verbose('Approve callback returned false cancelling hide');
return;
}
module.hide();
},
deny: function() {
if(settings.onDeny.call(element, $(this)) === false) {
module.verbose('Deny callback returned false cancelling hide');
return;
}
module.hide();
},
close: function() {
module.hide();
},
click: function(event) {
var
$target = $(event.target),
isInModal = ($target.closest(selector.modal).length > 0),
isInDOM = $.contains(document.documentElement, event.target)
;
if(!isInModal && isInDOM) {
module.debug('Dimmer clicked, hiding all modals');
if( module.is.active() ) {
module.remove.clickaway();
if(settings.allowMultiple) {
module.hide();
}
else {
module.hideAll();
}
}
}
},
debounce: function(method, delay) {
clearTimeout(module.timer);
module.timer = setTimeout(method, delay);
},
keyboard: function(event) {
var
keyCode = event.which,
escapeKey = 27
;
if(keyCode == escapeKey) {
if(settings.closable) {
module.debug('Escape key pressed hiding modal');
module.hide();
}
else {
module.debug('Escape key pressed, but closable is set to false');
}
event.preventDefault();
}
},
resize: function() {
if( $dimmable.dimmer('is active') ) {
requestAnimationFrame(module.refresh);
}
}
},
toggle: function() {
if( module.is.active() || module.is.animating() ) {
module.hide();
}
else {
module.show();
}
},
show: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
module.refreshModals();
module.showModal(callback);
},
hide: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
module.refreshModals();
module.hideModal(callback);
},
showModal: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if( module.is.animating() || !module.is.active() ) {
module.showDimmer();
module.cacheSizes();
module.set.position();
module.set.screenHeight();
module.set.type();
module.set.clickaway();
if( !settings.allowMultiple && module.others.active() ) {
module.hideOthers(module.showModal);
}
else {
settings.onShow.call(element);
if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
module.debug('Showing modal with css animations');
$module
.transition({
debug : settings.debug,
animation : settings.transition + ' in',
queue : settings.queue,
duration : settings.duration,
useFailSafe : true,
onComplete : function() {
settings.onVisible.apply(element);
module.add.keyboardShortcuts();
module.save.focus();
module.set.active();
if(settings.autofocus) {
module.set.autofocus();
}
callback();
}
})
;
}
else {
module.error(error.noTransition);
}
}
}
else {
module.debug('Modal is already visible');
}
},
hideModal: function(callback, keepDimmed) {
callback = $.isFunction(callback)
? callback
: function(){}
;
module.debug('Hiding modal');
settings.onHide.call(element);
if( module.is.animating() || module.is.active() ) {
if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
module.remove.active();
$module
.transition({
debug : settings.debug,
animation : settings.transition + ' out',
queue : settings.queue,
duration : settings.duration,
useFailSafe : true,
onStart : function() {
if(!module.others.active() && !keepDimmed) {
module.hideDimmer();
}
module.remove.keyboardShortcuts();
},
onComplete : function() {
settings.onHidden.call(element);
module.restore.focus();
callback();
}
})
;
}
else {
module.error(error.noTransition);
}
}
},
showDimmer: function() {
if($dimmable.dimmer('is animating') || !$dimmable.dimmer('is active') ) {
module.debug('Showing dimmer');
$dimmable.dimmer('show');
}
else {
module.debug('Dimmer already visible');
}
},
hideDimmer: function() {
if( $dimmable.dimmer('is animating') || ($dimmable.dimmer('is active')) ) {
$dimmable.dimmer('hide', function() {
module.remove.clickaway();
module.remove.screenHeight();
});
}
else {
module.debug('Dimmer is not visible cannot hide');
return;
}
},
hideAll: function(callback) {
var
$visibleModals = $allModals.filter('.' + className.active + ', .' + className.animating)
;
callback = $.isFunction(callback)
? callback
: function(){}
;
if( $visibleModals.length > 0 ) {
module.debug('Hiding all visible modals');
module.hideDimmer();
$visibleModals
.modal('hide modal', callback)
;
}
},
hideOthers: function(callback) {
var
$visibleModals = $otherModals.filter('.' + className.active + ', .' + className.animating)
;
callback = $.isFunction(callback)
? callback
: function(){}
;
if( $visibleModals.length > 0 ) {
module.debug('Hiding other modals', $otherModals);
$visibleModals
.modal('hide modal', callback, true)
;
}
},
others: {
active: function() {
return ($otherModals.filter('.' + className.active).length > 0);
},
animating: function() {
return ($otherModals.filter('.' + className.animating).length > 0);
}
},
add: {
keyboardShortcuts: function() {
module.verbose('Adding keyboard shortcuts');
$document
.on('keyup' + eventNamespace, module.event.keyboard)
;
}
},
save: {
focus: function() {
$focusedElement = $(document.activeElement).blur();
}
},
restore: {
focus: function() {
if($focusedElement && $focusedElement.length > 0) {
$focusedElement.focus();
}
}
},
remove: {
active: function() {
$module.removeClass(className.active);
},
clickaway: function() {
if(settings.closable) {
$dimmer
.off('click' + elementNamespace)
;
}
},
bodyStyle: function() {
if($body.attr('style') === '') {
module.verbose('Removing style attribute');
$body.removeAttr('style');
}
},
screenHeight: function() {
module.debug('Removing page height');
$body
.css('height', '')
;
},
keyboardShortcuts: function() {
module.verbose('Removing keyboard shortcuts');
$document
.off('keyup' + eventNamespace)
;
},
scrolling: function() {
$dimmable.removeClass(className.scrolling);
$module.removeClass(className.scrolling);
}
},
cacheSizes: function() {
var
modalHeight = $module.outerHeight()
;
if(module.cache === undefined || modalHeight !== 0) {
module.cache = {
pageHeight : $(document).outerHeight(),
height : modalHeight + settings.offset,
contextHeight : (settings.context == 'body')
? $(window).height()
: $dimmable.height()
};
}
module.debug('Caching modal and container sizes', module.cache);
},
can: {
fit: function() {
return ( ( module.cache.height + (settings.padding * 2) ) < module.cache.contextHeight);
}
},
is: {
active: function() {
return $module.hasClass(className.active);
},
animating: function() {
return $module.transition('is supported')
? $module.transition('is animating')
: $module.is(':visible')
;
},
scrolling: function() {
return $dimmable.hasClass(className.scrolling);
},
modernBrowser: function() {
// appName for IE11 reports 'Netscape' can no longer use
return !(window.ActiveXObject || "ActiveXObject" in window);
}
},
set: {
autofocus: function() {
var
$inputs = $module.find(':input').filter(':visible'),
$autofocus = $inputs.filter('[autofocus]'),
$input = ($autofocus.length > 0)
? $autofocus.first()
: $inputs.first()
;
if($input.length > 0) {
$input.focus();
}
},
clickaway: function() {
if(settings.closable) {
$dimmer
.on('click' + elementNamespace, module.event.click)
;
}
},
screenHeight: function() {
if( module.can.fit() ) {
$body.css('height', '');
}
else {
module.debug('Modal is taller than page content, resizing page height');
$body
.css('height', module.cache.height + (settings.padding * 2) )
;
}
},
active: function() {
$module.addClass(className.active);
},
scrolling: function() {
$dimmable.addClass(className.scrolling);
$module.addClass(className.scrolling);
},
type: function() {
if(module.can.fit()) {
module.verbose('Modal fits on screen');
if(!module.others.active() && !module.others.animating()) {
module.remove.scrolling();
}
}
else {
module.verbose('Modal cannot fit on screen setting to scrolling');
module.set.scrolling();
}
},
position: function() {
module.verbose('Centering modal on page', module.cache);
if(module.can.fit()) {
$module
.css({
top: '',
marginTop: -(module.cache.height / 2)
})
;
}
else {
$module
.css({
marginTop : '',
top : $document.scrollTop()
})
;
}
},
undetached: function() {
$dimmable.addClass(className.undetached);
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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( (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 = [];
}
},
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($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.modal.settings = {
name : 'Modal',
namespace : 'modal',
debug : false,
verbose : false,
performance : true,
observeChanges : false,
allowMultiple : false,
detachable : true,
closable : true,
autofocus : true,
inverted : false,
blurring : false,
dimmerSettings : {
closable : false,
useCSS : true
},
context : 'body',
queue : false,
duration : 500,
offset : 0,
transition : 'scale',
// padding with edge of page
padding : 50,
// called before show animation
onShow : function(){},
// called after show animation
onVisible : function(){},
// called before hide animation
onHide : function(){},
// called after hide animation
onHidden : function(){},
// called after approve selector match
onApprove : function(){ return true; },
// called after deny selector match
onDeny : function(){ return true; },
selector : {
close : '> .close',
approve : '.actions .positive, .actions .approve, .actions .ok',
deny : '.actions .negative, .actions .deny, .actions .cancel',
modal : '.ui.modal'
},
error : {
dimmer : 'UI Dimmer, a required component is not included in this page',
method : 'The method you called is not defined.',
notFound : 'The element you specified could not be found'
},
className : {
active : 'active',
animating : 'animating',
blurring : 'blurring',
scrolling : 'scrolling',
undetached : 'undetached'
}
};
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Nag
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ($, window, document, undefined) {
"use strict";
$.fn.nag = function(parameters) {
var
$allModules = $(this),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.nag.settings, parameters)
: $.extend({}, $.fn.nag.settings),
className = settings.className,
selector = settings.selector,
error = settings.error,
namespace = settings.namespace,
eventNamespace = '.' + namespace,
moduleNamespace = namespace + '-module',
$module = $(this),
$close = $module.find(selector.close),
$context = (settings.context)
? $(settings.context)
: $('body'),
element = this,
instance = $module.data(moduleNamespace),
moduleOffset,
moduleHeight,
contextWidth,
contextHeight,
contextOffset,
yOffset,
yPosition,
timer,
module,
requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { setTimeout(callback, 0); }
;
module = {
initialize: function() {
module.verbose('Initializing element');
$module
.on('click' + eventNamespace, selector.close, module.dismiss)
.data(moduleNamespace, module)
;
if(settings.detachable && $module.parent()[0] !== $context[0]) {
$module
.detach()
.prependTo($context)
;
}
if(settings.displayTime > 0) {
setTimeout(module.hide, settings.displayTime);
}
module.show();
},
destroy: function() {
module.verbose('Destroying instance');
$module
.removeData(moduleNamespace)
.off(eventNamespace)
;
},
show: function() {
if( module.should.show() && !$module.is(':visible') ) {
module.debug('Showing nag', settings.animation.show);
if(settings.animation.show == 'fade') {
$module
.fadeIn(settings.duration, settings.easing)
;
}
else {
$module
.slideDown(settings.duration, settings.easing)
;
}
}
},
hide: function() {
module.debug('Showing nag', settings.animation.hide);
if(settings.animation.show == 'fade') {
$module
.fadeIn(settings.duration, settings.easing)
;
}
else {
$module
.slideUp(settings.duration, settings.easing)
;
}
},
onHide: function() {
module.debug('Removing nag', settings.animation.hide);
$module.remove();
if (settings.onHide) {
settings.onHide();
}
},
dismiss: function(event) {
if(settings.storageMethod) {
module.storage.set(settings.key, settings.value);
}
module.hide();
event.stopImmediatePropagation();
event.preventDefault();
},
should: {
show: function() {
if(settings.persist) {
module.debug('Persistent nag is set, can show nag');
return true;
}
if( module.storage.get(settings.key) != settings.value.toString() ) {
module.debug('Stored value is not set, can show nag', module.storage.get(settings.key));
return true;
}
module.debug('Stored value is set, cannot show nag', module.storage.get(settings.key));
return false;
}
},
get: {
storageOptions: function() {
var
options = {}
;
if(settings.expires) {
options.expires = settings.expires;
}
if(settings.domain) {
options.domain = settings.domain;
}
if(settings.path) {
options.path = settings.path;
}
return options;
}
},
clear: function() {
module.storage.remove(settings.key);
},
storage: {
set: function(key, value) {
var
options = module.get.storageOptions()
;
if(settings.storageMethod == 'localstorage' && window.localStorage !== undefined) {
window.localStorage.setItem(key, value);
module.debug('Value stored using local storage', key, value);
}
else if(settings.storageMethod == 'sessionstorage' && window.sessionStorage !== undefined) {
window.sessionStorage.setItem(key, value);
module.debug('Value stored using session storage', key, value);
}
else if($.cookie !== undefined) {
$.cookie(key, value, options);
module.debug('Value stored using cookie', key, value, options);
}
else {
module.error(error.noCookieStorage);
return;
}
},
get: function(key, value) {
var
storedValue
;
if(settings.storageMethod == 'localstorage' && window.localStorage !== undefined) {
storedValue = window.localStorage.getItem(key);
}
else if(settings.storageMethod == 'sessionstorage' && window.sessionStorage !== undefined) {
storedValue = window.sessionStorage.getItem(key);
}
// get by cookie
else if($.cookie !== undefined) {
storedValue = $.cookie(key);
}
else {
module.error(error.noCookieStorage);
}
if(storedValue == 'undefined' || storedValue == 'null' || storedValue === undefined || storedValue === null) {
storedValue = undefined;
}
return storedValue;
},
remove: function(key) {
var
options = module.get.storageOptions()
;
if(settings.storageMethod == 'localstorage' && window.localStorage !== undefined) {
window.localStorage.removeItem(key);
}
else if(settings.storageMethod == 'sessionstorage' && window.sessionStorage !== undefined) {
window.sessionStorage.removeItem(key);
}
// store by cookie
else if($.cookie !== undefined) {
$.removeCookie(key, options);
}
else {
module.error(error.noStorage);
}
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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( (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 = [];
}
},
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 {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.nag.settings = {
name : 'Nag',
debug : false,
verbose : false,
performance : true,
namespace : 'Nag',
// allows cookie to be overriden
persist : false,
// set to zero to require manually dismissal, otherwise hides on its own
displayTime : 0,
animation : {
show : 'slide',
hide : 'slide'
},
context : false,
detachable : false,
expires : 30,
domain : false,
path : '/',
// type of storage to use
storageMethod : 'cookie',
// value to store in dismissed localstorage/cookie
key : 'nag',
value : 'dismiss',
error: {
noCookieStorage : '$.cookie is not included. A storage solution is required.',
noStorage : 'Neither $.cookie or store is defined. A storage solution is required for storing state',
method : 'The method you called is not defined.'
},
className : {
bottom : 'bottom',
fixed : 'fixed'
},
selector : {
close : '.close.icon'
},
speed : 500,
easing : 'easeOutQuad',
onHide: function() {}
};
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Popup
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ($, window, document, undefined) {
"use strict";
$.fn.popup = function(parameters) {
var
$allModules = $(this),
$document = $(document),
$window = $(window),
$body = $('body'),
moduleSelector = $allModules.selector || '',
hasTouch = (true),
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.popup.settings, parameters)
: $.extend({}, $.fn.popup.settings),
selector = settings.selector,
className = settings.className,
error = settings.error,
metadata = settings.metadata,
namespace = settings.namespace,
eventNamespace = '.' + settings.namespace,
moduleNamespace = 'module-' + namespace,
$module = $(this),
$context = $(settings.context),
$target = (settings.target)
? $(settings.target)
: $module,
$popup,
$offsetParent,
searchDepth = 0,
triedPositions = false,
openedWithTouch = false,
element = this,
instance = $module.data(moduleNamespace),
elementNamespace,
id,
module
;
module = {
// binds events
initialize: function() {
module.debug('Initializing', $module);
module.createID();
module.bind.events();
if( !module.exists() && settings.preserve) {
module.create();
}
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance', module);
instance = module;
$module
.data(moduleNamespace, instance)
;
},
refresh: function() {
if(settings.popup) {
$popup = $(settings.popup).eq(0);
}
else {
if(settings.inline) {
$popup = $target.nextAll(selector.popup).eq(0);
settings.popup = $popup;
}
}
if(settings.popup) {
$popup.addClass(className.loading);
$offsetParent = module.get.offsetParent();
$popup.removeClass(className.loading);
if(settings.movePopup && module.has.popup() && module.get.offsetParent($popup)[0] !== $offsetParent[0]) {
module.debug('Moving popup to the same offset parent as activating element');
$popup
.detach()
.appendTo($offsetParent)
;
}
}
else {
$offsetParent = (settings.inline)
? module.get.offsetParent($target)
: module.has.popup()
? module.get.offsetParent($popup)
: $body
;
}
if( $offsetParent.is('html') && $offsetParent[0] !== $body[0] ) {
module.debug('Setting page as offset parent');
$offsetParent = $body;
}
if( module.get.variation() ) {
module.set.variation();
}
},
reposition: function() {
module.refresh();
module.set.position();
},
destroy: function() {
module.debug('Destroying previous module');
// remove element only if was created dynamically
if($popup && !settings.preserve) {
module.removePopup();
}
// clear all timeouts
clearTimeout(module.hideTimer);
clearTimeout(module.showTimer);
// remove events
$window.off(elementNamespace);
$module
.off(eventNamespace)
.removeData(moduleNamespace)
;
},
event: {
start: function(event) {
var
delay = ($.isPlainObject(settings.delay))
? settings.delay.show
: settings.delay
;
clearTimeout(module.hideTimer);
if(!openedWithTouch) {
module.showTimer = setTimeout(module.show, delay);
}
},
end: function() {
var
delay = ($.isPlainObject(settings.delay))
? settings.delay.hide
: settings.delay
;
clearTimeout(module.showTimer);
module.hideTimer = setTimeout(module.hide, delay);
},
touchstart: function(event) {
openedWithTouch = true;
module.show();
},
resize: function() {
if( module.is.visible() ) {
module.set.position();
}
},
hideGracefully: function(event) {
// don't close on clicks inside popup
if(event && $(event.target).closest(selector.popup).length === 0) {
module.debug('Click occurred outside popup hiding popup');
module.hide();
}
else {
module.debug('Click was inside popup, keeping popup open');
}
}
},
// generates popup html from metadata
create: function() {
var
html = module.get.html(),
title = module.get.title(),
content = module.get.content()
;
if(html || content || title) {
module.debug('Creating pop-up html');
if(!html) {
html = settings.templates.popup({
title : title,
content : content
});
}
$popup = $('<div/>')
.addClass(className.popup)
.data(metadata.activator, $module)
.html(html)
;
if(settings.inline) {
module.verbose('Inserting popup element inline', $popup);
$popup
.insertAfter($module)
;
}
else {
module.verbose('Appending popup element to body', $popup);
$popup
.appendTo( $context )
;
}
module.refresh();
module.set.variation();
if(settings.hoverable) {
module.bind.popup();
}
settings.onCreate.call($popup, element);
}
else if($target.next(selector.popup).length !== 0) {
module.verbose('Pre-existing popup found');
settings.inline = true;
settings.popups = $target.next(selector.popup).data(metadata.activator, $module);
module.refresh();
if(settings.hoverable) {
module.bind.popup();
}
}
else if(settings.popup) {
$(settings.popup).data(metadata.activator, $module);
module.verbose('Used popup specified in settings');
module.refresh();
if(settings.hoverable) {
module.bind.popup();
}
}
else {
module.debug('No content specified skipping display', element);
}
},
createID: function() {
id = (Math.random().toString(16) + '000000000').substr(2,8);
elementNamespace = '.' + id;
module.verbose('Creating unique id for element', id);
},
// determines popup state
toggle: function() {
module.debug('Toggling pop-up');
if( module.is.hidden() ) {
module.debug('Popup is hidden, showing pop-up');
module.unbind.close();
module.show();
}
else {
module.debug('Popup is visible, hiding pop-up');
module.hide();
}
},
show: function(callback) {
callback = callback || function(){};
module.debug('Showing pop-up', settings.transition);
if(module.is.hidden() && !( module.is.active() && module.is.dropdown()) ) {
if( !module.exists() ) {
module.create();
}
if(settings.onShow.call($popup, element) === false) {
module.debug('onShow callback returned false, cancelling popup animation');
return;
}
else if(!settings.preserve && !settings.popup) {
module.refresh();
}
if( $popup && module.set.position() ) {
module.save.conditions();
if(settings.exclusive) {
module.hideAll();
}
module.animate.show(callback);
}
}
},
hide: function(callback) {
callback = callback || function(){};
if( module.is.visible() || module.is.animating() ) {
if(settings.onHide.call($popup, element) === false) {
module.debug('onHide callback returned false, cancelling popup animation');
return;
}
module.remove.visible();
module.unbind.close();
module.restore.conditions();
module.animate.hide(callback);
}
},
hideAll: function() {
$(selector.popup)
.filter('.' + className.visible)
.each(function() {
$(this)
.data(metadata.activator)
.popup('hide')
;
})
;
},
exists: function() {
if(!$popup) {
return false;
}
if(settings.inline || settings.popup) {
return ( module.has.popup() );
}
else {
return ( $popup.closest($context).length >= 1 )
? true
: false
;
}
},
removePopup: function() {
if( module.has.popup() && !settings.popup) {
module.debug('Removing popup', $popup);
$popup.remove();
$popup = undefined;
settings.onRemove.call($popup, element);
}
},
save: {
conditions: function() {
module.cache = {
title: $module.attr('title')
};
if (module.cache.title) {
$module.removeAttr('title');
}
module.verbose('Saving original attributes', module.cache.title);
}
},
restore: {
conditions: function() {
if(module.cache && module.cache.title) {
$module.attr('title', module.cache.title);
module.verbose('Restoring original attributes', module.cache.title);
}
return true;
}
},
animate: {
show: function(callback) {
callback = $.isFunction(callback) ? callback : function(){};
if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
module.set.visible();
$popup
.transition({
animation : settings.transition + ' in',
queue : false,
debug : settings.debug,
verbose : settings.verbose,
duration : settings.duration,
onComplete : function() {
module.bind.close();
callback.call($popup, element);
settings.onVisible.call($popup, element);
}
})
;
}
else {
module.error(error.noTransition);
}
},
hide: function(callback) {
callback = $.isFunction(callback) ? callback : function(){};
module.debug('Hiding pop-up');
if(settings.onHide.call($popup, element) === false) {
module.debug('onHide callback returned false, cancelling popup animation');
return;
}
if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
$popup
.transition({
animation : settings.transition + ' out',
queue : false,
duration : settings.duration,
debug : settings.debug,
verbose : settings.verbose,
onComplete : function() {
module.reset();
callback.call($popup, element);
settings.onHidden.call($popup, element);
}
})
;
}
else {
module.error(error.noTransition);
}
}
},
get: {
html: function() {
$module.removeData(metadata.html);
return $module.data(metadata.html) || settings.html;
},
title: function() {
$module.removeData(metadata.title);
return $module.data(metadata.title) || settings.title;
},
content: function() {
$module.removeData(metadata.content);
return $module.data(metadata.content) || $module.attr('title') || settings.content;
},
variation: function() {
$module.removeData(metadata.variation);
return $module.data(metadata.variation) || settings.variation;
},
popupOffset: function() {
return $popup.offset();
},
calculations: function() {
var
targetElement = $target[0],
targetPosition = (settings.inline || settings.popup)
? $target.position()
: $target.offset(),
calculations = {},
screen
;
calculations = {
// element which is launching popup
target : {
element : $target[0],
width : $target.outerWidth(),
height : $target.outerHeight(),
top : targetPosition.top,
left : targetPosition.left,
margin : {}
},
// popup itself
popup : {
width : $popup.outerWidth(),
height : $popup.outerHeight()
},
// offset container (or 3d context)
parent : {
width : $offsetParent.outerWidth(),
height : $offsetParent.outerHeight()
},
// screen boundaries
screen : {
scroll: {
top : $window.scrollTop(),
left : $window.scrollLeft()
},
width : $window.width(),
height : $window.height()
}
};
// add in container calcs if fluid
if( settings.setFluidWidth && module.is.fluid() ) {
calculations.container = {
width: $popup.parent().outerWidth()
};
calculations.popup.width = calculations.container.width;
}
// add in margins if inline
calculations.target.margin.top = (settings.inline)
? parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-top'), 10)
: 0
;
calculations.target.margin.left = (settings.inline)
? module.is.rtl()
? parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-right'), 10)
: parseInt( window.getComputedStyle(targetElement).getPropertyValue('margin-left') , 10)
: 0
;
// calculate screen boundaries
screen = calculations.screen;
calculations.boundary = {
top : screen.scroll.top,
bottom : screen.scroll.top + screen.height,
left : screen.scroll.left,
right : screen.scroll.left + screen.width
};
return calculations;
},
id: function() {
return id;
},
startEvent: function() {
if(settings.on == 'hover') {
return 'mouseenter';
}
else if(settings.on == 'focus') {
return 'focus';
}
return false;
},
scrollEvent: function() {
return 'scroll';
},
endEvent: function() {
if(settings.on == 'hover') {
return 'mouseleave';
}
else if(settings.on == 'focus') {
return 'blur';
}
return false;
},
distanceFromBoundary: function(offset, calculations) {
var
distanceFromBoundary = {},
popup,
boundary
;
offset = offset || module.get.offset();
calculations = calculations || module.get.calculations();
// shorthand
popup = calculations.popup;
boundary = calculations.boundary;
if(offset) {
distanceFromBoundary = {
top : (offset.top - boundary.top),
left : (offset.left - boundary.left),
right : (boundary.right - (offset.left + popup.width) ),
bottom : (boundary.bottom - (offset.top + popup.height) )
};
module.verbose('Distance from boundaries determined', offset, distanceFromBoundary);
}
return distanceFromBoundary;
},
offsetParent: function($target) {
var
element = ($target !== undefined)
? $target[0]
: $module[0],
parentNode = element.parentNode,
$node = $(parentNode)
;
if(parentNode) {
var
is2D = ($node.css('transform') === 'none'),
isStatic = ($node.css('position') === 'static'),
isHTML = $node.is('html')
;
while(parentNode && !isHTML && isStatic && is2D) {
parentNode = parentNode.parentNode;
$node = $(parentNode);
is2D = ($node.css('transform') === 'none');
isStatic = ($node.css('position') === 'static');
isHTML = $node.is('html');
}
}
return ($node && $node.length > 0)
? $node
: $()
;
},
positions: function() {
return {
'top left' : false,
'top center' : false,
'top right' : false,
'bottom left' : false,
'bottom center' : false,
'bottom right' : false,
'left center' : false,
'right center' : false
};
},
nextPosition: function(position) {
var
positions = position.split(' '),
verticalPosition = positions[0],
horizontalPosition = positions[1],
opposite = {
top : 'bottom',
bottom : 'top',
left : 'right',
right : 'left'
},
adjacent = {
left : 'center',
center : 'right',
right : 'left'
},
backup = {
'top left' : 'top center',
'top center' : 'top right',
'top right' : 'right center',
'right center' : 'bottom right',
'bottom right' : 'bottom center',
'bottom center' : 'bottom left',
'bottom left' : 'left center',
'left center' : 'top left'
},
adjacentsAvailable = (verticalPosition == 'top' || verticalPosition == 'bottom'),
oppositeTried = false,
adjacentTried = false,
nextPosition = false
;
if(!triedPositions) {
module.verbose('All available positions available');
triedPositions = module.get.positions();
}
module.debug('Recording last position tried', position);
triedPositions[position] = true;
if(settings.prefer === 'opposite') {
nextPosition = [opposite[verticalPosition], horizontalPosition];
nextPosition = nextPosition.join(' ');
oppositeTried = (triedPositions[nextPosition] === true);
module.debug('Trying opposite strategy', nextPosition);
}
if((settings.prefer === 'adjacent') && adjacentsAvailable ) {
nextPosition = [verticalPosition, adjacent[horizontalPosition]];
nextPosition = nextPosition.join(' ');
adjacentTried = (triedPositions[nextPosition] === true);
module.debug('Trying adjacent strategy', nextPosition);
}
if(adjacentTried || oppositeTried) {
module.debug('Using backup position', nextPosition);
nextPosition = backup[position];
}
return nextPosition;
}
},
set: {
position: function(position, calculations) {
// exit conditions
if($target.length === 0 || $popup.length === 0) {
module.error(error.notFound);
return;
}
var
offset,
distanceAway,
target,
popup,
parent,
positioning,
popupOffset,
distanceFromBoundary
;
calculations = calculations || module.get.calculations();
position = position || $module.data(metadata.position) || settings.position;
offset = $module.data(metadata.offset) || settings.offset;
distanceAway = settings.distanceAway;
// shorthand
target = calculations.target;
popup = calculations.popup;
parent = calculations.parent;
if(target.width === 0 && target.height === 0) {
module.debug('Popup target is hidden, no action taken');
return false;
}
if(settings.inline) {
module.debug('Adding margin to calculation', target.margin);
if(position == 'left center' || position == 'right center') {
offset += target.margin.top;
distanceAway += -target.margin.left;
}
else if (position == 'top left' || position == 'top center' || position == 'top right') {
offset += target.margin.left;
distanceAway -= target.margin.top;
}
else {
offset += target.margin.left;
distanceAway += target.margin.top;
}
}
module.debug('Determining popup position from calculations', position, calculations);
if (module.is.rtl()) {
position = position.replace(/left|right/g, function (match) {
return (match == 'left')
? 'right'
: 'left'
;
});
module.debug('RTL: Popup position updated', position);
}
// if last attempt use specified last resort position
if(searchDepth == settings.maxSearchDepth && typeof settings.lastResort === 'string') {
position = settings.lastResort;
}
switch (position) {
case 'top left':
positioning = {
top : 'auto',
bottom : parent.height - target.top + distanceAway,
left : target.left + offset,
right : 'auto'
};
break;
case 'top center':
positioning = {
bottom : parent.height - target.top + distanceAway,
left : target.left + (target.width / 2) - (popup.width / 2) + offset,
top : 'auto',
right : 'auto'
};
break;
case 'top right':
positioning = {
bottom : parent.height - target.top + distanceAway,
right : parent.width - target.left - target.width - offset,
top : 'auto',
left : 'auto'
};
break;
case 'left center':
positioning = {
top : target.top + (target.height / 2) - (popup.height / 2) + offset,
right : parent.width - target.left + distanceAway,
left : 'auto',
bottom : 'auto'
};
break;
case 'right center':
positioning = {
top : target.top + (target.height / 2) - (popup.height / 2) + offset,
left : target.left + target.width + distanceAway,
bottom : 'auto',
right : 'auto'
};
break;
case 'bottom left':
positioning = {
top : target.top + target.height + distanceAway,
left : target.left + offset,
bottom : 'auto',
right : 'auto'
};
break;
case 'bottom center':
positioning = {
top : target.top + target.height + distanceAway,
left : target.left + (target.width / 2) - (popup.width / 2) + offset,
bottom : 'auto',
right : 'auto'
};
break;
case 'bottom right':
positioning = {
top : target.top + target.height + distanceAway,
right : parent.width - target.left - target.width - offset,
left : 'auto',
bottom : 'auto'
};
break;
}
if(positioning === undefined) {
module.error(error.invalidPosition, position);
}
module.debug('Calculated popup positioning values', positioning);
// tentatively place on stage
$popup
.css(positioning)
.removeClass(className.position)
.addClass(position)
.addClass(className.loading)
;
popupOffset = module.get.popupOffset();
// see if any boundaries are surpassed with this tentative position
distanceFromBoundary = module.get.distanceFromBoundary(popupOffset, calculations);
if( module.is.offstage(distanceFromBoundary, position) ) {
module.debug('Position is outside viewport', position);
if(searchDepth < settings.maxSearchDepth) {
searchDepth++;
position = module.get.nextPosition(position);
module.debug('Trying new position', position);
return ($popup)
? module.set.position(position, calculations)
: false
;
}
else {
if(settings.lastResort) {
module.debug('No position found, showing with last position');
}
else {
module.debug('Popup could not find a position to display', $popup);
module.error(error.cannotPlace, element);
module.remove.attempts();
module.remove.loading();
module.reset();
return false;
}
}
}
module.debug('Position is on stage', position);
module.remove.attempts();
module.remove.loading();
if( settings.setFluidWidth && module.is.fluid() ) {
module.set.fluidWidth(calculations);
}
return true;
},
fluidWidth: function(calculations) {
calculations = calculations || module.get.calculations();
module.debug('Automatically setting element width to parent width', calculations.parent.width);
$popup.css('width', calculations.container.width);
},
variation: function(variation) {
variation = variation || module.get.variation();
if(variation && module.has.popup() ) {
module.verbose('Adding variation to popup', variation);
$popup.addClass(variation);
}
},
visible: function() {
$module.addClass(className.visible);
}
},
remove: {
loading: function() {
$popup.removeClass(className.loading);
},
variation: function(variation) {
variation = variation || module.get.variation();
if(variation) {
module.verbose('Removing variation', variation);
$popup.removeClass(variation);
}
},
visible: function() {
$module.removeClass(className.visible);
},
attempts: function() {
module.verbose('Resetting all searched positions');
searchDepth = 0;
triedPositions = false;
}
},
bind: {
events: function() {
module.debug('Binding popup events to module');
if(settings.on == 'click') {
$module
.on('click' + eventNamespace, module.toggle)
;
}
if(settings.on == 'hover' && hasTouch) {
$module
.on('touchstart' + eventNamespace, module.event.touchstart)
;
}
if( module.get.startEvent() ) {
$module
.on(module.get.startEvent() + eventNamespace, module.event.start)
.on(module.get.endEvent() + eventNamespace, module.event.end)
;
}
if(settings.target) {
module.debug('Target set to element', $target);
}
$window.on('resize' + elementNamespace, module.event.resize);
},
popup: function() {
module.verbose('Allowing hover events on popup to prevent closing');
if( $popup && module.has.popup() ) {
$popup
.on('mouseenter' + eventNamespace, module.event.start)
.on('mouseleave' + eventNamespace, module.event.end)
;
}
},
close: function() {
if(settings.hideOnScroll === true || (settings.hideOnScroll == 'auto' && settings.on != 'click')) {
$document
.one(module.get.scrollEvent() + elementNamespace, module.event.hideGracefully)
;
$context
.one(module.get.scrollEvent() + elementNamespace, module.event.hideGracefully)
;
}
if(settings.on == 'hover' && openedWithTouch) {
module.verbose('Binding popup close event to document');
$document
.on('touchstart' + elementNamespace, function(event) {
module.verbose('Touched away from popup');
module.event.hideGracefully.call(element, event);
})
;
}
if(settings.on == 'click' && settings.closable) {
module.verbose('Binding popup close event to document');
$document
.on('click' + elementNamespace, function(event) {
module.verbose('Clicked away from popup');
module.event.hideGracefully.call(element, event);
})
;
}
}
},
unbind: {
close: function() {
if(settings.hideOnScroll === true || (settings.hideOnScroll == 'auto' && settings.on != 'click')) {
$document
.off('scroll' + elementNamespace, module.hide)
;
$context
.off('scroll' + elementNamespace, module.hide)
;
}
if(settings.on == 'hover' && openedWithTouch) {
$document
.off('touchstart' + elementNamespace)
;
openedWithTouch = false;
}
if(settings.on == 'click' && settings.closable) {
module.verbose('Removing close event from document');
$document
.off('click' + elementNamespace)
;
}
}
},
has: {
popup: function() {
return ($popup && $popup.length > 0);
}
},
is: {
offstage: function(distanceFromBoundary, position) {
var
offstage = []
;
// return boundaries that have been surpassed
$.each(distanceFromBoundary, function(direction, distance) {
if(distance < -settings.jitter) {
module.debug('Position exceeds allowable distance from edge', direction, distance, position);
offstage.push(direction);
}
});
if(offstage.length > 0) {
return true;
}
else {
return false;
}
},
active: function() {
return $module.hasClass(className.active);
},
animating: function() {
return ( $popup && $popup.hasClass(className.animating) );
},
fluid: function() {
return ( $popup && $popup.hasClass(className.fluid));
},
visible: function() {
return $popup && $popup.hasClass(className.visible);
},
dropdown: function() {
return $module.hasClass(className.dropdown);
},
hidden: function() {
return !module.is.visible();
},
rtl: function () {
return $module.css('direction') == 'rtl';
}
},
reset: function() {
module.remove.visible();
if(settings.preserve) {
if($.fn.transition !== undefined) {
$popup
.transition('remove transition')
;
}
}
else {
module.removePopup();
}
},
setting: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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( (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 = [];
}
},
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($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.popup.settings = {
name : 'Popup',
// module settings
debug : false,
verbose : false,
performance : true,
namespace : 'popup',
// callback only when element added to dom
onCreate : function(){},
// callback before element removed from dom
onRemove : function(){},
// callback before show animation
onShow : function(){},
// callback after show animation
onVisible : function(){},
// callback before hide animation
onHide : function(){},
// callback after hide animation
onHidden : function(){},
// when to show popup
on : 'hover',
// whether to add touchstart events when using hover
addTouchEvents : true,
// default position relative to element
position : 'top left',
// name of variation to use
variation : '',
// whether popup should be moved to context
movePopup : true,
// element which popup should be relative to
target : false,
// jq selector or element that should be used as popup
popup : false,
// popup should remain inline next to activator
inline : false,
// popup should be removed from page on hide
preserve : false,
// popup should not close when being hovered on
hoverable : false,
// explicitly set content
content : false,
// explicitly set html
html : false,
// explicitly set title
title : false,
// whether automatically close on clickaway when on click
closable : true,
// automatically hide on scroll
hideOnScroll : 'auto',
// hide other popups on show
exclusive : false,
// context to attach popups
context : 'body',
// position to prefer when calculating new position
prefer : 'opposite',
// specify position to appear even if it doesn't fit
lastResort : false,
// delay used to prevent accidental refiring of animations due to user error
delay : {
show : 50,
hide : 70
},
// whether fluid variation should assign width explicitly
setFluidWidth : true,
// transition settings
duration : 200,
transition : 'scale',
// distance away from activating element in px
distanceAway : 0,
// number of pixels an element is allowed to be "offstage" for a position to be chosen (allows for rounding)
jitter : 2,
// offset on aligning axis from calculated position
offset : 0,
// maximum times to look for a position before failing (9 positions total)
maxSearchDepth : 15,
error: {
invalidPosition : 'The position you specified is not a valid position',
cannotPlace : 'Popup does not fit within the boundaries of the viewport',
method : 'The method you called is not defined.',
noTransition : 'This module requires ui transitions <https://github.com/Semantic-Org/UI-Transition>',
notFound : 'The target or popup you specified does not exist on the page'
},
metadata: {
activator : 'activator',
content : 'content',
html : 'html',
offset : 'offset',
position : 'position',
title : 'title',
variation : 'variation'
},
className : {
active : 'active',
animating : 'animating',
dropdown : 'dropdown',
fluid : 'fluid',
loading : 'loading',
popup : 'ui popup',
position : 'top left center bottom right',
visible : 'visible'
},
selector : {
popup : '.ui.popup'
},
templates: {
escape: function(string) {
var
badChars = /[&<>"'`]/g,
shouldEscape = /[&<>"'`]/,
escape = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"`": "`"
},
escapedChar = function(chr) {
return escape[chr];
}
;
if(shouldEscape.test(string)) {
return string.replace(badChars, escapedChar);
}
return string;
},
popup: function(text) {
var
html = '',
escape = $.fn.popup.settings.templates.escape
;
if(typeof text !== undefined) {
if(typeof text.title !== undefined && text.title) {
text.title = escape(text.title);
html += '<div class="header">' + text.title + '</div>';
}
if(typeof text.content !== undefined && text.content) {
text.content = escape(text.content);
html += '<div class="content">' + text.content + '</div>';
}
}
return html;
}
}
};
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Progress
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.fn.progress = function(parameters) {
var
$allModules = $(this),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.progress.settings, parameters)
: $.extend({}, $.fn.progress.settings),
className = settings.className,
metadata = settings.metadata,
namespace = settings.namespace,
selector = settings.selector,
error = settings.error,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
$module = $(this),
$bar = $(this).find(selector.bar),
$progress = $(this).find(selector.progress),
$label = $(this).find(selector.label),
element = this,
instance = $module.data(moduleNamespace),
animating = false,
transitionEnd,
module
;
module = {
initialize: function() {
module.debug('Initializing progress bar', settings);
module.set.duration();
module.set.transitionEvent();
module.read.metadata();
module.read.settings();
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of progress', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
destroy: function() {
module.verbose('Destroying previous progress for', $module);
clearInterval(instance.interval);
module.remove.state();
$module.removeData(moduleNamespace);
instance = undefined;
},
reset: function() {
module.set.percent(0);
},
complete: function() {
if(module.percent === undefined || module.percent < 100) {
module.set.percent(100);
}
},
read: {
metadata: function() {
var
data = {
percent : $module.data(metadata.percent),
total : $module.data(metadata.total),
value : $module.data(metadata.value)
}
;
if(data.percent) {
module.debug('Current percent value set from metadata', data.percent);
module.set.percent(data.percent);
}
if(data.total) {
module.debug('Total value set from metadata', data.total);
module.set.total(data.total);
}
if(data.value) {
module.debug('Current value set from metadata', data.value);
module.set.value(data.value);
module.set.progress(data.value);
}
},
settings: function() {
if(settings.total !== false) {
module.debug('Current total set in settings', settings.total);
module.set.total(settings.total);
}
if(settings.value !== false) {
module.debug('Current value set in settings', settings.value);
module.set.value(settings.value);
module.set.progress(module.value);
}
if(settings.percent !== false) {
module.debug('Current percent set in settings', settings.percent);
module.set.percent(settings.percent);
}
}
},
increment: function(incrementValue) {
var
maxValue,
startValue,
newValue
;
if( module.has.total() ) {
startValue = module.get.value();
incrementValue = incrementValue || 1;
newValue = startValue + incrementValue;
maxValue = module.get.total();
module.debug('Incrementing value', startValue, newValue, maxValue);
if(newValue > maxValue ) {
module.debug('Value cannot increment above total', maxValue);
newValue = maxValue;
}
}
else {
startValue = module.get.percent();
incrementValue = incrementValue || module.get.randomValue();
newValue = startValue + incrementValue;
maxValue = 100;
module.debug('Incrementing percentage by', startValue, newValue);
if(newValue > maxValue ) {
module.debug('Value cannot increment above 100 percent');
newValue = maxValue;
}
}
module.set.progress(newValue);
},
decrement: function(decrementValue) {
var
total = module.get.total(),
startValue,
newValue
;
if(total) {
startValue = module.get.value();
decrementValue = decrementValue || 1;
newValue = startValue - decrementValue;
module.debug('Decrementing value by', decrementValue, startValue);
}
else {
startValue = module.get.percent();
decrementValue = decrementValue || module.get.randomValue();
newValue = startValue - decrementValue;
module.debug('Decrementing percentage by', decrementValue, startValue);
}
if(newValue < 0) {
module.debug('Value cannot decrement below 0');
newValue = 0;
}
module.set.progress(newValue);
},
has: {
total: function() {
return (module.get.total() !== false);
}
},
get: {
text: function(templateText) {
var
value = module.value || 0,
total = module.total || 0,
percent = (animating)
? module.get.displayPercent()
: module.percent || 0,
left = (module.total > 0)
? (total - value)
: (100 - percent)
;
templateText = templateText || '';
templateText = templateText
.replace('{value}', value)
.replace('{total}', total)
.replace('{left}', left)
.replace('{percent}', percent)
;
module.debug('Adding variables to progress bar text', templateText);
return templateText;
},
randomValue: function() {
module.debug('Generating random increment percentage');
return Math.floor((Math.random() * settings.random.max) + settings.random.min);
},
numericValue: function(value) {
return (typeof value === 'string')
? (value.replace(/[^\d.]/g, '') !== '')
? +(value.replace(/[^\d.]/g, ''))
: false
: value
;
},
transitionEnd: function() {
var
element = document.createElement('element'),
transitions = {
'transition' :'transitionend',
'OTransition' :'oTransitionEnd',
'MozTransition' :'transitionend',
'WebkitTransition' :'webkitTransitionEnd'
},
transition
;
for(transition in transitions){
if( element.style[transition] !== undefined ){
return transitions[transition];
}
}
},
// gets current displayed percentage (if animating values this is the intermediary value)
displayPercent: function() {
var
barWidth = $bar.width(),
totalWidth = $module.width(),
minDisplay = parseInt($bar.css('min-width'), 10),
displayPercent = (barWidth > minDisplay)
? (barWidth / totalWidth * 100)
: module.percent
;
return (settings.precision > 0)
? Math.round(displayPercent * (10 * settings.precision)) / (10 * settings.precision)
: Math.round(displayPercent)
;
},
percent: function() {
return module.percent || 0;
},
value: function() {
return module.value || 0;
},
total: function() {
return module.total || false;
}
},
is: {
success: function() {
return $module.hasClass(className.success);
},
warning: function() {
return $module.hasClass(className.warning);
},
error: function() {
return $module.hasClass(className.error);
},
active: function() {
return $module.hasClass(className.active);
},
visible: function() {
return $module.is(':visible');
}
},
remove: {
state: function() {
module.verbose('Removing stored state');
delete module.total;
delete module.percent;
delete module.value;
},
active: function() {
module.verbose('Removing active state');
$module.removeClass(className.active);
},
success: function() {
module.verbose('Removing success state');
$module.removeClass(className.success);
},
warning: function() {
module.verbose('Removing warning state');
$module.removeClass(className.warning);
},
error: function() {
module.verbose('Removing error state');
$module.removeClass(className.error);
}
},
set: {
barWidth: function(value) {
if(value > 100) {
module.error(error.tooHigh, value);
}
else if (value < 0) {
module.error(error.tooLow, value);
}
else {
$bar
.css('width', value + '%')
;
$module
.attr('data-percent', parseInt(value, 10))
;
}
},
duration: function(duration) {
duration = duration || settings.duration;
duration = (typeof duration == 'number')
? duration + 'ms'
: duration
;
module.verbose('Setting progress bar transition duration', duration);
$bar
.css({
'transition-duration': duration
})
;
},
percent: function(percent) {
percent = (typeof percent == 'string')
? +(percent.replace('%', ''))
: percent
;
// round display percentage
percent = (settings.precision > 0)
? Math.round(percent * (10 * settings.precision)) / (10 * settings.precision)
: Math.round(percent)
;
module.percent = percent;
if( !module.has.total() ) {
module.value = (settings.precision > 0)
? Math.round( (percent / 100) * module.total * (10 * settings.precision)) / (10 * settings.precision)
: Math.round( (percent / 100) * module.total * 10) / 10
;
if(settings.limitValues) {
module.value = (module.value > 100)
? 100
: (module.value < 0)
? 0
: module.value
;
}
}
module.set.barWidth(percent);
module.set.labelInterval();
module.set.labels();
settings.onChange.call(element, percent, module.value, module.total);
},
labelInterval: function() {
var
animationCallback = function() {
module.verbose('Bar finished animating, removing continuous label updates');
clearInterval(module.interval);
animating = false;
module.set.labels();
}
;
clearInterval(module.interval);
$bar.one(transitionEnd + eventNamespace, animationCallback);
module.timer = setTimeout(animationCallback, settings.duration + 100);
animating = true;
module.interval = setInterval(module.set.labels, settings.framerate);
},
labels: function() {
module.verbose('Setting both bar progress and outer label text');
module.set.barLabel();
module.set.state();
},
label: function(text) {
text = text || '';
if(text) {
text = module.get.text(text);
module.debug('Setting label to text', text);
$label.text(text);
}
},
state: function(percent) {
percent = (percent !== undefined)
? percent
: module.percent
;
if(percent === 100) {
if(settings.autoSuccess && !(module.is.warning() || module.is.error())) {
module.set.success();
module.debug('Automatically triggering success at 100%');
}
else {
module.verbose('Reached 100% removing active state');
module.remove.active();
}
}
else if(percent > 0) {
module.verbose('Adjusting active progress bar label', percent);
module.set.active();
}
else {
module.remove.active();
module.set.label(settings.text.active);
}
},
barLabel: function(text) {
if(text !== undefined) {
$progress.text( module.get.text(text) );
}
else if(settings.label == 'ratio' && module.total) {
module.debug('Adding ratio to bar label');
$progress.text( module.get.text(settings.text.ratio) );
}
else if(settings.label == 'percent') {
module.debug('Adding percentage to bar label');
$progress.text( module.get.text(settings.text.percent) );
}
},
active: function(text) {
text = text || settings.text.active;
module.debug('Setting active state');
if(settings.showActivity && !module.is.active() ) {
$module.addClass(className.active);
}
module.remove.warning();
module.remove.error();
module.remove.success();
if(text) {
module.set.label(text);
}
settings.onActive.call(element, module.value, module.total);
},
success : function(text) {
text = text || settings.text.success;
module.debug('Setting success state');
$module.addClass(className.success);
module.remove.active();
module.remove.warning();
module.remove.error();
module.complete();
if(text) {
module.set.label(text);
}
settings.onSuccess.call(element, module.total);
},
warning : function(text) {
text = text || settings.text.warning;
module.debug('Setting warning state');
$module.addClass(className.warning);
module.remove.active();
module.remove.success();
module.remove.error();
module.complete();
if(text) {
module.set.label(text);
}
settings.onWarning.call(element, module.value, module.total);
},
error : function(text) {
text = text || settings.text.error;
module.debug('Setting error state');
$module.addClass(className.error);
module.remove.active();
module.remove.success();
module.remove.warning();
module.complete();
if(text) {
module.set.label(text);
}
settings.onError.call(element, module.value, module.total);
},
transitionEvent: function() {
transitionEnd = module.get.transitionEnd();
},
total: function(totalValue) {
module.total = totalValue;
},
value: function(value) {
module.value = value;
},
progress: function(value) {
var
numericValue = module.get.numericValue(value),
percentComplete
;
if(numericValue === false) {
module.error(error.nonNumeric, value);
}
if( module.has.total() ) {
module.set.value(numericValue);
percentComplete = (numericValue / module.total) * 100;
module.debug('Calculating percent complete from total', percentComplete);
module.set.percent( percentComplete );
}
else {
percentComplete = numericValue;
module.debug('Setting value to exact percentage value', percentComplete);
module.set.percent( percentComplete );
}
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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( (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 = [];
}
},
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 {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.progress.settings = {
name : 'Progress',
namespace : 'progress',
debug : false,
verbose : false,
performance : true,
random : {
min : 2,
max : 5
},
duration : 300,
autoSuccess : true,
showActivity : true,
limitValues : true,
label : 'percent',
precision : 0,
framerate : (1000 / 30), /// 30 fps
percent : false,
total : false,
value : false,
onChange : function(percent, value, total){},
onSuccess : function(total){},
onActive : function(value, total){},
onError : function(value, total){},
onWarning : function(value, total){},
error : {
method : 'The method you called is not defined.',
nonNumeric : 'Progress value is non numeric',
tooHigh : 'Value specified is above 100%',
tooLow : 'Value specified is below 0%'
},
regExp: {
variable: /\{\$*[A-z0-9]+\}/g
},
metadata: {
percent : 'percent',
total : 'total',
value : 'value'
},
selector : {
bar : '> .bar',
label : '> .label',
progress : '.bar > .progress'
},
text : {
active : false,
error : false,
success : false,
warning : false,
percent : '{percent}%',
ratio : '{value} of {total}'
},
className : {
active : 'active',
error : 'error',
success : 'success',
warning : 'warning'
}
};
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Rating
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ($, window, document, undefined) {
"use strict";
$.fn.rating = function(parameters) {
var
$allModules = $(this),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.rating.settings, parameters)
: $.extend({}, $.fn.rating.settings),
namespace = settings.namespace,
className = settings.className,
metadata = settings.metadata,
selector = settings.selector,
error = settings.error,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
element = this,
instance = $(this).data(moduleNamespace),
$module = $(this),
$icon = $module.find(selector.icon),
module
;
module = {
initialize: function() {
module.verbose('Initializing rating module', settings);
if($icon.length === 0) {
module.setup.layout();
}
if(settings.interactive) {
module.enable();
}
else {
module.disable();
}
module.set.rating( module.get.initialRating() );
module.instantiate();
},
instantiate: function() {
module.verbose('Instantiating module', settings);
instance = module;
$module
.data(moduleNamespace, module)
;
},
destroy: function() {
module.verbose('Destroying previous instance', instance);
module.remove.events();
$module
.removeData(moduleNamespace)
;
},
refresh: function() {
$icon = $module.find(selector.icon);
},
setup: {
layout: function() {
var
maxRating = module.get.maxRating(),
html = $.fn.rating.settings.templates.icon(maxRating)
;
module.debug('Generating icon html dynamically');
$module
.html(html)
;
module.refresh();
}
},
event: {
mouseenter: function() {
var
$activeIcon = $(this)
;
$activeIcon
.nextAll()
.removeClass(className.selected)
;
$module
.addClass(className.selected)
;
$activeIcon
.addClass(className.selected)
.prevAll()
.addClass(className.selected)
;
},
mouseleave: function() {
$module
.removeClass(className.selected)
;
$icon
.removeClass(className.selected)
;
},
click: function() {
var
$activeIcon = $(this),
currentRating = module.get.rating(),
rating = $icon.index($activeIcon) + 1,
canClear = (settings.clearable == 'auto')
? ($icon.length === 1)
: settings.clearable
;
if(canClear && currentRating == rating) {
module.clearRating();
}
else {
module.set.rating( rating );
}
}
},
clearRating: function() {
module.debug('Clearing current rating');
module.set.rating(0);
},
bind: {
events: function() {
module.verbose('Binding events');
$module
.on('mouseenter' + eventNamespace, selector.icon, module.event.mouseenter)
.on('mouseleave' + eventNamespace, selector.icon, module.event.mouseleave)
.on('click' + eventNamespace, selector.icon, module.event.click)
;
}
},
remove: {
events: function() {
module.verbose('Removing events');
$module
.off(eventNamespace)
;
}
},
enable: function() {
module.debug('Setting rating to interactive mode');
module.bind.events();
$module
.removeClass(className.disabled)
;
},
disable: function() {
module.debug('Setting rating to read-only mode');
module.remove.events();
$module
.addClass(className.disabled)
;
},
get: {
initialRating: function() {
if($module.data(metadata.rating) !== undefined) {
$module.removeData(metadata.rating);
return $module.data(metadata.rating);
}
return settings.initialRating;
},
maxRating: function() {
if($module.data(metadata.maxRating) !== undefined) {
$module.removeData(metadata.maxRating);
return $module.data(metadata.maxRating);
}
return settings.maxRating;
},
rating: function() {
var
currentRating = $icon.filter('.' + className.active).length
;
module.verbose('Current rating retrieved', currentRating);
return currentRating;
}
},
set: {
rating: function(rating) {
var
ratingIndex = (rating - 1 >= 0)
? (rating - 1)
: 0,
$activeIcon = $icon.eq(ratingIndex)
;
$module
.removeClass(className.selected)
;
$icon
.removeClass(className.selected)
.removeClass(className.active)
;
if(rating > 0) {
module.verbose('Setting current rating to', rating);
$activeIcon
.prevAll()
.andSelf()
.addClass(className.active)
;
}
settings.onRate.call(element, rating);
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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 = [];
}
},
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($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.rating.settings = {
name : 'Rating',
namespace : 'rating',
debug : false,
verbose : false,
performance : true,
initialRating : 0,
interactive : true,
maxRating : 4,
clearable : 'auto',
onRate : function(rating){},
error : {
method : 'The method you called is not defined',
noMaximum : 'No maximum rating specified. Cannot generate HTML automatically'
},
metadata: {
rating : 'rating',
maxRating : 'maxRating'
},
className : {
active : 'active',
disabled : 'disabled',
selected : 'selected',
loading : 'loading'
},
selector : {
icon : '.icon'
},
templates: {
icon: function(maxRating) {
var
icon = 1,
html = ''
;
while(icon <= maxRating) {
html += '<i class="icon"></i>';
icon++;
}
return html;
}
}
};
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Search
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ($, window, document, undefined) {
"use strict";
$.fn.search = function(parameters) {
var
$allModules = $(this),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$(this)
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.search.settings, parameters)
: $.extend({}, $.fn.search.settings),
className = settings.className,
metadata = settings.metadata,
regExp = settings.regExp,
fields = settings.fields,
selector = settings.selector,
error = settings.error,
namespace = settings.namespace,
eventNamespace = '.' + namespace,
moduleNamespace = namespace + '-module',
$module = $(this),
$prompt = $module.find(selector.prompt),
$searchButton = $module.find(selector.searchButton),
$results = $module.find(selector.results),
$result = $module.find(selector.result),
$category = $module.find(selector.category),
element = this,
instance = $module.data(moduleNamespace),
module
;
module = {
initialize: function() {
module.verbose('Initializing module');
module.determine.searchFields();
module.bind.events();
module.set.type();
module.create.results();
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of module', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
destroy: function() {
module.verbose('Destroying instance');
$module
.off(eventNamespace)
.removeData(moduleNamespace)
;
},
bind: {
events: function() {
module.verbose('Binding events to search');
if(settings.automatic) {
$module
.on(module.get.inputEvent() + eventNamespace, selector.prompt, module.event.input)
;
$prompt
.attr('autocomplete', 'off')
;
}
$module
// prompt
.on('focus' + eventNamespace, selector.prompt, module.event.focus)
.on('blur' + eventNamespace, selector.prompt, module.event.blur)
.on('keydown' + eventNamespace, selector.prompt, module.handleKeyboard)
// search button
.on('click' + eventNamespace, selector.searchButton, module.query)
// results
.on('mousedown' + eventNamespace, selector.results, module.event.result.mousedown)
.on('mouseup' + eventNamespace, selector.results, module.event.result.mouseup)
.on('click' + eventNamespace, selector.result, module.event.result.click)
;
}
},
determine: {
searchFields: function() {
// this makes sure $.extend does not add specified search fields to default fields
// this is the only setting which should not extend defaults
if(parameters && parameters.searchFields !== undefined) {
settings.searchFields = parameters.searchFields;
}
}
},
event: {
input: function() {
clearTimeout(module.timer);
module.timer = setTimeout(module.query, settings.searchDelay);
},
focus: function() {
module.set.focus();
if( module.has.minimumCharacters() ) {
module.query();
if( module.can.show() ) {
module.showResults();
}
}
},
blur: function(event) {
var
pageLostFocus = (document.activeElement === this)
;
if(!pageLostFocus && !module.resultsClicked) {
module.cancel.query();
module.remove.focus();
module.timer = setTimeout(module.hideResults, settings.hideDelay);
}
},
result: {
mousedown: function() {
module.resultsClicked = true;
},
mouseup: function() {
module.resultsClicked = false;
},
click: function(event) {
module.debug('Search result selected');
var
$result = $(this),
$title = $result.find(selector.title).eq(0),
$link = $result.find('a[href]').eq(0),
href = $link.attr('href') || false,
target = $link.attr('target') || false,
title = $title.html(),
// title is used for result lookup
value = ($title.length > 0)
? $title.text()
: false,
results = module.get.results(),
result = $result.data(metadata.result) || module.get.result(value, results),
returnedValue
;
if( $.isFunction(settings.onSelect) ) {
if(settings.onSelect.call(element, result, results) === false) {
module.debug('Custom onSelect callback cancelled default select action');
return;
}
}
module.hideResults();
if(value) {
module.set.value(value);
}
if(href) {
module.verbose('Opening search link found in result', $link);
if(target == '_blank' || event.ctrlKey) {
window.open(href);
}
else {
window.location.href = (href);
}
}
}
}
},
handleKeyboard: function(event) {
var
// force selector refresh
$result = $module.find(selector.result),
$category = $module.find(selector.category),
currentIndex = $result.index( $result.filter('.' + className.active) ),
resultSize = $result.length,
keyCode = event.which,
keys = {
backspace : 8,
enter : 13,
escape : 27,
upArrow : 38,
downArrow : 40
},
newIndex
;
// search shortcuts
if(keyCode == keys.escape) {
module.verbose('Escape key pressed, blurring search field');
$prompt
.trigger('blur')
;
}
if( module.is.visible() ) {
if(keyCode == keys.enter) {
module.verbose('Enter key pressed, selecting active result');
if( $result.filter('.' + className.active).length > 0 ) {
module.event.result.click.call($result.filter('.' + className.active), event);
event.preventDefault();
return false;
}
}
else if(keyCode == keys.upArrow) {
module.verbose('Up key pressed, changing active result');
newIndex = (currentIndex - 1 < 0)
? currentIndex
: currentIndex - 1
;
$category
.removeClass(className.active)
;
$result
.removeClass(className.active)
.eq(newIndex)
.addClass(className.active)
.closest($category)
.addClass(className.active)
;
event.preventDefault();
}
else if(keyCode == keys.downArrow) {
module.verbose('Down key pressed, changing active result');
newIndex = (currentIndex + 1 >= resultSize)
? currentIndex
: currentIndex + 1
;
$category
.removeClass(className.active)
;
$result
.removeClass(className.active)
.eq(newIndex)
.addClass(className.active)
.closest($category)
.addClass(className.active)
;
event.preventDefault();
}
}
else {
// query shortcuts
if(keyCode == keys.enter) {
module.verbose('Enter key pressed, executing query');
module.query();
module.set.buttonPressed();
$prompt.one('keyup', module.remove.buttonFocus);
}
}
},
setup: {
api: function() {
var
apiSettings = {
debug : settings.debug,
on : false,
cache : 'local',
action : 'search',
onError : module.error
},
searchHTML
;
module.verbose('First request, initializing API');
$module.api(apiSettings);
}
},
can: {
useAPI: function() {
return $.fn.api !== undefined;
},
show: function() {
return module.is.focused() && !module.is.visible() && !module.is.empty();
},
transition: function() {
return settings.transition && $.fn.transition !== undefined && $module.transition('is supported');
}
},
is: {
empty: function() {
return ($results.html() === '');
},
visible: function() {
return ($results.filter(':visible').length > 0);
},
focused: function() {
return ($prompt.filter(':focus').length > 0);
}
},
get: {
inputEvent: function() {
var
prompt = $prompt[0],
inputEvent = (prompt !== undefined && prompt.oninput !== undefined)
? 'input'
: (prompt !== undefined && prompt.onpropertychange !== undefined)
? 'propertychange'
: 'keyup'
;
return inputEvent;
},
value: function() {
return $prompt.val();
},
results: function() {
var
results = $module.data(metadata.results)
;
return results;
},
result: function(value, results) {
var
lookupFields = ['title', 'id'],
result = false
;
value = (value !== undefined)
? value
: module.get.value()
;
results = (results !== undefined)
? results
: module.get.results()
;
if(settings.type === 'category') {
module.debug('Finding result that matches', value);
$.each(results, function(index, category) {
if($.isArray(category.results)) {
result = module.search.object(value, category.results, lookupFields)[0];
// don't continue searching if a result is found
if(result) {
return false;
}
}
});
}
else {
module.debug('Finding result in results object', value);
result = module.search.object(value, results, lookupFields)[0];
}
return result || false;
},
},
set: {
focus: function() {
$module.addClass(className.focus);
},
loading: function() {
$module.addClass(className.loading);
},
value: function(value) {
module.verbose('Setting search input value', value);
$prompt
.val(value)
;
},
type: function(type) {
type = type || settings.type;
if(settings.type == 'category') {
$module.addClass(settings.type);
}
},
buttonPressed: function() {
$searchButton.addClass(className.pressed);
}
},
remove: {
loading: function() {
$module.removeClass(className.loading);
},
focus: function() {
$module.removeClass(className.focus);
},
buttonPressed: function() {
$searchButton.removeClass(className.pressed);
}
},
query: function() {
var
searchTerm = module.get.value(),
cache = module.read.cache(searchTerm)
;
if( module.has.minimumCharacters() ) {
if(cache) {
module.debug('Reading result from cache', searchTerm);
module.save.results(cache.results);
module.addResults(cache.html);
module.inject.id(cache.results);
}
else {
module.debug('Querying for', searchTerm);
if($.isPlainObject(settings.source) || $.isArray(settings.source)) {
module.search.local(searchTerm);
}
else if( module.can.useAPI() ) {
module.search.remote(searchTerm);
}
else {
module.error(error.source);
}
settings.onSearchQuery.call(element, searchTerm);
}
}
else {
module.hideResults();
}
},
search: {
local: function(searchTerm) {
var
results = module.search.object(searchTerm, settings.content),
searchHTML
;
module.set.loading();
module.save.results(results);
module.debug('Returned local search results', results);
searchHTML = module.generateResults({
results: results
});
module.remove.loading();
module.addResults(searchHTML);
module.inject.id(results);
module.write.cache(searchTerm, {
html : searchHTML,
results : results
});
},
remote: function(searchTerm) {
var
apiSettings = {
onSuccess : function(response) {
module.parse.response.call(element, response, searchTerm);
},
onFailure: function() {
module.displayMessage(error.serverError);
},
urlData: {
query: searchTerm
}
}
;
if( !$module.api('get request') ) {
module.setup.api();
}
$.extend(true, apiSettings, settings.apiSettings);
module.debug('Executing search', apiSettings);
module.cancel.query();
$module
.api('setting', apiSettings)
.api('query')
;
},
object: function(searchTerm, source, searchFields) {
var
results = [],
fuzzyResults = [],
searchExp = searchTerm.toString().replace(regExp.escape, '\\$&'),
matchRegExp = new RegExp(regExp.beginsWith + searchExp, 'i'),
// avoid duplicates when pushing results
addResult = function(array, result) {
var
notResult = ($.inArray(result, results) == -1),
notFuzzyResult = ($.inArray(result, fuzzyResults) == -1)
;
if(notResult && notFuzzyResult) {
array.push(result);
}
}
;
source = source || settings.source;
searchFields = (searchFields !== undefined)
? searchFields
: settings.searchFields
;
// search fields should be array to loop correctly
if(!$.isArray(searchFields)) {
searchFields = [searchFields];
}
// exit conditions if no source
if(source === undefined || source === false) {
module.error(error.source);
return [];
}
// iterate through search fields looking for matches
$.each(searchFields, function(index, field) {
$.each(source, function(label, content) {
var
fieldExists = (typeof content[field] == 'string')
;
if(fieldExists) {
if( content[field].search(matchRegExp) !== -1) {
// content starts with value (first in results)
addResult(results, content);
}
else if(settings.searchFullText && module.fuzzySearch(searchTerm, content[field]) ) {
// content fuzzy matches (last in results)
addResult(fuzzyResults, content);
}
}
});
});
return $.merge(results, fuzzyResults);
}
},
fuzzySearch: function(query, term) {
var
termLength = term.length,
queryLength = query.length
;
if(typeof query !== 'string') {
return false;
}
query = query.toLowerCase();
term = term.toLowerCase();
if(queryLength > termLength) {
return false;
}
if(queryLength === termLength) {
return (query === term);
}
search: for (var characterIndex = 0, nextCharacterIndex = 0; characterIndex < queryLength; characterIndex++) {
var
queryCharacter = query.charCodeAt(characterIndex)
;
while(nextCharacterIndex < termLength) {
if(term.charCodeAt(nextCharacterIndex++) === queryCharacter) {
continue search;
}
}
return false;
}
return true;
},
parse: {
response: function(response, searchTerm) {
var
searchHTML = module.generateResults(response)
;
module.verbose('Parsing server response', response);
if(response !== undefined) {
if(searchTerm !== undefined && response[fields.results] !== undefined) {
module.addResults(searchHTML);
module.inject.id(response[fields.results]);
module.write.cache(searchTerm, {
html : searchHTML,
results : response[fields.results]
});
module.save.results(response[fields.results]);
}
}
}
},
cancel: {
query: function() {
if( module.can.useAPI() ) {
$module.api('abort');
}
}
},
has: {
minimumCharacters: function() {
var
searchTerm = module.get.value(),
numCharacters = searchTerm.length
;
return (numCharacters >= settings.minCharacters);
}
},
clear: {
cache: function(value) {
var
cache = $module.data(metadata.cache)
;
if(!value) {
module.debug('Clearing cache', value);
$module.removeData(metadata.cache);
}
else if(value && cache && cache[value]) {
module.debug('Removing value from cache', value);
delete cache[value];
$module.data(metadata.cache, cache);
}
}
},
read: {
cache: function(name) {
var
cache = $module.data(metadata.cache)
;
if(settings.cache) {
module.verbose('Checking cache for generated html for query', name);
return (typeof cache == 'object') && (cache[name] !== undefined)
? cache[name]
: false
;
}
return false;
}
},
create: {
id: function(resultIndex, categoryIndex) {
var
resultID = (resultIndex + 1), // not zero indexed
categoryID = (categoryIndex + 1),
firstCharCode,
letterID,
id
;
if(categoryIndex !== undefined) {
// start char code for "A"
letterID = String.fromCharCode(97 + categoryIndex);
id = letterID + resultID;
module.verbose('Creating category result id', id);
}
else {
id = resultID;
module.verbose('Creating result id', id);
}
return id;
},
results: function() {
if($results.length === 0) {
$results = $('<div />')
.addClass(className.results)
.appendTo($module)
;
}
}
},
inject: {
result: function(result, resultIndex, categoryIndex) {
module.verbose('Injecting result into results');
var
$selectedResult = (categoryIndex !== undefined)
? $results
.children().eq(categoryIndex)
.children(selector.result).eq(resultIndex)
: $results
.children(selector.result).eq(resultIndex)
;
module.verbose('Injecting results metadata', $selectedResult);
$selectedResult
.data(metadata.result, result)
;
},
id: function(results) {
module.debug('Injecting unique ids into results');
var
// since results may be object, we must use counters
categoryIndex = 0,
resultIndex = 0
;
if(settings.type === 'category') {
// iterate through each category result
$.each(results, function(index, category) {
resultIndex = 0;
$.each(category.results, function(index, value) {
var
result = category.results[index]
;
if(result.id === undefined) {
result.id = module.create.id(resultIndex, categoryIndex);
}
module.inject.result(result, resultIndex, categoryIndex);
resultIndex++;
});
categoryIndex++;
});
}
else {
// top level
$.each(results, function(index, value) {
var
result = results[index]
;
if(result.id === undefined) {
result.id = module.create.id(resultIndex);
}
module.inject.result(result, resultIndex);
resultIndex++;
});
}
return results;
}
},
save: {
results: function(results) {
module.verbose('Saving current search results to metadata', results);
$module.data(metadata.results, results);
}
},
write: {
cache: function(name, value) {
var
cache = ($module.data(metadata.cache) !== undefined)
? $module.data(metadata.cache)
: {}
;
if(settings.cache) {
module.verbose('Writing generated html to cache', name, value);
cache[name] = value;
$module
.data(metadata.cache, cache)
;
}
}
},
addResults: function(html) {
if( $.isFunction(settings.onResultsAdd) ) {
if( settings.onResultsAdd.call($results, html) === false ) {
module.debug('onResultsAdd callback cancelled default action');
return false;
}
}
$results
.html(html)
;
if( module.can.show() ) {
module.showResults();
}
},
showResults: function() {
if(!module.is.visible()) {
if( module.can.transition() ) {
module.debug('Showing results with css animations');
$results
.transition({
animation : settings.transition + ' in',
debug : settings.debug,
verbose : settings.verbose,
duration : settings.duration,
queue : true
})
;
}
else {
module.debug('Showing results with javascript');
$results
.stop()
.fadeIn(settings.duration, settings.easing)
;
}
settings.onResultsOpen.call($results);
}
},
hideResults: function() {
if( module.is.visible() ) {
if( module.can.transition() ) {
module.debug('Hiding results with css animations');
$results
.transition({
animation : settings.transition + ' out',
debug : settings.debug,
verbose : settings.verbose,
duration : settings.duration,
queue : true
})
;
}
else {
module.debug('Hiding results with javascript');
$results
.stop()
.fadeOut(settings.duration, settings.easing)
;
}
settings.onResultsClose.call($results);
}
},
generateResults: function(response) {
module.debug('Generating html from response', response);
var
template = settings.templates[settings.type],
isProperObject = ($.isPlainObject(response[fields.results]) && !$.isEmptyObject(response[fields.results])),
isProperArray = ($.isArray(response[fields.results]) && response[fields.results].length > 0),
html = ''
;
if(isProperObject || isProperArray ) {
if(settings.maxResults > 0) {
if(isProperObject) {
if(settings.type == 'standard') {
module.error(error.maxResults);
}
}
else {
response[fields.results] = response[fields.results].slice(0, settings.maxResults);
}
}
if($.isFunction(template)) {
html = template(response, fields);
}
else {
module.error(error.noTemplate, false);
}
}
else {
html = module.displayMessage(error.noResults, 'empty');
}
settings.onResults.call(element, response);
return html;
},
displayMessage: function(text, type) {
type = type || 'standard';
module.debug('Displaying message', text, type);
module.addResults( settings.templates.message(text, type) );
return settings.templates.message(text, type);
},
setting: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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 = [];
}
},
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($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.search.settings = {
name : 'Search',
namespace : 'search',
debug : false,
verbose : false,
performance : true,
type : 'standard',
// template to use (specified in settings.templates)
minCharacters : 1,
// minimum characters required to search
apiSettings : false,
// API config
source : false,
// object to search
searchFields : [
'title',
'description'
],
// fields to search
displayField : '',
// field to display in standard results template
searchFullText : true,
// whether to include fuzzy results in local search
automatic : true,
// whether to add events to prompt automatically
hideDelay : 0,
// delay before hiding menu after blur
searchDelay : 200,
// delay before searching
maxResults : 7,
// maximum results returned from local
cache : true,
// whether to store lookups in local cache
// transition settings
transition : 'scale',
duration : 200,
easing : 'easeOutExpo',
// callbacks
onSelect : false,
onResultsAdd : false,
onSearchQuery : function(query){},
onResults : function(response){},
onResultsOpen : function(){},
onResultsClose : function(){},
className: {
active : 'active',
empty : 'empty',
focus : 'focus',
loading : 'loading',
results : 'results',
pressed : 'down'
},
error : {
source : 'Cannot search. No source used, and Semantic API module was not included',
noResults : 'Your search returned no results',
logging : 'Error in debug logging, exiting.',
noEndpoint : 'No search endpoint was specified',
noTemplate : 'A valid template name was not specified.',
serverError : 'There was an issue querying the server.',
maxResults : 'Results must be an array to use maxResults setting',
method : 'The method you called is not defined.'
},
metadata: {
cache : 'cache',
results : 'results',
result : 'result'
},
regExp: {
escape : /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,
beginsWith : '(?:\s|^)'
},
// maps api response attributes to internal representation
fields: {
categories : 'results', // array of categories (category view)
categoryName : 'name', // name of category (category view)
categoryResults : 'results', // array of results (category view)
description : 'description', // result description
image : 'image', // result image
price : 'price', // result price
results : 'results', // array of results (standard)
title : 'title', // result title
action : 'action', // "view more" object name
actionText : 'text', // "view more" text
actionURL : 'url' // "view more" url
},
selector : {
prompt : '.prompt',
searchButton : '.search.button',
results : '.results',
category : '.category',
result : '.result',
title : '.title, .name'
},
templates: {
escape: function(string) {
var
badChars = /[&<>"'`]/g,
shouldEscape = /[&<>"'`]/,
escape = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"`": "`"
},
escapedChar = function(chr) {
return escape[chr];
}
;
if(shouldEscape.test(string)) {
return string.replace(badChars, escapedChar);
}
return string;
},
message: function(message, type) {
var
html = ''
;
if(message !== undefined && type !== undefined) {
html += ''
+ '<div class="message ' + type + '">'
;
// message type
if(type == 'empty') {
html += ''
+ '<div class="header">No Results</div class="header">'
+ '<div class="description">' + message + '</div class="description">'
;
}
else {
html += ' <div class="description">' + message + '</div>';
}
html += '</div>';
}
return html;
},
category: function(response, fields) {
var
html = '',
escape = $.fn.search.settings.templates.escape
;
if(response[fields.categoryResults] !== undefined) {
// each category
$.each(response[fields.categoryResults], function(index, category) {
if(category[fields.results] !== undefined && category.results.length > 0) {
html += '<div class="category">';
if(category[fields.categoryName] !== undefined) {
html += '<div class="name">' + category[fields.categoryName] + '</div>';
}
// each item inside category
$.each(category.results, function(index, result) {
if(response[fields.url]) {
html += '<a class="result" href="' + response[fields.url] + '">';
}
else {
html += '<a class="result">';
}
if(result[fields.image] !== undefined) {
html += ''
+ '<div class="image">'
+ ' <img src="' + result[fields.image] + '">'
+ '</div>'
;
}
html += '<div class="content">';
if(result[fields.price] !== undefined) {
html += '<div class="price">' + result[fields.price] + '</div>';
}
if(result[fields.title] !== undefined) {
html += '<div class="title">' + result[fields.title] + '</div>';
}
if(result[fields.description] !== undefined) {
html += '<div class="description">' + result[fields.description] + '</div>';
}
html += ''
+ '</div>'
;
html += '</a>';
});
html += ''
+ '</div>'
;
}
});
if(response[fields.action]) {
html += ''
+ '<a href="' + response[fields.action][fields.actionURL] + '" class="action">'
+ response[fields.action][fields.actionText]
+ '</a>';
}
return html;
}
return false;
},
standard: function(response, fields) {
var
html = ''
;
if(response[fields.results] !== undefined) {
// each result
$.each(response[fields.results], function(index, result) {
if(response[fields.url]) {
html += '<a class="result" href="' + response[fields.url] + '">';
}
else {
html += '<a class="result">';
}
if(result[fields.image] !== undefined) {
html += ''
+ '<div class="image">'
+ ' <img src="' + result[fields.image] + '">'
+ '</div>'
;
}
html += '<div class="content">';
if(result[fields.price] !== undefined) {
html += '<div class="price">' + result[fields.price] + '</div>';
}
if(result[fields.title] !== undefined) {
html += '<div class="title">' + result[fields.title] + '</div>';
}
if(result[fields.description] !== undefined) {
html += '<div class="description">' + result[fields.description] + '</div>';
}
html += ''
+ '</div>'
;
html += '</a>';
});
if(response[fields.action]) {
html += ''
+ '<a href="' + response[fields.action][fields.actionURL] + '" class="action">'
+ response[fields.action][fields.actionText]
+ '</a>';
}
return html;
}
return false;
}
}
};
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Shape
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.fn.shape = function(parameters) {
var
$allModules = $(this),
$body = $('body'),
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { setTimeout(callback, 0); },
returnedValue
;
$allModules
.each(function() {
var
moduleSelector = $allModules.selector || '',
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.shape.settings, parameters)
: $.extend({}, $.fn.shape.settings),
// internal aliases
namespace = settings.namespace,
selector = settings.selector,
error = settings.error,
className = settings.className,
// define namespaces for modules
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
// selector cache
$module = $(this),
$sides = $module.find(selector.sides),
$side = $module.find(selector.side),
// private variables
nextIndex = false,
$activeSide,
$nextSide,
// standard module
element = this,
instance = $module.data(moduleNamespace),
module
;
module = {
initialize: function() {
module.verbose('Initializing module for', element);
module.set.defaultSide();
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)
.off(eventNamespace)
;
},
refresh: function() {
module.verbose('Refreshing selector cache for', element);
$module = $(element);
$sides = $(this).find(selector.shape);
$side = $(this).find(selector.side);
},
repaint: function() {
module.verbose('Forcing repaint event');
var
shape = $sides[0] || document.createElement('div'),
fakeAssignment = shape.offsetWidth
;
},
animate: function(propertyObject, callback) {
module.verbose('Animating box with properties', propertyObject);
callback = callback || function(event) {
module.verbose('Executing animation callback');
if(event !== undefined) {
event.stopPropagation();
}
module.reset();
module.set.active();
};
settings.beforeChange.call($nextSide[0]);
if(module.get.transitionEvent()) {
module.verbose('Starting CSS animation');
$module
.addClass(className.animating)
;
$sides
.css(propertyObject)
.one(module.get.transitionEvent(), callback)
;
module.set.duration(settings.duration);
requestAnimationFrame(function() {
$module
.addClass(className.animating)
;
$activeSide
.addClass(className.hidden)
;
});
}
else {
callback();
}
},
queue: function(method) {
module.debug('Queueing animation of', method);
$sides
.one(module.get.transitionEvent(), function() {
module.debug('Executing queued animation');
setTimeout(function(){
$module.shape(method);
}, 0);
})
;
},
reset: function() {
module.verbose('Animating states reset');
$module
.removeClass(className.animating)
.attr('style', '')
.removeAttr('style')
;
// removeAttr style does not consistently work in safari
$sides
.attr('style', '')
.removeAttr('style')
;
$side
.attr('style', '')
.removeAttr('style')
.removeClass(className.hidden)
;
$nextSide
.removeClass(className.animating)
.attr('style', '')
.removeAttr('style')
;
},
is: {
complete: function() {
return ($side.filter('.' + className.active)[0] == $nextSide[0]);
},
animating: function() {
return $module.hasClass(className.animating);
}
},
set: {
defaultSide: function() {
$activeSide = $module.find('.' + settings.className.active);
$nextSide = ( $activeSide.next(selector.side).length > 0 )
? $activeSide.next(selector.side)
: $module.find(selector.side).first()
;
nextIndex = false;
module.verbose('Active side set to', $activeSide);
module.verbose('Next side set to', $nextSide);
},
duration: function(duration) {
duration = duration || settings.duration;
duration = (typeof duration == 'number')
? duration + 'ms'
: duration
;
module.verbose('Setting animation duration', duration);
if(settings.duration || settings.duration === 0) {
$sides.add($side)
.css({
'-webkit-transition-duration': duration,
'-moz-transition-duration': duration,
'-ms-transition-duration': duration,
'-o-transition-duration': duration,
'transition-duration': duration
})
;
}
},
currentStageSize: function() {
var
$activeSide = $module.find('.' + settings.className.active),
width = $activeSide.outerWidth(true),
height = $activeSide.outerHeight(true)
;
$module
.css({
width: width,
height: height
})
;
},
stageSize: function() {
var
$clone = $module.clone().addClass(className.loading),
$activeSide = $clone.find('.' + settings.className.active),
$nextSide = (nextIndex)
? $clone.find(selector.side).eq(nextIndex)
: ( $activeSide.next(selector.side).length > 0 )
? $activeSide.next(selector.side)
: $clone.find(selector.side).first(),
newSize = {}
;
module.set.currentStageSize();
$activeSide.removeClass(className.active);
$nextSide.addClass(className.active);
$clone.insertAfter($module);
newSize = {
width : $nextSide.outerWidth(true),
height : $nextSide.outerHeight(true)
};
$clone.remove();
$module
.css(newSize)
;
module.verbose('Resizing stage to fit new content', newSize);
},
nextSide: function(selector) {
nextIndex = selector;
$nextSide = $side.filter(selector);
nextIndex = $side.index($nextSide);
if($nextSide.length === 0) {
module.set.defaultSide();
module.error(error.side);
}
module.verbose('Next side manually set to', $nextSide);
},
active: function() {
module.verbose('Setting new side to active', $nextSide);
$side
.removeClass(className.active)
;
$nextSide
.addClass(className.active)
;
settings.onChange.call($nextSide[0]);
module.set.defaultSide();
}
},
flip: {
up: function() {
if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
module.debug('Side already visible', $nextSide);
return;
}
if( !module.is.animating()) {
module.debug('Flipping up', $nextSide);
module.set.stageSize();
module.stage.above();
module.animate( module.get.transform.up() );
}
else {
module.queue('flip up');
}
},
down: function() {
if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
module.debug('Side already visible', $nextSide);
return;
}
if( !module.is.animating()) {
module.debug('Flipping down', $nextSide);
module.set.stageSize();
module.stage.below();
module.animate( module.get.transform.down() );
}
else {
module.queue('flip down');
}
},
left: function() {
if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
module.debug('Side already visible', $nextSide);
return;
}
if( !module.is.animating()) {
module.debug('Flipping left', $nextSide);
module.set.stageSize();
module.stage.left();
module.animate(module.get.transform.left() );
}
else {
module.queue('flip left');
}
},
right: function() {
if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
module.debug('Side already visible', $nextSide);
return;
}
if( !module.is.animating()) {
module.debug('Flipping right', $nextSide);
module.set.stageSize();
module.stage.right();
module.animate(module.get.transform.right() );
}
else {
module.queue('flip right');
}
},
over: function() {
if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
module.debug('Side already visible', $nextSide);
return;
}
if( !module.is.animating()) {
module.debug('Flipping over', $nextSide);
module.set.stageSize();
module.stage.behind();
module.animate(module.get.transform.over() );
}
else {
module.queue('flip over');
}
},
back: function() {
if(module.is.complete() && !module.is.animating() && !settings.allowRepeats) {
module.debug('Side already visible', $nextSide);
return;
}
if( !module.is.animating()) {
module.debug('Flipping back', $nextSide);
module.set.stageSize();
module.stage.behind();
module.animate(module.get.transform.back() );
}
else {
module.queue('flip back');
}
}
},
get: {
transform: {
up: function() {
var
translate = {
y: -(($activeSide.outerHeight(true) - $nextSide.outerHeight(true)) / 2),
z: -($activeSide.outerHeight(true) / 2)
}
;
return {
transform: 'translateY(' + translate.y + 'px) translateZ('+ translate.z + 'px) rotateX(-90deg)'
};
},
down: function() {
var
translate = {
y: -(($activeSide.outerHeight(true) - $nextSide.outerHeight(true)) / 2),
z: -($activeSide.outerHeight(true) / 2)
}
;
return {
transform: 'translateY(' + translate.y + 'px) translateZ('+ translate.z + 'px) rotateX(90deg)'
};
},
left: function() {
var
translate = {
x : -(($activeSide.outerWidth(true) - $nextSide.outerWidth(true)) / 2),
z : -($activeSide.outerWidth(true) / 2)
}
;
return {
transform: 'translateX(' + translate.x + 'px) translateZ(' + translate.z + 'px) rotateY(90deg)'
};
},
right: function() {
var
translate = {
x : -(($activeSide.outerWidth(true) - $nextSide.outerWidth(true)) / 2),
z : -($activeSide.outerWidth(true) / 2)
}
;
return {
transform: 'translateX(' + translate.x + 'px) translateZ(' + translate.z + 'px) rotateY(-90deg)'
};
},
over: function() {
var
translate = {
x : -(($activeSide.outerWidth(true) - $nextSide.outerWidth(true)) / 2)
}
;
return {
transform: 'translateX(' + translate.x + 'px) rotateY(180deg)'
};
},
back: function() {
var
translate = {
x : -(($activeSide.outerWidth(true) - $nextSide.outerWidth(true)) / 2)
}
;
return {
transform: 'translateX(' + translate.x + 'px) rotateY(-180deg)'
};
}
},
transitionEvent: function() {
var
element = document.createElement('element'),
transitions = {
'transition' :'transitionend',
'OTransition' :'oTransitionEnd',
'MozTransition' :'transitionend',
'WebkitTransition' :'webkitTransitionEnd'
},
transition
;
for(transition in transitions){
if( element.style[transition] !== undefined ){
return transitions[transition];
}
}
},
nextSide: function() {
return ( $activeSide.next(selector.side).length > 0 )
? $activeSide.next(selector.side)
: $module.find(selector.side).first()
;
}
},
stage: {
above: function() {
var
box = {
origin : (($activeSide.outerHeight(true) - $nextSide.outerHeight(true)) / 2),
depth : {
active : ($nextSide.outerHeight(true) / 2),
next : ($activeSide.outerHeight(true) / 2)
}
}
;
module.verbose('Setting the initial animation position as above', $nextSide, box);
$sides
.css({
'transform' : 'translateZ(-' + box.depth.active + 'px)'
})
;
$activeSide
.css({
'transform' : 'rotateY(0deg) translateZ(' + box.depth.active + 'px)'
})
;
$nextSide
.addClass(className.animating)
.css({
'top' : box.origin + 'px',
'transform' : 'rotateX(90deg) translateZ(' + box.depth.next + 'px)'
})
;
},
below: function() {
var
box = {
origin : (($activeSide.outerHeight(true) - $nextSide.outerHeight(true)) / 2),
depth : {
active : ($nextSide.outerHeight(true) / 2),
next : ($activeSide.outerHeight(true) / 2)
}
}
;
module.verbose('Setting the initial animation position as below', $nextSide, box);
$sides
.css({
'transform' : 'translateZ(-' + box.depth.active + 'px)'
})
;
$activeSide
.css({
'transform' : 'rotateY(0deg) translateZ(' + box.depth.active + 'px)'
})
;
$nextSide
.addClass(className.animating)
.css({
'top' : box.origin + 'px',
'transform' : 'rotateX(-90deg) translateZ(' + box.depth.next + 'px)'
})
;
},
left: function() {
var
height = {
active : $activeSide.outerWidth(true),
next : $nextSide.outerWidth(true)
},
box = {
origin : ( ( height.active - height.next ) / 2),
depth : {
active : (height.next / 2),
next : (height.active / 2)
}
}
;
module.verbose('Setting the initial animation position as left', $nextSide, box);
$sides
.css({
'transform' : 'translateZ(-' + box.depth.active + 'px)'
})
;
$activeSide
.css({
'transform' : 'rotateY(0deg) translateZ(' + box.depth.active + 'px)'
})
;
$nextSide
.addClass(className.animating)
.css({
'left' : box.origin + 'px',
'transform' : 'rotateY(-90deg) translateZ(' + box.depth.next + 'px)'
})
;
},
right: function() {
var
height = {
active : $activeSide.outerWidth(true),
next : $nextSide.outerWidth(true)
},
box = {
origin : ( ( height.active - height.next ) / 2),
depth : {
active : (height.next / 2),
next : (height.active / 2)
}
}
;
module.verbose('Setting the initial animation position as left', $nextSide, box);
$sides
.css({
'transform' : 'translateZ(-' + box.depth.active + 'px)'
})
;
$activeSide
.css({
'transform' : 'rotateY(0deg) translateZ(' + box.depth.active + 'px)'
})
;
$nextSide
.addClass(className.animating)
.css({
'left' : box.origin + 'px',
'transform' : 'rotateY(90deg) translateZ(' + box.depth.next + 'px)'
})
;
},
behind: function() {
var
height = {
active : $activeSide.outerWidth(true),
next : $nextSide.outerWidth(true)
},
box = {
origin : ( ( height.active - height.next ) / 2),
depth : {
active : (height.next / 2),
next : (height.active / 2)
}
}
;
module.verbose('Setting the initial animation position as behind', $nextSide, box);
$activeSide
.css({
'transform' : 'rotateY(0deg)'
})
;
$nextSide
.addClass(className.animating)
.css({
'left' : box.origin + 'px',
'transform' : 'rotateY(-180deg)'
})
;
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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 = [];
}
},
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($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.shape.settings = {
// module info
name : 'Shape',
// debug content outputted to console
debug : false,
// verbose debug output
verbose : false,
// performance data output
performance: true,
// event namespace
namespace : 'shape',
// callback occurs on side change
beforeChange : function() {},
onChange : function() {},
// allow animation to same side
allowRepeats: false,
// animation duration
duration : false,
// possible errors
error: {
side : 'You tried to switch to a side that does not exist.',
method : 'The method you called is not defined'
},
// classnames used
className : {
animating : 'animating',
hidden : 'hidden',
loading : 'loading',
active : 'active'
},
// selectors used
selector : {
sides : '.sides',
side : '.side'
}
};
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Sidebar
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.fn.sidebar = function(parameters) {
var
$allModules = $(this),
$window = $(window),
$document = $(document),
$html = $('html'),
$head = $('head'),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { setTimeout(callback, 0); },
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.sidebar.settings, parameters)
: $.extend({}, $.fn.sidebar.settings),
selector = settings.selector,
className = settings.className,
namespace = settings.namespace,
regExp = settings.regExp,
error = settings.error,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
$module = $(this),
$context = $(settings.context),
$sidebars = $module.children(selector.sidebar),
$fixed = $context.children(selector.fixed),
$pusher = $context.children(selector.pusher),
$style,
element = this,
instance = $module.data(moduleNamespace),
elementNamespace,
id,
currentScroll,
transitionEvent,
module
;
module = {
initialize: function() {
module.debug('Initializing sidebar', parameters);
module.create.id();
transitionEvent = module.get.transitionEvent();
if(module.is.ios()) {
module.set.ios();
}
// avoids locking rendering if initialized in onReady
if(settings.delaySetup) {
requestAnimationFrame(module.setup.layout);
}
else {
module.setup.layout();
}
requestAnimationFrame(function() {
module.setup.cache();
});
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of module', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
create: {
id: function() {
id = (Math.random().toString(16) + '000000000').substr(2,8);
elementNamespace = '.' + id;
module.verbose('Creating unique id for element', id);
}
},
destroy: function() {
module.verbose('Destroying previous module for', $module);
$module
.off(eventNamespace)
.removeData(moduleNamespace)
;
if(module.is.ios()) {
module.remove.ios();
}
// bound by uuid
$context.off(elementNamespace);
$window.off(elementNamespace);
$document.off(elementNamespace);
},
event: {
clickaway: function(event) {
var
clickedInPusher = ($pusher.find(event.target).length > 0 || $pusher.is(event.target)),
clickedContext = ($context.is(event.target))
;
if(clickedInPusher) {
module.verbose('User clicked on dimmed page');
module.hide();
}
if(clickedContext) {
module.verbose('User clicked on dimmable context (scaled out page)');
module.hide();
}
},
touch: function(event) {
//event.stopPropagation();
},
containScroll: function(event) {
if(element.scrollTop <= 0) {
element.scrollTop = 1;
}
if((element.scrollTop + element.offsetHeight) >= element.scrollHeight) {
element.scrollTop = element.scrollHeight - element.offsetHeight - 1;
}
},
scroll: function(event) {
if( $(event.target).closest(selector.sidebar).length === 0 ) {
event.preventDefault();
}
}
},
bind: {
clickaway: function() {
module.verbose('Adding clickaway events to context', $context);
if(settings.closable) {
$context
.on('click' + elementNamespace, module.event.clickaway)
.on('touchend' + elementNamespace, module.event.clickaway)
;
}
},
scrollLock: function() {
if(settings.scrollLock) {
module.debug('Disabling page scroll');
$window
.on('DOMMouseScroll' + elementNamespace, module.event.scroll)
;
}
module.verbose('Adding events to contain sidebar scroll');
$document
.on('touchmove' + elementNamespace, module.event.touch)
;
$module
.on('scroll' + eventNamespace, module.event.containScroll)
;
}
},
unbind: {
clickaway: function() {
module.verbose('Removing clickaway events from context', $context);
$context.off(elementNamespace);
},
scrollLock: function() {
module.verbose('Removing scroll lock from page');
$document.off(elementNamespace);
$window.off(elementNamespace);
$module.off('scroll' + eventNamespace);
}
},
add: {
inlineCSS: function() {
var
width = module.cache.width || $module.outerWidth(),
height = module.cache.height || $module.outerHeight(),
isRTL = module.is.rtl(),
direction = module.get.direction(),
distance = {
left : width,
right : -width,
top : height,
bottom : -height
},
style
;
if(isRTL){
module.verbose('RTL detected, flipping widths');
distance.left = -width;
distance.right = width;
}
style = '<style>';
if(direction === 'left' || direction === 'right') {
module.debug('Adding CSS rules for animation distance', width);
style += ''
+ ' .ui.visible.' + direction + '.sidebar ~ .fixed,'
+ ' .ui.visible.' + direction + '.sidebar ~ .pusher {'
+ ' -webkit-transform: translate3d('+ distance[direction] + 'px, 0, 0);'
+ ' transform: translate3d('+ distance[direction] + 'px, 0, 0);'
+ ' }'
;
}
else if(direction === 'top' || direction == 'bottom') {
style += ''
+ ' .ui.visible.' + direction + '.sidebar ~ .fixed,'
+ ' .ui.visible.' + direction + '.sidebar ~ .pusher {'
+ ' -webkit-transform: translate3d(0, ' + distance[direction] + 'px, 0);'
+ ' transform: translate3d(0, ' + distance[direction] + 'px, 0);'
+ ' }'
;
}
/* IE is only browser not to create context with transforms */
/* https://www.w3.org/Bugs/Public/show_bug.cgi?id=16328 */
if( module.is.ie() ) {
if(direction === 'left' || direction === 'right') {
module.debug('Adding CSS rules for animation distance', width);
style += ''
+ ' body.pushable > .ui.visible.' + direction + '.sidebar ~ .pusher:after {'
+ ' -webkit-transform: translate3d('+ distance[direction] + 'px, 0, 0);'
+ ' transform: translate3d('+ distance[direction] + 'px, 0, 0);'
+ ' }'
;
}
else if(direction === 'top' || direction == 'bottom') {
style += ''
+ ' body.pushable > .ui.visible.' + direction + '.sidebar ~ .pusher:after {'
+ ' -webkit-transform: translate3d(0, ' + distance[direction] + 'px, 0);'
+ ' transform: translate3d(0, ' + distance[direction] + 'px, 0);'
+ ' }'
;
}
/* opposite sides visible forces content overlay */
style += ''
+ ' body.pushable > .ui.visible.left.sidebar ~ .ui.visible.right.sidebar ~ .pusher:after,'
+ ' body.pushable > .ui.visible.right.sidebar ~ .ui.visible.left.sidebar ~ .pusher:after {'
+ ' -webkit-transform: translate3d(0px, 0, 0);'
+ ' transform: translate3d(0px, 0, 0);'
+ ' }'
;
}
style += '</style>';
$style = $(style)
.appendTo($head)
;
module.debug('Adding sizing css to head', $style);
}
},
refresh: function() {
module.verbose('Refreshing selector cache');
$context = $(settings.context);
$sidebars = $context.children(selector.sidebar);
$pusher = $context.children(selector.pusher);
$fixed = $context.children(selector.fixed);
module.clear.cache();
},
refreshSidebars: function() {
module.verbose('Refreshing other sidebars');
$sidebars = $context.children(selector.sidebar);
},
repaint: function() {
module.verbose('Forcing repaint event');
element.style.display = 'none';
var ignored = element.offsetHeight;
element.scrollTop = element.scrollTop;
element.style.display = '';
},
setup: {
cache: function() {
module.cache = {
width : $module.outerWidth(),
height : $module.outerHeight(),
rtl : ($module.css('direction') == 'rtl')
};
},
layout: function() {
if( $context.children(selector.pusher).length === 0 ) {
module.debug('Adding wrapper element for sidebar');
module.error(error.pusher);
$pusher = $('<div class="pusher" />');
$context
.children()
.not(selector.omitted)
.not($sidebars)
.wrapAll($pusher)
;
module.refresh();
}
if($module.nextAll(selector.pusher).length === 0 || $module.nextAll(selector.pusher)[0] !== $pusher[0]) {
module.debug('Moved sidebar to correct parent element');
module.error(error.movedSidebar, element);
$module.detach().prependTo($context);
module.refresh();
}
module.clear.cache();
module.set.pushable();
module.set.direction();
}
},
attachEvents: function(selector, event) {
var
$toggle = $(selector)
;
event = $.isFunction(module[event])
? module[event]
: module.toggle
;
if($toggle.length > 0) {
module.debug('Attaching sidebar events to element', selector, event);
$toggle
.on('click' + eventNamespace, event)
;
}
else {
module.error(error.notFound, selector);
}
},
show: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if(module.is.hidden()) {
module.refreshSidebars();
if(settings.overlay) {
module.error(error.overlay);
settings.transition = 'overlay';
}
module.refresh();
if(module.othersActive()) {
module.debug('Other sidebars currently visible');
if(settings.exclusive) {
// if not overlay queue animation after hide
if(settings.transition != 'overlay') {
module.hideOthers(module.show);
return;
}
else {
module.hideOthers();
}
}
else {
settings.transition = 'overlay';
}
}
module.pushPage(function() {
callback.call(element);
settings.onShow.call(element);
});
settings.onChange.call(element);
settings.onVisible.call(element);
}
else {
module.debug('Sidebar is already visible');
}
},
hide: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
if(module.is.visible() || module.is.animating()) {
module.debug('Hiding sidebar', callback);
module.refreshSidebars();
module.pullPage(function() {
callback.call(element);
settings.onHidden.call(element);
});
settings.onChange.call(element);
settings.onHide.call(element);
}
},
othersAnimating: function() {
return ($sidebars.not($module).filter('.' + className.animating).length > 0);
},
othersVisible: function() {
return ($sidebars.not($module).filter('.' + className.visible).length > 0);
},
othersActive: function() {
return(module.othersVisible() || module.othersAnimating());
},
hideOthers: function(callback) {
var
$otherSidebars = $sidebars.not($module).filter('.' + className.visible),
sidebarCount = $otherSidebars.length,
callbackCount = 0
;
callback = callback || function(){};
$otherSidebars
.sidebar('hide', function() {
callbackCount++;
if(callbackCount == sidebarCount) {
callback();
}
})
;
},
toggle: function() {
module.verbose('Determining toggled direction');
if(module.is.hidden()) {
module.show();
}
else {
module.hide();
}
},
pushPage: function(callback) {
var
transition = module.get.transition(),
$transition = (transition === 'overlay' || module.othersActive())
? $module
: $pusher,
animate,
dim,
transitionEnd
;
callback = $.isFunction(callback)
? callback
: function(){}
;
if(settings.transition == 'scale down') {
module.scrollToTop();
}
module.set.transition(transition);
module.repaint();
animate = function() {
module.bind.clickaway();
module.add.inlineCSS();
module.set.animating();
module.set.visible();
};
dim = function() {
module.set.dimmed();
};
transitionEnd = function(event) {
if( event.target == $transition[0] ) {
$transition.off(transitionEvent + elementNamespace, transitionEnd);
module.remove.animating();
module.bind.scrollLock();
callback.call(element);
}
};
$transition.off(transitionEvent + elementNamespace);
$transition.on(transitionEvent + elementNamespace, transitionEnd);
requestAnimationFrame(animate);
if(settings.dimPage && !module.othersVisible()) {
requestAnimationFrame(dim);
}
},
pullPage: function(callback) {
var
transition = module.get.transition(),
$transition = (transition == 'overlay' || module.othersActive())
? $module
: $pusher,
animate,
transitionEnd
;
callback = $.isFunction(callback)
? callback
: function(){}
;
module.verbose('Removing context push state', module.get.direction());
module.unbind.clickaway();
module.unbind.scrollLock();
animate = function() {
module.set.transition(transition);
module.set.animating();
module.remove.visible();
if(settings.dimPage && !module.othersVisible()) {
$pusher.removeClass(className.dimmed);
}
};
transitionEnd = function(event) {
if( event.target == $transition[0] ) {
$transition.off(transitionEvent + elementNamespace, transitionEnd);
module.remove.animating();
module.remove.transition();
module.remove.inlineCSS();
if(transition == 'scale down' || (settings.returnScroll && module.is.mobile()) ) {
module.scrollBack();
}
callback.call(element);
}
};
$transition.off(transitionEvent + elementNamespace);
$transition.on(transitionEvent + elementNamespace, transitionEnd);
requestAnimationFrame(animate);
},
scrollToTop: function() {
module.verbose('Scrolling to top of page to avoid animation issues');
currentScroll = $(window).scrollTop();
$module.scrollTop(0);
window.scrollTo(0, 0);
},
scrollBack: function() {
module.verbose('Scrolling back to original page position');
window.scrollTo(0, currentScroll);
},
clear: {
cache: function() {
module.verbose('Clearing cached dimensions');
module.cache = {};
}
},
set: {
// ios only (scroll on html not document). This prevent auto-resize canvas/scroll in ios
ios: function() {
$html.addClass(className.ios);
},
// container
pushed: function() {
$context.addClass(className.pushed);
},
pushable: function() {
$context.addClass(className.pushable);
},
// pusher
dimmed: function() {
$pusher.addClass(className.dimmed);
},
// sidebar
active: function() {
$module.addClass(className.active);
},
animating: function() {
$module.addClass(className.animating);
},
transition: function(transition) {
transition = transition || module.get.transition();
$module.addClass(transition);
},
direction: function(direction) {
direction = direction || module.get.direction();
$module.addClass(className[direction]);
},
visible: function() {
$module.addClass(className.visible);
},
overlay: function() {
$module.addClass(className.overlay);
}
},
remove: {
inlineCSS: function() {
module.debug('Removing inline css styles', $style);
if($style && $style.length > 0) {
$style.remove();
}
},
// ios scroll on html not document
ios: function() {
$html.removeClass(className.ios);
},
// context
pushed: function() {
$context.removeClass(className.pushed);
},
pushable: function() {
$context.removeClass(className.pushable);
},
// sidebar
active: function() {
$module.removeClass(className.active);
},
animating: function() {
$module.removeClass(className.animating);
},
transition: function(transition) {
transition = transition || module.get.transition();
$module.removeClass(transition);
},
direction: function(direction) {
direction = direction || module.get.direction();
$module.removeClass(className[direction]);
},
visible: function() {
$module.removeClass(className.visible);
},
overlay: function() {
$module.removeClass(className.overlay);
}
},
get: {
direction: function() {
if($module.hasClass(className.top)) {
return className.top;
}
else if($module.hasClass(className.right)) {
return className.right;
}
else if($module.hasClass(className.bottom)) {
return className.bottom;
}
return className.left;
},
transition: function() {
var
direction = module.get.direction(),
transition
;
transition = ( module.is.mobile() )
? (settings.mobileTransition == 'auto')
? settings.defaultTransition.mobile[direction]
: settings.mobileTransition
: (settings.transition == 'auto')
? settings.defaultTransition.computer[direction]
: settings.transition
;
module.verbose('Determined transition', transition);
return transition;
},
transitionEvent: function() {
var
element = document.createElement('element'),
transitions = {
'transition' :'transitionend',
'OTransition' :'oTransitionEnd',
'MozTransition' :'transitionend',
'WebkitTransition' :'webkitTransitionEnd'
},
transition
;
for(transition in transitions){
if( element.style[transition] !== undefined ){
return transitions[transition];
}
}
}
},
is: {
ie: function() {
var
isIE11 = (!(window.ActiveXObject) && 'ActiveXObject' in window),
isIE = ('ActiveXObject' in window)
;
return (isIE11 || isIE);
},
ios: function() {
var
userAgent = navigator.userAgent,
isIOS = userAgent.match(regExp.ios),
isMobileChrome = userAgent.match(regExp.mobileChrome)
;
if(isIOS && !isMobileChrome) {
module.verbose('Browser was found to be iOS', userAgent);
return true;
}
else {
return false;
}
},
mobile: function() {
var
userAgent = navigator.userAgent,
isMobile = userAgent.match(regExp.mobile)
;
if(isMobile) {
module.verbose('Browser was found to be mobile', userAgent);
return true;
}
else {
module.verbose('Browser is not mobile, using regular transition', userAgent);
return false;
}
},
hidden: function() {
return !module.is.visible();
},
visible: function() {
return $module.hasClass(className.visible);
},
// alias
open: function() {
return module.is.visible();
},
closed: function() {
return module.is.hidden();
},
vertical: function() {
return $module.hasClass(className.top);
},
animating: function() {
return $context.hasClass(className.animating);
},
rtl: function () {
if(module.cache.rtl === undefined) {
module.cache.rtl = ($module.css('direction') == 'rtl');
}
return module.cache.rtl;
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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( (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 = [];
}
},
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 {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
}
;
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
module.invoke('destroy');
}
module.initialize();
}
});
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.sidebar.settings = {
name : 'Sidebar',
namespace : 'sidebar',
debug : false,
verbose : false,
performance : true,
transition : 'auto',
mobileTransition : 'auto',
defaultTransition : {
computer: {
left : 'uncover',
right : 'uncover',
top : 'overlay',
bottom : 'overlay'
},
mobile: {
left : 'uncover',
right : 'uncover',
top : 'overlay',
bottom : 'overlay'
}
},
context : 'body',
exclusive : false,
closable : true,
dimPage : true,
scrollLock : false,
returnScroll : false,
delaySetup : false,
duration : 500,
onChange : function(){},
onShow : function(){},
onHide : function(){},
onHidden : function(){},
onVisible : function(){},
className : {
active : 'active',
animating : 'animating',
dimmed : 'dimmed',
ios : 'ios',
pushable : 'pushable',
pushed : 'pushed',
right : 'right',
top : 'top',
left : 'left',
bottom : 'bottom',
visible : 'visible'
},
selector: {
fixed : '.fixed',
omitted : 'script, link, style, .ui.modal, .ui.dimmer, .ui.nag, .ui.fixed',
pusher : '.pusher',
sidebar : '.ui.sidebar'
},
regExp: {
ios : /(iPad|iPhone|iPod)/g,
mobileChrome : /(CriOS)/g,
mobile : /Mobile|iP(hone|od|ad)|Android|BlackBerry|IEMobile|Kindle|NetFront|Silk-Accelerated|(hpw|web)OS|Fennec|Minimo|Opera M(obi|ini)|Blazer|Dolfin|Dolphin|Skyfire|Zune/g
},
error : {
method : 'The method you called is not defined.',
pusher : 'Had to add pusher element. For optimal performance make sure body content is inside a pusher element',
movedSidebar : 'Had to move sidebar. For optimal performance make sure sidebar and pusher are direct children of your body tag',
overlay : 'The overlay setting is no longer supported, use animation: overlay',
notFound : 'There were no elements that matched the specified selector'
}
};
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Sticky
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.fn.sticky = function(parameters) {
var
$allModules = $(this),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.sticky.settings, parameters)
: $.extend({}, $.fn.sticky.settings),
className = settings.className,
namespace = settings.namespace,
error = settings.error,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
$module = $(this),
$window = $(window),
$scroll = $(settings.scrollContext),
$container,
$context,
selector = $module.selector || '',
instance = $module.data(moduleNamespace),
requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { setTimeout(callback, 0); },
element = this,
observer,
module
;
module = {
initialize: function() {
module.determineContainer();
module.determineContext();
module.verbose('Initializing sticky', settings, $container);
module.save.positions();
module.checkErrors();
module.bind.events();
if(settings.observeChanges) {
module.observeChanges();
}
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of module', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
destroy: function() {
module.verbose('Destroying previous instance');
module.reset();
if(observer) {
observer.disconnect();
}
$window
.off('load' + eventNamespace, module.event.load)
.off('resize' + eventNamespace, module.event.resize)
;
$scroll
.off('scrollchange' + eventNamespace, module.event.scrollchange)
;
$module.removeData(moduleNamespace);
},
observeChanges: function() {
var
context = $context[0]
;
if('MutationObserver' in window) {
observer = new MutationObserver(function(mutations) {
clearTimeout(module.timer);
module.timer = setTimeout(function() {
module.verbose('DOM tree modified, updating sticky menu', mutations);
module.refresh();
}, 100);
});
observer.observe(element, {
childList : true,
subtree : true
});
observer.observe(context, {
childList : true,
subtree : true
});
module.debug('Setting up mutation observer', observer);
}
},
determineContainer: function() {
$container = $module.offsetParent();
},
determineContext: function() {
if(settings.context) {
$context = $(settings.context);
}
else {
$context = $container;
}
if($context.length === 0) {
module.error(error.invalidContext, settings.context, $module);
return;
}
},
checkErrors: function() {
if( module.is.hidden() ) {
module.error(error.visible, $module);
}
if(module.cache.element.height > module.cache.context.height) {
module.reset();
module.error(error.elementSize, $module);
return;
}
},
bind: {
events: function() {
$window
.on('load' + eventNamespace, module.event.load)
.on('resize' + eventNamespace, module.event.resize)
;
// pub/sub pattern
$scroll
.off('scroll' + eventNamespace)
.on('scroll' + eventNamespace, module.event.scroll)
.on('scrollchange' + eventNamespace, module.event.scrollchange)
;
}
},
event: {
load: function() {
module.verbose('Page contents finished loading');
requestAnimationFrame(module.refresh);
},
resize: function() {
module.verbose('Window resized');
requestAnimationFrame(module.refresh);
},
scroll: function() {
requestAnimationFrame(function() {
$scroll.triggerHandler('scrollchange' + eventNamespace, $scroll.scrollTop() );
});
},
scrollchange: function(event, scrollPosition) {
module.stick(scrollPosition);
settings.onScroll.call(element);
}
},
refresh: function(hardRefresh) {
module.reset();
if(!settings.context) {
module.determineContext();
}
if(hardRefresh) {
module.determineContainer();
}
module.save.positions();
module.stick();
settings.onReposition.call(element);
},
supports: {
sticky: function() {
var
$element = $('<div/>'),
element = $element[0]
;
$element.addClass(className.supported);
return($element.css('position').match('sticky'));
}
},
save: {
lastScroll: function(scroll) {
module.lastScroll = scroll;
},
elementScroll: function(scroll) {
module.elementScroll = scroll;
},
positions: function() {
var
window = {
height: $window.height()
},
element = {
margin: {
top : parseInt($module.css('margin-top'), 10),
bottom : parseInt($module.css('margin-bottom'), 10),
},
offset : $module.offset(),
width : $module.outerWidth(),
height : $module.outerHeight()
},
context = {
offset : $context.offset(),
height : $context.outerHeight()
},
container = {
height: $container.outerHeight()
}
;
module.cache = {
fits : ( element.height < window.height ),
window: {
height: window.height
},
element: {
margin : element.margin,
top : element.offset.top - element.margin.top,
left : element.offset.left,
width : element.width,
height : element.height,
bottom : element.offset.top + element.height
},
context: {
top : context.offset.top,
height : context.height,
bottom : context.offset.top + context.height
}
};
module.set.containerSize();
module.set.size();
module.stick();
module.debug('Caching element positions', module.cache);
}
},
get: {
direction: function(scroll) {
var
direction = 'down'
;
scroll = scroll || $scroll.scrollTop();
if(module.lastScroll !== undefined) {
if(module.lastScroll < scroll) {
direction = 'down';
}
else if(module.lastScroll > scroll) {
direction = 'up';
}
}
return direction;
},
scrollChange: function(scroll) {
scroll = scroll || $scroll.scrollTop();
return (module.lastScroll)
? (scroll - module.lastScroll)
: 0
;
},
currentElementScroll: function() {
if(module.elementScroll) {
return module.elementScroll;
}
return ( module.is.top() )
? Math.abs(parseInt($module.css('top'), 10)) || 0
: Math.abs(parseInt($module.css('bottom'), 10)) || 0
;
},
elementScroll: function(scroll) {
scroll = scroll || $scroll.scrollTop();
var
element = module.cache.element,
window = module.cache.window,
delta = module.get.scrollChange(scroll),
maxScroll = (element.height - window.height + settings.offset),
elementScroll = module.get.currentElementScroll(),
possibleScroll = (elementScroll + delta)
;
if(module.cache.fits || possibleScroll < 0) {
elementScroll = 0;
}
else if(possibleScroll > maxScroll ) {
elementScroll = maxScroll;
}
else {
elementScroll = possibleScroll;
}
return elementScroll;
}
},
remove: {
lastScroll: function() {
delete module.lastScroll;
},
elementScroll: function(scroll) {
delete module.elementScroll;
},
offset: function() {
$module.css('margin-top', '');
}
},
set: {
offset: function() {
module.verbose('Setting offset on element', settings.offset);
$module
.css('margin-top', settings.offset)
;
},
containerSize: function() {
var
tagName = $container.get(0).tagName
;
if(tagName === 'HTML' || tagName == 'body') {
// this can trigger for too many reasons
//module.error(error.container, tagName, $module);
module.determineContainer();
}
else {
if( Math.abs($container.outerHeight() - module.cache.context.height) > settings.jitter) {
module.debug('Context has padding, specifying exact height for container', module.cache.context.height);
$container.css({
height: module.cache.context.height
});
}
}
},
minimumSize: function() {
var
element = module.cache.element
;
$container
.css('min-height', element.height)
;
},
scroll: function(scroll) {
module.debug('Setting scroll on element', scroll);
if(module.elementScroll == scroll) {
return;
}
if( module.is.top() ) {
$module
.css('bottom', '')
.css('top', -scroll)
;
}
if( module.is.bottom() ) {
$module
.css('top', '')
.css('bottom', scroll)
;
}
},
size: function() {
if(module.cache.element.height !== 0 && module.cache.element.width !== 0) {
element.style.setProperty('width', module.cache.element.width + 'px', 'important');
element.style.setProperty('height', module.cache.element.height + 'px', 'important');
}
}
},
is: {
top: function() {
return $module.hasClass(className.top);
},
bottom: function() {
return $module.hasClass(className.bottom);
},
initialPosition: function() {
return (!module.is.fixed() && !module.is.bound());
},
hidden: function() {
return (!$module.is(':visible'));
},
bound: function() {
return $module.hasClass(className.bound);
},
fixed: function() {
return $module.hasClass(className.fixed);
}
},
stick: function(scroll) {
var
cachedPosition = scroll || $scroll.scrollTop(),
cache = module.cache,
fits = cache.fits,
element = cache.element,
window = cache.window,
context = cache.context,
offset = (module.is.bottom() && settings.pushing)
? settings.bottomOffset
: settings.offset,
scroll = {
top : cachedPosition + offset,
bottom : cachedPosition + offset + window.height
},
direction = module.get.direction(scroll.top),
elementScroll = (fits)
? 0
: module.get.elementScroll(scroll.top),
// shorthand
doesntFit = !fits,
elementVisible = (element.height !== 0)
;
if(elementVisible) {
if( module.is.initialPosition() ) {
if(scroll.top >= context.bottom) {
module.debug('Initial element position is bottom of container');
module.bindBottom();
}
else if(scroll.top > element.top) {
if( (element.height + scroll.top - elementScroll) >= context.bottom ) {
module.debug('Initial element position is bottom of container');
module.bindBottom();
}
else {
module.debug('Initial element position is fixed');
module.fixTop();
}
}
}
else if( module.is.fixed() ) {
// currently fixed top
if( module.is.top() ) {
if( scroll.top <= element.top ) {
module.debug('Fixed element reached top of container');
module.setInitialPosition();
}
else if( (element.height + scroll.top - elementScroll) >= context.bottom ) {
module.debug('Fixed element reached bottom of container');
module.bindBottom();
}
// scroll element if larger than screen
else if(doesntFit) {
module.set.scroll(elementScroll);
module.save.lastScroll(scroll.top);
module.save.elementScroll(elementScroll);
}
}
// currently fixed bottom
else if(module.is.bottom() ) {
// top edge
if( (scroll.bottom - element.height) <= element.top) {
module.debug('Bottom fixed rail has reached top of container');
module.setInitialPosition();
}
// bottom edge
else if(scroll.bottom >= context.bottom) {
module.debug('Bottom fixed rail has reached bottom of container');
module.bindBottom();
}
// scroll element if larger than screen
else if(doesntFit) {
module.set.scroll(elementScroll);
module.save.lastScroll(scroll.top);
module.save.elementScroll(elementScroll);
}
}
}
else if( module.is.bottom() ) {
if(settings.pushing) {
if(module.is.bound() && scroll.bottom <= context.bottom ) {
module.debug('Fixing bottom attached element to bottom of browser.');
module.fixBottom();
}
}
else {
if(module.is.bound() && (scroll.top <= context.bottom - element.height) ) {
module.debug('Fixing bottom attached element to top of browser.');
module.fixTop();
}
}
}
}
},
bindTop: function() {
module.debug('Binding element to top of parent container');
module.remove.offset();
$module
.css({
left : '',
top : '',
marginBottom : ''
})
.removeClass(className.fixed)
.removeClass(className.bottom)
.addClass(className.bound)
.addClass(className.top)
;
settings.onTop.call(element);
settings.onUnstick.call(element);
},
bindBottom: function() {
module.debug('Binding element to bottom of parent container');
module.remove.offset();
$module
.css({
left : '',
top : ''
})
.removeClass(className.fixed)
.removeClass(className.top)
.addClass(className.bound)
.addClass(className.bottom)
;
settings.onBottom.call(element);
settings.onUnstick.call(element);
},
setInitialPosition: function() {
module.debug('Returning to initial position');
module.unfix();
module.unbind();
},
fixTop: function() {
module.debug('Fixing element to top of page');
module.set.minimumSize();
module.set.offset();
$module
.css({
left : module.cache.element.left,
bottom : '',
marginBottom : ''
})
.removeClass(className.bound)
.removeClass(className.bottom)
.addClass(className.fixed)
.addClass(className.top)
;
settings.onStick.call(element);
},
fixBottom: function() {
module.debug('Sticking element to bottom of page');
module.set.minimumSize();
module.set.offset();
$module
.css({
left : module.cache.element.left,
bottom : '',
marginBottom : ''
})
.removeClass(className.bound)
.removeClass(className.top)
.addClass(className.fixed)
.addClass(className.bottom)
;
settings.onStick.call(element);
},
unbind: function() {
if( module.is.bound() ) {
module.debug('Removing container bound position on element');
module.remove.offset();
$module
.removeClass(className.bound)
.removeClass(className.top)
.removeClass(className.bottom)
;
}
},
unfix: function() {
if( module.is.fixed() ) {
module.debug('Removing fixed position on element');
module.remove.offset();
$module
.removeClass(className.fixed)
.removeClass(className.top)
.removeClass(className.bottom)
;
settings.onUnstick.call(element);
}
},
reset: function() {
module.debug('Reseting elements position');
module.unbind();
module.unfix();
module.resetCSS();
module.remove.offset();
module.remove.lastScroll();
},
resetCSS: function() {
$module
.css({
width : '',
height : ''
})
;
$container
.css({
height: ''
})
;
},
setting: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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, 0);
},
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( (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 = [];
}
},
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($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.sticky.settings = {
name : 'Sticky',
namespace : 'sticky',
debug : false,
verbose : true,
performance : true,
// whether to stick in the opposite direction on scroll up
pushing : false,
context : false,
// Context to watch scroll events
scrollContext : window,
// Offset to adjust scroll
offset : 0,
// Offset to adjust scroll when attached to bottom of screen
bottomOffset : 0,
jitter : 5, // will only set container height if difference between context and container is larger than this number
// Whether to automatically observe changes with Mutation Observers
observeChanges : false,
// Called when position is recalculated
onReposition : function(){},
// Called on each scroll
onScroll : function(){},
// Called when element is stuck to viewport
onStick : function(){},
// Called when element is unstuck from viewport
onUnstick : function(){},
// Called when element reaches top of context
onTop : function(){},
// Called when element reaches bottom of context
onBottom : function(){},
error : {
container : 'Sticky element must be inside a relative container',
visible : 'Element is hidden, you must call refresh after element becomes visible',
method : 'The method you called is not defined.',
invalidContext : 'Context specified does not exist',
elementSize : 'Sticky element is larger than its container, cannot create sticky.'
},
className : {
bound : 'bound',
fixed : 'fixed',
supported : 'native',
top : 'top',
bottom : 'bottom'
}
};
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Tab
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ($, window, document, undefined) {
"use strict";
$.fn.tab = function(parameters) {
var
// use window context if none specified
$allModules = $.isFunction(this)
? $(window)
: $(this),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
initializedHistory = false,
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.tab.settings, parameters)
: $.extend({}, $.fn.tab.settings),
className = settings.className,
metadata = settings.metadata,
selector = settings.selector,
error = settings.error,
eventNamespace = '.' + settings.namespace,
moduleNamespace = 'module-' + settings.namespace,
$module = $(this),
$context,
$tabs,
cache = {},
firstLoad = true,
recursionDepth = 0,
element = this,
instance = $module.data(moduleNamespace),
activeTabPath,
parameterArray,
module,
historyEvent
;
module = {
initialize: function() {
module.debug('Initializing tab menu item', $module);
module.fix.callbacks();
module.determineTabs();
module.debug('Determining tabs', settings.context, $tabs);
// set up automatic routing
if(settings.auto) {
module.set.auto();
}
module.bind.events();
if(settings.history && !initializedHistory) {
module.initializeHistory();
initializedHistory = true;
}
module.instantiate();
},
instantiate: function () {
module.verbose('Storing instance of module', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
destroy: function() {
module.debug('Destroying tabs', $module);
$module
.removeData(moduleNamespace)
.off(eventNamespace)
;
},
bind: {
events: function() {
// if using $.tab don't add events
if( !$.isWindow( element ) ) {
module.debug('Attaching tab activation events to element', $module);
$module
.on('click' + eventNamespace, module.event.click)
;
}
}
},
determineTabs: function() {
var
$reference
;
// determine tab context
if(settings.context === 'parent') {
if($module.closest(selector.ui).length > 0) {
$reference = $module.closest(selector.ui);
module.verbose('Using closest UI element as parent', $reference);
}
else {
$reference = $module;
}
$context = $reference.parent();
module.verbose('Determined parent element for creating context', $context);
}
else if(settings.context) {
$context = $(settings.context);
module.verbose('Using selector for tab context', settings.context, $context);
}
else {
$context = $('body');
}
// find tabs
if(settings.childrenOnly) {
$tabs = $context.children(selector.tabs);
module.debug('Searching tab context children for tabs', $context, $tabs);
}
else {
$tabs = $context.find(selector.tabs);
module.debug('Searching tab context for tabs', $context, $tabs);
}
},
fix: {
callbacks: function() {
if( $.isPlainObject(parameters) && (parameters.onTabLoad || parameters.onTabInit) ) {
if(parameters.onTabLoad) {
parameters.onLoad = parameters.onTabLoad;
delete parameters.onTabLoad;
module.error(error.legacyLoad, parameters.onLoad);
}
if(parameters.onTabInit) {
parameters.onFirstLoad = parameters.onTabInit;
delete parameters.onTabInit;
module.error(error.legacyInit, parameters.onFirstLoad);
}
settings = $.extend(true, {}, $.fn.tab.settings, parameters);
}
}
},
initializeHistory: function() {
module.debug('Initializing page state');
if( $.address === undefined ) {
module.error(error.state);
return false;
}
else {
if(settings.historyType == 'state') {
module.debug('Using HTML5 to manage state');
if(settings.path !== false) {
$.address
.history(true)
.state(settings.path)
;
}
else {
module.error(error.path);
return false;
}
}
$.address
.bind('change', module.event.history.change)
;
}
},
event: {
click: function(event) {
var
tabPath = $(this).data(metadata.tab)
;
if(tabPath !== undefined) {
if(settings.history) {
module.verbose('Updating page state', event);
$.address.value(tabPath);
}
else {
module.verbose('Changing tab', event);
module.changeTab(tabPath);
}
event.preventDefault();
}
else {
module.debug('No tab specified');
}
},
history: {
change: function(event) {
var
tabPath = event.pathNames.join('/') || module.get.initialPath(),
pageTitle = settings.templates.determineTitle(tabPath) || false
;
module.performance.display();
module.debug('History change event', tabPath, event);
historyEvent = event;
if(tabPath !== undefined) {
module.changeTab(tabPath);
}
if(pageTitle) {
$.address.title(pageTitle);
}
}
}
},
refresh: function() {
if(activeTabPath) {
module.debug('Refreshing tab', activeTabPath);
module.changeTab(activeTabPath);
}
},
cache: {
read: function(cacheKey) {
return (cacheKey !== undefined)
? cache[cacheKey]
: false
;
},
add: function(cacheKey, content) {
cacheKey = cacheKey || activeTabPath;
module.debug('Adding cached content for', cacheKey);
cache[cacheKey] = content;
},
remove: function(cacheKey) {
cacheKey = cacheKey || activeTabPath;
module.debug('Removing cached content for', cacheKey);
delete cache[cacheKey];
}
},
set: {
auto: function() {
var
url = (typeof settings.path == 'string')
? settings.path.replace(/\/$/, '') + '/{$tab}'
: '/{$tab}'
;
module.verbose('Setting up automatic tab retrieval from server', url);
if($.isPlainObject(settings.apiSettings)) {
settings.apiSettings.url = url;
}
else {
settings.apiSettings = {
url: url
};
}
},
loading: function(tabPath) {
var
$tab = module.get.tabElement(tabPath),
isLoading = $tab.hasClass(className.loading)
;
if(!isLoading) {
module.verbose('Setting loading state for', $tab);
$tab
.addClass(className.loading)
.siblings($tabs)
.removeClass(className.active + ' ' + className.loading)
;
if($tab.length > 0) {
settings.onRequest.call($tab[0], tabPath);
}
}
},
state: function(state) {
$.address.value(state);
}
},
changeTab: function(tabPath) {
var
pushStateAvailable = (window.history && window.history.pushState),
shouldIgnoreLoad = (pushStateAvailable && settings.ignoreFirstLoad && firstLoad),
remoteContent = (settings.auto || $.isPlainObject(settings.apiSettings) ),
// only add default path if not remote content
pathArray = (remoteContent && !shouldIgnoreLoad)
? module.utilities.pathToArray(tabPath)
: module.get.defaultPathArray(tabPath)
;
tabPath = module.utilities.arrayToPath(pathArray);
$.each(pathArray, function(index, tab) {
var
currentPathArray = pathArray.slice(0, index + 1),
currentPath = module.utilities.arrayToPath(currentPathArray),
isTab = module.is.tab(currentPath),
isLastIndex = (index + 1 == pathArray.length),
$tab = module.get.tabElement(currentPath),
$anchor,
nextPathArray,
nextPath,
isLastTab
;
module.verbose('Looking for tab', tab);
if(isTab) {
module.verbose('Tab was found', tab);
// scope up
activeTabPath = currentPath;
parameterArray = module.utilities.filterArray(pathArray, currentPathArray);
if(isLastIndex) {
isLastTab = true;
}
else {
nextPathArray = pathArray.slice(0, index + 2);
nextPath = module.utilities.arrayToPath(nextPathArray);
isLastTab = ( !module.is.tab(nextPath) );
if(isLastTab) {
module.verbose('Tab parameters found', nextPathArray);
}
}
if(isLastTab && remoteContent) {
if(!shouldIgnoreLoad) {
module.activate.navigation(currentPath);
module.fetch.content(currentPath, tabPath);
}
else {
module.debug('Ignoring remote content on first tab load', currentPath);
firstLoad = false;
module.cache.add(tabPath, $tab.html());
module.activate.all(currentPath);
settings.onFirstLoad.call($tab[0], currentPath, parameterArray, historyEvent);
settings.onLoad.call($tab[0], currentPath, parameterArray, historyEvent);
}
return false;
}
else {
module.debug('Opened local tab', currentPath);
module.activate.all(currentPath);
if( !module.cache.read(currentPath) ) {
module.cache.add(currentPath, true);
module.debug('First time tab loaded calling tab init');
settings.onFirstLoad.call($tab[0], currentPath, parameterArray, historyEvent);
}
settings.onLoad.call($tab[0], currentPath, parameterArray, historyEvent);
}
}
else if(tabPath.search('/') == -1 && tabPath !== '') {
// look for in page anchor
$anchor = $('#' + tabPath + ', a[name="' + tabPath + '"]');
currentPath = $anchor.closest('[data-tab]').data(metadata.tab);
$tab = module.get.tabElement(currentPath);
// if anchor exists use parent tab
if($anchor && $anchor.length > 0 && currentPath) {
module.debug('Anchor link used, opening parent tab', $tab, $anchor);
if( !$tab.hasClass(className.active) ) {
setTimeout(function() {
module.scrollTo($anchor);
}, 0);
}
module.activate.all(currentPath);
if( !module.cache.read(currentPath) ) {
module.cache.add(currentPath, true);
module.debug('First time tab loaded calling tab init');
settings.onFirstLoad.call($tab[0], currentPath, parameterArray, historyEvent);
}
settings.onLoad.call($tab[0], currentPath, parameterArray, historyEvent);
return false;
}
}
else {
module.error(error.missingTab, $module, $context, currentPath);
return false;
}
});
},
scrollTo: function($element) {
var
scrollOffset = ($element && $element.length > 0)
? $element.offset().top
: false
;
if(scrollOffset !== false) {
module.debug('Forcing scroll to an in-page link in a hidden tab', scrollOffset, $element);
$(document).scrollTop(scrollOffset);
}
},
update: {
content: function(tabPath, html, evaluateScripts) {
var
$tab = module.get.tabElement(tabPath),
tab = $tab[0]
;
evaluateScripts = (evaluateScripts !== undefined)
? evaluateScripts
: settings.evaluateScripts
;
if(evaluateScripts) {
module.debug('Updating HTML and evaluating inline scripts', tabPath, html);
$tab.html(html);
}
else {
module.debug('Updating HTML', tabPath, html);
tab.innerHTML = html;
}
}
},
fetch: {
content: function(tabPath, fullTabPath) {
var
$tab = module.get.tabElement(tabPath),
apiSettings = {
dataType : 'html',
encodeParameters : false,
on : 'now',
cache : settings.alwaysRefresh,
headers : {
'X-Remote': true
},
onSuccess : function(response) {
module.cache.add(fullTabPath, response);
module.update.content(tabPath, response);
if(tabPath == activeTabPath) {
module.debug('Content loaded', tabPath);
module.activate.tab(tabPath);
}
else {
module.debug('Content loaded in background', tabPath);
}
settings.onFirstLoad.call($tab[0], tabPath, parameterArray, historyEvent);
settings.onLoad.call($tab[0], tabPath, parameterArray, historyEvent);
},
urlData: {
tab: fullTabPath
}
},
request = $tab.api('get request') || false,
existingRequest = ( request && request.state() === 'pending' ),
requestSettings,
cachedContent
;
fullTabPath = fullTabPath || tabPath;
cachedContent = module.cache.read(fullTabPath);
if(settings.cache && cachedContent) {
module.activate.tab(tabPath);
module.debug('Adding cached content', fullTabPath);
if(settings.evaluateScripts == 'once') {
module.update.content(tabPath, cachedContent, false);
}
else {
module.update.content(tabPath, cachedContent);
}
settings.onLoad.call($tab[0], tabPath, parameterArray, historyEvent);
}
else if(existingRequest) {
module.set.loading(tabPath);
module.debug('Content is already loading', fullTabPath);
}
else if($.api !== undefined) {
requestSettings = $.extend(true, {}, settings.apiSettings, apiSettings);
module.debug('Retrieving remote content', fullTabPath, requestSettings);
module.set.loading(tabPath);
$tab.api(requestSettings);
}
else {
module.error(error.api);
}
}
},
activate: {
all: function(tabPath) {
module.activate.tab(tabPath);
module.activate.navigation(tabPath);
},
tab: function(tabPath) {
var
$tab = module.get.tabElement(tabPath),
isActive = $tab.hasClass(className.active)
;
module.verbose('Showing tab content for', $tab);
if(!isActive) {
$tab
.addClass(className.active)
.siblings($tabs)
.removeClass(className.active + ' ' + className.loading)
;
if($tab.length > 0) {
settings.onVisible.call($tab[0], tabPath);
}
}
},
navigation: function(tabPath) {
var
$navigation = module.get.navElement(tabPath),
isActive = $navigation.hasClass(className.active)
;
module.verbose('Activating tab navigation for', $navigation, tabPath);
if(!isActive) {
$navigation
.addClass(className.active)
.siblings($allModules)
.removeClass(className.active + ' ' + className.loading)
;
}
}
},
deactivate: {
all: function() {
module.deactivate.navigation();
module.deactivate.tabs();
},
navigation: function() {
$allModules
.removeClass(className.active)
;
},
tabs: function() {
$tabs
.removeClass(className.active + ' ' + className.loading)
;
}
},
is: {
tab: function(tabName) {
return (tabName !== undefined)
? ( module.get.tabElement(tabName).length > 0 )
: false
;
}
},
get: {
initialPath: function() {
return $allModules.eq(0).data(metadata.tab) || $tabs.eq(0).data(metadata.tab);
},
path: function() {
return $.address.value();
},
// adds default tabs to tab path
defaultPathArray: function(tabPath) {
return module.utilities.pathToArray( module.get.defaultPath(tabPath) );
},
defaultPath: function(tabPath) {
var
$defaultNav = $allModules.filter('[data-' + metadata.tab + '^="' + tabPath + '/"]').eq(0),
defaultTab = $defaultNav.data(metadata.tab) || false
;
if( defaultTab ) {
module.debug('Found default tab', defaultTab);
if(recursionDepth < settings.maxDepth) {
recursionDepth++;
return module.get.defaultPath(defaultTab);
}
module.error(error.recursion);
}
else {
module.debug('No default tabs found for', tabPath, $tabs);
}
recursionDepth = 0;
return tabPath;
},
navElement: function(tabPath) {
tabPath = tabPath || activeTabPath;
return $allModules.filter('[data-' + metadata.tab + '="' + tabPath + '"]');
},
tabElement: function(tabPath) {
var
$fullPathTab,
$simplePathTab,
tabPathArray,
lastTab
;
tabPath = tabPath || activeTabPath;
tabPathArray = module.utilities.pathToArray(tabPath);
lastTab = module.utilities.last(tabPathArray);
$fullPathTab = $tabs.filter('[data-' + metadata.tab + '="' + tabPath + '"]');
$simplePathTab = $tabs.filter('[data-' + metadata.tab + '="' + lastTab + '"]');
return ($fullPathTab.length > 0)
? $fullPathTab
: $simplePathTab
;
},
tab: function() {
return activeTabPath;
}
},
utilities: {
filterArray: function(keepArray, removeArray) {
return $.grep(keepArray, function(keepValue) {
return ( $.inArray(keepValue, removeArray) == -1);
});
},
last: function(array) {
return $.isArray(array)
? array[ array.length - 1]
: false
;
},
pathToArray: function(pathName) {
if(pathName === undefined) {
pathName = activeTabPath;
}
return typeof pathName == 'string'
? pathName.split('/')
: [pathName]
;
},
arrayToPath: function(pathArray) {
return $.isArray(pathArray)
? pathArray.join('/')
: false
;
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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( (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 = [];
}
},
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 {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
// shortcut for tabbed content with no defined navigation
$.tab = function() {
$(window).tab.apply(this, arguments);
};
$.fn.tab.settings = {
name : 'Tab',
namespace : 'tab',
debug : false,
verbose : false,
performance : true,
auto : false, // uses pjax style endpoints fetching content from same url with remote-content headers
history : false, // use browser history
historyType : 'hash', // #/ or html5 state
path : false, // base path of url
context : false, // specify a context that tabs must appear inside
childrenOnly : false, // use only tabs that are children of context
maxDepth : 25, // max depth a tab can be nested
alwaysRefresh : false, // load tab content new every tab click
cache : true, // cache the content requests to pull locally
ignoreFirstLoad : false, // don't load remote content on first load
apiSettings : false, // settings for api call
evaluateScripts : 'once', // whether inline scripts should be parsed (true/false/once). Once will not re-evaluate on cached content
onFirstLoad : function(tabPath, parameterArray, historyEvent) {}, // called first time loaded
onLoad : function(tabPath, parameterArray, historyEvent) {}, // called on every load
onVisible : function(tabPath, parameterArray, historyEvent) {}, // called every time tab visible
onRequest : function(tabPath, parameterArray, historyEvent) {}, // called ever time a tab beings loading remote content
templates : {
determineTitle: function(tabArray) {} // returns page title for path
},
error: {
api : 'You attempted to load content without API module',
method : 'The method you called is not defined',
missingTab : 'Activated tab cannot be found. Tabs are case-sensitive.',
noContent : 'The tab you specified is missing a content url.',
path : 'History enabled, but no path was specified',
recursion : 'Max recursive depth reached',
legacyInit : 'onTabInit has been renamed to onFirstLoad in 2.0, please adjust your code.',
legacyLoad : 'onTabLoad has been renamed to onLoad in 2.0. Please adjust your code',
state : 'History requires Asual\'s Address library <https://github.com/asual/jquery-address>'
},
metadata : {
tab : 'tab',
loaded : 'loaded',
promise: 'promise'
},
className : {
loading : 'loading',
active : 'active'
},
selector : {
tabs : '.ui.tab',
ui : '.ui'
}
};
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Transition
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.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.restore.conditions();
}
}
},
force: {
visible: function() {
var
style = $module.attr('style'),
userStyle = module.get.userStyle(),
displayType = module.get.displayType(),
overrideStyle = userStyle + 'display: ' + displayType + ' !important;',
currentDisplay = $module.css('display'),
emptyStyle = (style === undefined || style === '')
;
if(currentDisplay !== displayType) {
module.verbose('Overriding default display to show element', displayType);
$module
.attr('style', overrideStyle)
;
}
else if(emptyStyle) {
$module.removeAttr('style');
}
},
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 $.isArray(style.match(/display.*?;/, ''));
}
},
set: {
animating: function(animation) {
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);
// override display if necessary so animation appears visibly
module.force.visible();
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.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
});
}
return $.fn.transition.settings;
},
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() {
if(settings.displayType) {
return settings.displayType;
}
if($module.data(metadata.displayType) === undefined) {
// create fake element to determine display state
module.can.transition(true);
}
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),
elementClass,
tagName,
$clone,
currentAnimation,
inAnimation,
directionExists,
displayType
;
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')
;
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();
module.set.hidden();
module.force.hidden();
settings.onHide.call(element);
settings.onComplete.call(element);
// module.repaint();
},
show: function(display) {
module.verbose('Showing element', display);
module.remove.hidden();
module.set.visible();
module.force.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) {
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.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.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() {
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($.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',
// 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,
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 : 'There is no css animation matching the one you specified. Please make sure your css is vendor prefixed, and you have included transition css.',
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 );
/*!
* # Semantic UI 2.1.4 - API
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.api = $.fn.api = function(parameters) {
var
// use window context if none specified
$allModules = $.isFunction(this)
? $(window)
: $(this),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.api.settings, parameters)
: $.extend({}, $.fn.api.settings),
// internal aliases
namespace = settings.namespace,
metadata = settings.metadata,
selector = settings.selector,
error = settings.error,
className = settings.className,
// define namespaces for modules
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
// element that creates request
$module = $(this),
$form = $module.closest(selector.form),
// context used for state
$context = (settings.stateContext)
? $(settings.stateContext)
: $module,
// request details
ajaxSettings,
requestSettings,
url,
data,
requestStartTime,
// standard module
element = this,
context = $context[0],
instance = $module.data(moduleNamespace),
module
;
module = {
initialize: function() {
if(!methodInvoked) {
module.bind.events();
}
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)
.off(eventNamespace)
;
},
bind: {
events: function() {
var
triggerEvent = module.get.event()
;
if( triggerEvent ) {
module.verbose('Attaching API events to element', triggerEvent);
$module
.on(triggerEvent + eventNamespace, module.event.trigger)
;
}
else if(settings.on == 'now') {
module.debug('Querying API endpoint immediately');
module.query();
}
}
},
decode: {
json: function(response) {
if(response !== undefined && typeof response == 'string') {
try {
response = JSON.parse(response);
}
catch(e) {
// isnt json string
}
}
return response;
}
},
read: {
cachedResponse: function(url) {
var
response
;
if(window.Storage === undefined) {
module.error(error.noStorage);
return;
}
response = sessionStorage.getItem(url);
module.debug('Using cached response', url, response);
response = module.decode.json(response);
return false;
}
},
write: {
cachedResponse: function(url, response) {
if(response && response === '') {
module.debug('Response empty, not caching', response);
return;
}
if(window.Storage === undefined) {
module.error(error.noStorage);
return;
}
if( $.isPlainObject(response) ) {
response = JSON.stringify(response);
}
sessionStorage.setItem(url, response);
module.verbose('Storing cached response for url', url, response);
}
},
query: function() {
if(module.is.disabled()) {
module.debug('Element is disabled API request aborted');
return;
}
if(module.is.loading()) {
if(settings.interruptRequests) {
module.debug('Interrupting previous request');
module.abort();
}
else {
module.debug('Cancelling request, previous request is still pending');
return;
}
}
// pass element metadata to url (value, text)
if(settings.defaultData) {
$.extend(true, settings.urlData, module.get.defaultData());
}
// Add form content
if(settings.serializeForm) {
settings.data = module.add.formData(settings.data);
}
// call beforesend and get any settings changes
requestSettings = module.get.settings();
// check if before send cancelled request
if(requestSettings === false) {
module.cancelled = true;
module.error(error.beforeSend);
return;
}
else {
module.cancelled = false;
}
// get url
url = module.get.templatedURL();
if(!url && !module.is.mocked()) {
module.error(error.missingURL);
return;
}
// replace variables
url = module.add.urlData( url );
// missing url parameters
if( !url && !module.is.mocked()) {
return;
}
// look for jQuery ajax parameters in settings
ajaxSettings = $.extend(true, {}, settings, {
type : settings.method || settings.type,
data : data,
url : settings.base + url,
beforeSend : settings.beforeXHR,
success : function() {},
failure : function() {},
complete : function() {}
});
module.debug('Querying URL', ajaxSettings.url);
module.verbose('Using AJAX settings', ajaxSettings);
if(settings.cache === 'local' && module.read.cachedResponse(url)) {
module.debug('Response returned from local cache');
module.request = module.create.request();
module.request.resolveWith(context, [ module.read.cachedResponse(url) ]);
return;
}
if( !settings.throttle ) {
module.debug('Sending request', data, ajaxSettings.method);
module.send.request();
}
else {
if(!settings.throttleFirstRequest && !module.timer) {
module.debug('Sending request', data, ajaxSettings.method);
module.send.request();
module.timer = setTimeout(function(){}, settings.throttle);
}
else {
module.debug('Throttling request', settings.throttle);
clearTimeout(module.timer);
module.timer = setTimeout(function() {
if(module.timer) {
delete module.timer;
}
module.debug('Sending throttled request', data, ajaxSettings.method);
module.send.request();
}, settings.throttle);
}
}
},
should: {
removeError: function() {
return ( settings.hideError === true || (settings.hideError === 'auto' && !module.is.form()) );
}
},
is: {
disabled: function() {
return ($module.filter(selector.disabled).length > 0);
},
form: function() {
return $module.is('form') || $context.is('form');
},
mocked: function() {
return (settings.mockResponse || settings.mockResponseAsync);
},
input: function() {
return $module.is('input');
},
loading: function() {
return (module.request && module.request.state() == 'pending');
},
abortedRequest: function(xhr) {
if(xhr && xhr.readyState !== undefined && xhr.readyState === 0) {
module.verbose('XHR request determined to be aborted');
return true;
}
else {
module.verbose('XHR request was not aborted');
return false;
}
},
validResponse: function(response) {
if( (settings.dataType !== 'json' && settings.dataType !== 'jsonp') || !$.isFunction(settings.successTest) ) {
module.verbose('Response is not JSON, skipping validation', settings.successTest, response);
return true;
}
module.debug('Checking JSON returned success', settings.successTest, response);
if( settings.successTest(response) ) {
module.debug('Response passed success test', response);
return true;
}
else {
module.debug('Response failed success test', response);
return false;
}
}
},
was: {
cancelled: function() {
return (module.cancelled || false);
},
succesful: function() {
return (module.request && module.request.state() == 'resolved');
},
failure: function() {
return (module.request && module.request.state() == 'rejected');
},
complete: function() {
return (module.request && (module.request.state() == 'resolved' || module.request.state() == 'rejected') );
}
},
add: {
urlData: function(url, urlData) {
var
requiredVariables,
optionalVariables
;
if(url) {
requiredVariables = url.match(settings.regExp.required);
optionalVariables = url.match(settings.regExp.optional);
urlData = urlData || settings.urlData;
if(requiredVariables) {
module.debug('Looking for required URL variables', requiredVariables);
$.each(requiredVariables, function(index, templatedString) {
var
// allow legacy {$var} style
variable = (templatedString.indexOf('$') !== -1)
? templatedString.substr(2, templatedString.length - 3)
: templatedString.substr(1, templatedString.length - 2),
value = ($.isPlainObject(urlData) && urlData[variable] !== undefined)
? urlData[variable]
: ($module.data(variable) !== undefined)
? $module.data(variable)
: ($context.data(variable) !== undefined)
? $context.data(variable)
: urlData[variable]
;
// remove value
if(value === undefined) {
module.error(error.requiredParameter, variable, url);
url = false;
return false;
}
else {
module.verbose('Found required variable', variable, value);
value = (settings.encodeParameters)
? module.get.urlEncodedValue(value)
: value
;
url = url.replace(templatedString, value);
}
});
}
if(optionalVariables) {
module.debug('Looking for optional URL variables', requiredVariables);
$.each(optionalVariables, function(index, templatedString) {
var
// allow legacy {/$var} style
variable = (templatedString.indexOf('$') !== -1)
? templatedString.substr(3, templatedString.length - 4)
: templatedString.substr(2, templatedString.length - 3),
value = ($.isPlainObject(urlData) && urlData[variable] !== undefined)
? urlData[variable]
: ($module.data(variable) !== undefined)
? $module.data(variable)
: ($context.data(variable) !== undefined)
? $context.data(variable)
: urlData[variable]
;
// optional replacement
if(value !== undefined) {
module.verbose('Optional variable Found', variable, value);
url = url.replace(templatedString, value);
}
else {
module.verbose('Optional variable not found', variable);
// remove preceding slash if set
if(url.indexOf('/' + templatedString) !== -1) {
url = url.replace('/' + templatedString, '');
}
else {
url = url.replace(templatedString, '');
}
}
});
}
}
return url;
},
formData: function(data) {
var
canSerialize = ($.fn.serializeObject !== undefined),
formData = (canSerialize)
? $form.serializeObject()
: $form.serialize(),
hasOtherData
;
data = data || settings.data;
hasOtherData = $.isPlainObject(data);
if(hasOtherData) {
if(canSerialize) {
module.debug('Extending existing data with form data', data, formData);
data = $.extend(true, {}, data, formData);
}
else {
module.error(error.missingSerialize);
module.debug('Cant extend data. Replacing data with form data', data, formData);
data = formData;
}
}
else {
module.debug('Adding form data', formData);
data = formData;
}
return data;
}
},
send: {
request: function() {
module.set.loading();
module.request = module.create.request();
if( module.is.mocked() ) {
module.mockedXHR = module.create.mockedXHR();
}
else {
module.xhr = module.create.xhr();
}
settings.onRequest.call(context, module.request, module.xhr);
}
},
event: {
trigger: function(event) {
module.query();
if(event.type == 'submit' || event.type == 'click') {
event.preventDefault();
}
},
xhr: {
always: function() {
// nothing special
},
done: function(response, textStatus, xhr) {
var
context = this,
elapsedTime = (new Date().getTime() - requestStartTime),
timeLeft = (settings.loadingDuration - elapsedTime),
translatedResponse = ( $.isFunction(settings.onResponse) )
? settings.onResponse.call(context, $.extend(true, {}, response))
: false
;
timeLeft = (timeLeft > 0)
? timeLeft
: 0
;
if(translatedResponse) {
module.debug('Modified API response in onResponse callback', settings.onResponse, translatedResponse, response);
response = translatedResponse;
}
if(timeLeft > 0) {
module.debug('Response completed early delaying state change by', timeLeft);
}
setTimeout(function() {
if( module.is.validResponse(response) ) {
module.request.resolveWith(context, [response, xhr]);
}
else {
module.request.rejectWith(context, [xhr, 'invalid']);
}
}, timeLeft);
},
fail: function(xhr, status, httpMessage) {
var
context = this,
elapsedTime = (new Date().getTime() - requestStartTime),
timeLeft = (settings.loadingDuration - elapsedTime)
;
timeLeft = (timeLeft > 0)
? timeLeft
: 0
;
if(timeLeft > 0) {
module.debug('Response completed early delaying state change by', timeLeft);
}
setTimeout(function() {
if( module.is.abortedRequest(xhr) ) {
module.request.rejectWith(context, [xhr, 'aborted', httpMessage]);
}
else {
module.request.rejectWith(context, [xhr, 'error', status, httpMessage]);
}
}, timeLeft);
}
},
request: {
done: function(response, xhr) {
module.debug('Successful API Response', response);
if(settings.cache === 'local' && url) {
module.write.cachedResponse(url, response);
module.debug('Saving server response locally', module.cache);
}
settings.onSuccess.call(context, response, $module, xhr);
},
complete: function(firstParameter, secondParameter) {
var
xhr,
response
;
// have to guess callback parameters based on request success
if( module.was.succesful() ) {
response = firstParameter;
xhr = secondParameter;
}
else {
xhr = firstParameter;
response = module.get.responseFromXHR(xhr);
}
module.remove.loading();
settings.onComplete.call(context, response, $module, xhr);
},
fail: function(xhr, status, httpMessage) {
var
// pull response from xhr if available
response = module.get.responseFromXHR(xhr),
errorMessage = module.get.errorFromRequest(response, status, httpMessage)
;
if(status == 'aborted') {
module.debug('XHR Aborted (Most likely caused by page navigation or CORS Policy)', status, httpMessage);
settings.onAbort.call(context, status, $module, xhr);
}
else if(status == 'invalid') {
module.debug('JSON did not pass success test. A server-side error has most likely occurred', response);
}
else if(status == 'error') {
if(xhr !== undefined) {
module.debug('XHR produced a server error', status, httpMessage);
// make sure we have an error to display to console
if( xhr.status != 200 && httpMessage !== undefined && httpMessage !== '') {
module.error(error.statusMessage + httpMessage, ajaxSettings.url);
}
settings.onError.call(context, errorMessage, $module, xhr);
}
}
if(settings.errorDuration && status !== 'aborted') {
module.debug('Adding error state');
module.set.error();
if( module.should.removeError() ) {
setTimeout(module.remove.error, settings.errorDuration);
}
}
module.debug('API Request failed', errorMessage, xhr);
settings.onFailure.call(context, response, $module, xhr);
}
}
},
create: {
request: function() {
// api request promise
return $.Deferred()
.always(module.event.request.complete)
.done(module.event.request.done)
.fail(module.event.request.fail)
;
},
mockedXHR: function () {
var
// xhr does not simulate these properties of xhr but must return them
textStatus = false,
status = false,
httpMessage = false,
asyncCallback,
response,
mockedXHR
;
mockedXHR = $.Deferred()
.always(module.event.xhr.complete)
.done(module.event.xhr.done)
.fail(module.event.xhr.fail)
;
if(settings.mockResponse) {
if( $.isFunction(settings.mockResponse) ) {
module.debug('Using mocked callback returning response', settings.mockResponse);
response = settings.mockResponse.call(context, settings);
}
else {
module.debug('Using specified response', settings.mockResponse);
response = settings.mockResponse;
}
// simulating response
mockedXHR.resolveWith(context, [ response, textStatus, { responseText: response }]);
}
else if( $.isFunction(settings.mockResponseAsync) ) {
asyncCallback = function(response) {
module.debug('Async callback returned response', response);
if(response) {
mockedXHR.resolveWith(context, [ response, textStatus, { responseText: response }]);
}
else {
mockedXHR.rejectWith(context, [{ responseText: response }, status, httpMessage]);
}
};
module.debug('Using async mocked response', settings.mockResponseAsync);
settings.mockResponseAsync.call(context, settings, asyncCallback);
}
return mockedXHR;
},
xhr: function() {
var
xhr
;
// ajax request promise
xhr = $.ajax(ajaxSettings)
.always(module.event.xhr.always)
.done(module.event.xhr.done)
.fail(module.event.xhr.fail)
;
module.verbose('Created server request', xhr);
return xhr;
}
},
set: {
error: function() {
module.verbose('Adding error state to element', $context);
$context.addClass(className.error);
},
loading: function() {
module.verbose('Adding loading state to element', $context);
$context.addClass(className.loading);
requestStartTime = new Date().getTime();
}
},
remove: {
error: function() {
module.verbose('Removing error state from element', $context);
$context.removeClass(className.error);
},
loading: function() {
module.verbose('Removing loading state from element', $context);
$context.removeClass(className.loading);
}
},
get: {
responseFromXHR: function(xhr) {
return $.isPlainObject(xhr)
? (settings.dataType == 'json' || settings.dataType == 'jsonp')
? module.decode.json(xhr.responseText)
: xhr.responseText
: false
;
},
errorFromRequest: function(response, status, httpMessage) {
return ($.isPlainObject(response) && response.error !== undefined)
? response.error // use json error message
: (settings.error[status] !== undefined) // use server error message
? settings.error[status]
: httpMessage
;
},
request: function() {
return module.request || false;
},
xhr: function() {
return module.xhr || false;
},
settings: function() {
var
runSettings
;
runSettings = settings.beforeSend.call(context, settings);
if(runSettings) {
if(runSettings.success !== undefined) {
module.debug('Legacy success callback detected', runSettings);
module.error(error.legacyParameters, runSettings.success);
runSettings.onSuccess = runSettings.success;
}
if(runSettings.failure !== undefined) {
module.debug('Legacy failure callback detected', runSettings);
module.error(error.legacyParameters, runSettings.failure);
runSettings.onFailure = runSettings.failure;
}
if(runSettings.complete !== undefined) {
module.debug('Legacy complete callback detected', runSettings);
module.error(error.legacyParameters, runSettings.complete);
runSettings.onComplete = runSettings.complete;
}
}
if(runSettings === undefined) {
module.error(error.noReturnedValue);
}
return (runSettings !== undefined)
? runSettings
: settings
;
},
urlEncodedValue: function(value) {
var
decodedValue = window.decodeURIComponent(value),
encodedValue = window.encodeURIComponent(value),
alreadyEncoded = (decodedValue !== value)
;
if(alreadyEncoded) {
module.debug('URL value is already encoded, avoiding double encoding', value);
return value;
}
module.verbose('Encoding value using encodeURIComponent', value, encodedValue);
return encodedValue;
},
defaultData: function() {
var
data = {}
;
if( !$.isWindow(element) ) {
if( module.is.input() ) {
data.value = $module.val();
}
else if( !module.is.form() ) {
}
else {
data.text = $module.text();
}
}
return data;
},
event: function() {
if( $.isWindow(element) || settings.on == 'now' ) {
module.debug('API called without element, no events attached');
return false;
}
else if(settings.on == 'auto') {
if( $module.is('input') ) {
return (element.oninput !== undefined)
? 'input'
: (element.onpropertychange !== undefined)
? 'propertychange'
: 'keyup'
;
}
else if( $module.is('form') ) {
return 'submit';
}
else {
return 'click';
}
}
else {
return settings.on;
}
},
templatedURL: function(action) {
action = action || $module.data(metadata.action) || settings.action || false;
url = $module.data(metadata.url) || settings.url || false;
if(url) {
module.debug('Using specified url', url);
return url;
}
if(action) {
module.debug('Looking up url for action', action, settings.api);
if(settings.api[action] === undefined && !module.is.mocked()) {
module.error(error.missingAction, settings.action, settings.api);
return;
}
url = settings.api[action];
}
else if( module.is.form() ) {
url = $module.attr('action') || $context.attr('action') || false;
module.debug('No url or action specified, defaulting to form action', url);
}
return url;
}
},
abort: function() {
var
xhr = module.get.xhr()
;
if( xhr && xhr.state() !== 'resolved') {
module.debug('Cancelling API request');
xhr.abort();
}
},
// reset state
reset: function() {
module.remove.error();
module.remove.loading();
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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( (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 = [];
}
},
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 {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.api.settings = {
name : 'API',
namespace : 'api',
debug : false,
verbose : false,
performance : true,
// object containing all templates endpoints
api : {},
// whether to cache responses
cache : true,
// whether new requests should abort previous requests
interruptRequests : true,
// event binding
on : 'auto',
// context for applying state classes
stateContext : false,
// duration for loading state
loadingDuration : 0,
// whether to hide errors after a period of time
hideError : 'auto',
// duration for error state
errorDuration : 2000,
// whether parameters should be encoded with encodeURIComponent
encodeParameters : true,
// API action to use
action : false,
// templated URL to use
url : false,
// base URL to apply to all endpoints
base : '',
// data that will
urlData : {},
// whether to add default data to url data
defaultData : true,
// whether to serialize closest form
serializeForm : false,
// how long to wait before request should occur
throttle : 0,
// whether to throttle first request or only repeated
throttleFirstRequest : true,
// standard ajax settings
method : 'get',
data : {},
dataType : 'json',
// mock response
mockResponse : false,
mockResponseAsync : false,
// callbacks before request
beforeSend : function(settings) { return settings; },
beforeXHR : function(xhr) {},
onRequest : function(promise, xhr) {},
// after request
onResponse : false, // function(response) { },
// response was successful, if JSON passed validation
onSuccess : function(response, $module) {},
// request finished without aborting
onComplete : function(response, $module) {},
// failed JSON success test
onFailure : function(response, $module) {},
// server error
onError : function(errorMessage, $module) {},
// request aborted
onAbort : function(errorMessage, $module) {},
successTest : false,
// errors
error : {
beforeSend : 'The before send function has aborted the request',
error : 'There was an error with your request',
exitConditions : 'API Request Aborted. Exit conditions met',
JSONParse : 'JSON could not be parsed during error handling',
legacyParameters : 'You are using legacy API success callback names',
method : 'The method you called is not defined',
missingAction : 'API action used but no url was defined',
missingSerialize : 'jquery-serialize-object is required to add form data to an existing data object',
missingURL : 'No URL specified for api event',
noReturnedValue : 'The beforeSend callback must return a settings object, beforeSend ignored.',
noStorage : 'Caching responses locally requires session storage',
parseError : 'There was an error parsing your request',
requiredParameter : 'Missing a required URL parameter: ',
statusMessage : 'Server gave an error: ',
timeout : 'Your request timed out'
},
regExp : {
required : /\{\$*[A-z0-9]+\}/g,
optional : /\{\/\$*[A-z0-9]+\}/g,
},
className: {
loading : 'loading',
error : 'error'
},
selector: {
disabled : '.disabled',
form : 'form'
},
metadata: {
action : 'action',
url : 'url'
}
};
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - State
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.fn.state = function(parameters) {
var
$allModules = $(this),
moduleSelector = $allModules.selector || '',
hasTouch = ('ontouchstart' in document.documentElement),
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.state.settings, parameters)
: $.extend({}, $.fn.state.settings),
error = settings.error,
metadata = settings.metadata,
className = settings.className,
namespace = settings.namespace,
states = settings.states,
text = settings.text,
eventNamespace = '.' + namespace,
moduleNamespace = namespace + '-module',
$module = $(this),
element = this,
instance = $module.data(moduleNamespace),
module
;
module = {
initialize: function() {
module.verbose('Initializing module');
// allow module to guess desired state based on element
if(settings.automatic) {
module.add.defaults();
}
// bind events with delegated events
if(settings.context && moduleSelector !== '') {
$(settings.context)
.on(moduleSelector, 'mouseenter' + eventNamespace, module.change.text)
.on(moduleSelector, 'mouseleave' + eventNamespace, module.reset.text)
.on(moduleSelector, 'click' + eventNamespace, module.toggle.state)
;
}
else {
$module
.on('mouseenter' + eventNamespace, module.change.text)
.on('mouseleave' + eventNamespace, module.reset.text)
.on('click' + eventNamespace, module.toggle.state)
;
}
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of module', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
destroy: function() {
module.verbose('Destroying previous module', instance);
$module
.off(eventNamespace)
.removeData(moduleNamespace)
;
},
refresh: function() {
module.verbose('Refreshing selector cache');
$module = $(element);
},
add: {
defaults: function() {
var
userStates = parameters && $.isPlainObject(parameters.states)
? parameters.states
: {}
;
$.each(settings.defaults, function(type, typeStates) {
if( module.is[type] !== undefined && module.is[type]() ) {
module.verbose('Adding default states', type, element);
$.extend(settings.states, typeStates, userStates);
}
});
}
},
is: {
active: function() {
return $module.hasClass(className.active);
},
loading: function() {
return $module.hasClass(className.loading);
},
inactive: function() {
return !( $module.hasClass(className.active) );
},
state: function(state) {
if(className[state] === undefined) {
return false;
}
return $module.hasClass( className[state] );
},
enabled: function() {
return !( $module.is(settings.filter.active) );
},
disabled: function() {
return ( $module.is(settings.filter.active) );
},
textEnabled: function() {
return !( $module.is(settings.filter.text) );
},
// definitions for automatic type detection
button: function() {
return $module.is('.button:not(a, .submit)');
},
input: function() {
return $module.is('input');
},
progress: function() {
return $module.is('.ui.progress');
}
},
allow: function(state) {
module.debug('Now allowing state', state);
states[state] = true;
},
disallow: function(state) {
module.debug('No longer allowing', state);
states[state] = false;
},
allows: function(state) {
return states[state] || false;
},
enable: function() {
$module.removeClass(className.disabled);
},
disable: function() {
$module.addClass(className.disabled);
},
setState: function(state) {
if(module.allows(state)) {
$module.addClass( className[state] );
}
},
removeState: function(state) {
if(module.allows(state)) {
$module.removeClass( className[state] );
}
},
toggle: {
state: function() {
var
apiRequest,
requestCancelled
;
if( module.allows('active') && module.is.enabled() ) {
module.refresh();
if($.fn.api !== undefined) {
apiRequest = $module.api('get request');
requestCancelled = $module.api('was cancelled');
if( requestCancelled ) {
module.debug('API Request cancelled by beforesend');
settings.activateTest = function(){ return false; };
settings.deactivateTest = function(){ return false; };
}
else if(apiRequest) {
module.listenTo(apiRequest);
return;
}
}
module.change.state();
}
}
},
listenTo: function(apiRequest) {
module.debug('API request detected, waiting for state signal', apiRequest);
if(apiRequest) {
if(text.loading) {
module.update.text(text.loading);
}
$.when(apiRequest)
.then(function() {
if(apiRequest.state() == 'resolved') {
module.debug('API request succeeded');
settings.activateTest = function(){ return true; };
settings.deactivateTest = function(){ return true; };
}
else {
module.debug('API request failed');
settings.activateTest = function(){ return false; };
settings.deactivateTest = function(){ return false; };
}
module.change.state();
})
;
}
},
// checks whether active/inactive state can be given
change: {
state: function() {
module.debug('Determining state change direction');
// inactive to active change
if( module.is.inactive() ) {
module.activate();
}
else {
module.deactivate();
}
if(settings.sync) {
module.sync();
}
settings.onChange.call(element);
},
text: function() {
if( module.is.textEnabled() ) {
if(module.is.disabled() ) {
module.verbose('Changing text to disabled text', text.hover);
module.update.text(text.disabled);
}
else if( module.is.active() ) {
if(text.hover) {
module.verbose('Changing text to hover text', text.hover);
module.update.text(text.hover);
}
else if(text.deactivate) {
module.verbose('Changing text to deactivating text', text.deactivate);
module.update.text(text.deactivate);
}
}
else {
if(text.hover) {
module.verbose('Changing text to hover text', text.hover);
module.update.text(text.hover);
}
else if(text.activate){
module.verbose('Changing text to activating text', text.activate);
module.update.text(text.activate);
}
}
}
}
},
activate: function() {
if( settings.activateTest.call(element) ) {
module.debug('Setting state to active');
$module
.addClass(className.active)
;
module.update.text(text.active);
settings.onActivate.call(element);
}
},
deactivate: function() {
if( settings.deactivateTest.call(element) ) {
module.debug('Setting state to inactive');
$module
.removeClass(className.active)
;
module.update.text(text.inactive);
settings.onDeactivate.call(element);
}
},
sync: function() {
module.verbose('Syncing other buttons to current state');
if( module.is.active() ) {
$allModules
.not($module)
.state('activate');
}
else {
$allModules
.not($module)
.state('deactivate')
;
}
},
get: {
text: function() {
return (settings.selector.text)
? $module.find(settings.selector.text).text()
: $module.html()
;
},
textFor: function(state) {
return text[state] || false;
}
},
flash: {
text: function(text, duration, callback) {
var
previousText = module.get.text()
;
module.debug('Flashing text message', text, duration);
text = text || settings.text.flash;
duration = duration || settings.flashDuration;
callback = callback || function() {};
module.update.text(text);
setTimeout(function(){
module.update.text(previousText);
callback.call(element);
}, duration);
}
},
reset: {
// on mouseout sets text to previous value
text: function() {
var
activeText = text.active || $module.data(metadata.storedText),
inactiveText = text.inactive || $module.data(metadata.storedText)
;
if( module.is.textEnabled() ) {
if( module.is.active() && activeText) {
module.verbose('Resetting active text', activeText);
module.update.text(activeText);
}
else if(inactiveText) {
module.verbose('Resetting inactive text', activeText);
module.update.text(inactiveText);
}
}
}
},
update: {
text: function(text) {
var
currentText = module.get.text()
;
if(text && text !== currentText) {
module.debug('Updating text', text);
if(settings.selector.text) {
$module
.data(metadata.storedText, text)
.find(settings.selector.text)
.text(text)
;
}
else {
$module
.data(metadata.storedText, text)
.html(text)
;
}
}
else {
module.debug('Text is already set, ignoring update', text);
}
}
},
setting: function(name, value) {
module.debug('Changing setting', name, value);
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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( (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 = [];
}
},
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 {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.state.settings = {
// module info
name : 'State',
// debug output
debug : false,
// verbose debug output
verbose : false,
// namespace for events
namespace : 'state',
// debug data includes performance
performance : true,
// callback occurs on state change
onActivate : function() {},
onDeactivate : function() {},
onChange : function() {},
// state test functions
activateTest : function() { return true; },
deactivateTest : function() { return true; },
// whether to automatically map default states
automatic : true,
// activate / deactivate changes all elements instantiated at same time
sync : false,
// default flash text duration, used for temporarily changing text of an element
flashDuration : 1000,
// selector filter
filter : {
text : '.loading, .disabled',
active : '.disabled'
},
context : false,
// error
error: {
beforeSend : 'The before send function has cancelled state change',
method : 'The method you called is not defined.'
},
// metadata
metadata: {
promise : 'promise',
storedText : 'stored-text'
},
// change class on state
className: {
active : 'active',
disabled : 'disabled',
error : 'error',
loading : 'loading',
success : 'success',
warning : 'warning'
},
selector: {
// selector for text node
text: false
},
defaults : {
input: {
disabled : true,
loading : true,
active : true
},
button: {
disabled : true,
loading : true,
active : true,
},
progress: {
active : true,
success : true,
warning : true,
error : true
}
},
states : {
active : true,
disabled : true,
error : true,
loading : true,
success : true,
warning : true
},
text : {
disabled : false,
flash : false,
hover : false,
active : false,
inactive : false,
activate : false,
deactivate : false
}
};
})( jQuery, window , document );
/*!
* # Semantic UI 2.1.4 - Visibility
* http://github.com/semantic-org/semantic-ui/
*
*
* Copyright 2015 Contributors
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ( $, window, document, undefined ) {
"use strict";
$.fn.visibility = function(parameters) {
var
$allModules = $(this),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$allModules
.each(function() {
var
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.visibility.settings, parameters)
: $.extend({}, $.fn.visibility.settings),
className = settings.className,
namespace = settings.namespace,
error = settings.error,
metadata = settings.metadata,
eventNamespace = '.' + namespace,
moduleNamespace = 'module-' + namespace,
$window = $(window),
$module = $(this),
$context = $(settings.context),
$placeholder,
selector = $module.selector || '',
instance = $module.data(moduleNamespace),
requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { setTimeout(callback, 0); },
element = this,
disabled = false,
observer,
module
;
module = {
initialize: function() {
module.debug('Initializing', settings);
module.setup.cache();
if( module.should.trackChanges() ) {
if(settings.type == 'image') {
module.setup.image();
}
if(settings.type == 'fixed') {
module.setup.fixed();
}
if(settings.observeChanges) {
module.observeChanges();
}
module.bind.events();
}
module.save.position();
if( !module.is.visible() ) {
module.error(error.visible, $module);
}
if(settings.initialCheck) {
module.checkVisibility();
}
module.instantiate();
},
instantiate: function() {
module.debug('Storing instance', module);
$module
.data(moduleNamespace, module)
;
instance = module;
},
destroy: function() {
module.verbose('Destroying previous module');
if(observer) {
observer.disconnect();
}
$window
.off('load' + eventNamespace, module.event.load)
.off('resize' + eventNamespace, module.event.resize)
;
$context
.off('scrollchange' + eventNamespace, module.event.scrollchange)
;
$module
.off(eventNamespace)
.removeData(moduleNamespace)
;
},
observeChanges: function() {
if('MutationObserver' in window) {
observer = new MutationObserver(function(mutations) {
module.verbose('DOM tree modified, updating visibility calculations');
module.timer = setTimeout(function() {
module.verbose('DOM tree modified, updating sticky menu');
module.refresh();
}, 100);
});
observer.observe(element, {
childList : true,
subtree : true
});
module.debug('Setting up mutation observer', observer);
}
},
bind: {
events: function() {
module.verbose('Binding visibility events to scroll and resize');
if(settings.refreshOnLoad) {
$window
.on('load' + eventNamespace, module.event.load)
;
}
$window
.on('resize' + eventNamespace, module.event.resize)
;
// pub/sub pattern
$context
.off('scroll' + eventNamespace)
.on('scroll' + eventNamespace, module.event.scroll)
.on('scrollchange' + eventNamespace, module.event.scrollchange)
;
}
},
event: {
resize: function() {
module.debug('Window resized');
if(settings.refreshOnResize) {
requestAnimationFrame(module.refresh);
}
},
load: function() {
module.debug('Page finished loading');
requestAnimationFrame(module.refresh);
},
// publishes scrollchange event on one scroll
scroll: function() {
if(settings.throttle) {
clearTimeout(module.timer);
module.timer = setTimeout(function() {
$context.triggerHandler('scrollchange' + eventNamespace, [ $context.scrollTop() ]);
}, settings.throttle);
}
else {
requestAnimationFrame(function() {
$context.triggerHandler('scrollchange' + eventNamespace, [ $context.scrollTop() ]);
});
}
},
// subscribes to scrollchange
scrollchange: function(event, scrollPosition) {
module.checkVisibility(scrollPosition);
},
},
precache: function(images, callback) {
if (!(images instanceof Array)) {
images = [images];
}
var
imagesLength = images.length,
loadedCounter = 0,
cache = [],
cacheImage = document.createElement('img'),
handleLoad = function() {
loadedCounter++;
if (loadedCounter >= images.length) {
if ($.isFunction(callback)) {
callback();
}
}
}
;
while (imagesLength--) {
cacheImage = document.createElement('img');
cacheImage.onload = handleLoad;
cacheImage.onerror = handleLoad;
cacheImage.src = images[imagesLength];
cache.push(cacheImage);
}
},
enableCallbacks: function() {
module.debug('Allowing callbacks to occur');
disabled = false;
},
disableCallbacks: function() {
module.debug('Disabling all callbacks temporarily');
disabled = true;
},
should: {
trackChanges: function() {
if(methodInvoked) {
module.debug('One time query, no need to bind events');
return false;
}
module.debug('Callbacks being attached');
return true;
}
},
setup: {
cache: function() {
module.cache = {
occurred : {},
screen : {},
element : {},
};
},
image: function() {
var
src = $module.data(metadata.src)
;
if(src) {
module.verbose('Lazy loading image', src);
settings.once = true;
settings.observeChanges = false;
// show when top visible
settings.onOnScreen = function() {
module.debug('Image on screen', element);
module.precache(src, function() {
module.set.image(src);
});
};
}
},
fixed: function() {
module.debug('Setting up fixed');
settings.once = false;
settings.observeChanges = false;
settings.initialCheck = true;
settings.refreshOnLoad = true;
if(!parameters.transition) {
settings.transition = false;
}
module.create.placeholder();
module.debug('Added placeholder', $placeholder);
settings.onTopPassed = function() {
module.debug('Element passed, adding fixed position', $module);
module.show.placeholder();
module.set.fixed();
if(settings.transition) {
if($.fn.transition !== undefined) {
$module.transition(settings.transition, settings.duration);
}
}
};
settings.onTopPassedReverse = function() {
module.debug('Element returned to position, removing fixed', $module);
module.hide.placeholder();
module.remove.fixed();
};
}
},
create: {
placeholder: function() {
module.verbose('Creating fixed position placeholder');
$placeholder = $module
.clone(false)
.css('display', 'none')
.addClass(className.placeholder)
.insertAfter($module)
;
}
},
show: {
placeholder: function() {
module.verbose('Showing placeholder');
$placeholder
.css('display', 'block')
.css('visibility', 'hidden')
;
}
},
hide: {
placeholder: function() {
module.verbose('Hiding placeholder');
$placeholder
.css('display', 'none')
.css('visibility', '')
;
}
},
set: {
fixed: function() {
module.verbose('Setting element to fixed position');
$module
.addClass(className.fixed)
.css({
position : 'fixed',
top : settings.offset + 'px',
left : 'auto',
zIndex : '1'
})
;
},
image: function(src) {
$module
.attr('src', src)
;
if(settings.transition) {
if( $.fn.transition !== undefined ) {
$module.transition(settings.transition, settings.duration);
}
else {
$module.fadeIn(settings.duration);
}
}
else {
$module.show();
}
}
},
is: {
onScreen: function() {
var
calculations = module.get.elementCalculations()
;
return calculations.onScreen;
},
offScreen: function() {
var
calculations = module.get.elementCalculations()
;
return calculations.offScreen;
},
visible: function() {
if(module.cache && module.cache.element) {
return !(module.cache.element.width === 0 && module.cache.element.offset.top === 0);
}
return false;
}
},
refresh: function() {
module.debug('Refreshing constants (width/height)');
if(settings.type == 'fixed') {
module.remove.fixed();
module.remove.occurred();
}
module.reset();
module.save.position();
if(settings.checkOnRefresh) {
module.checkVisibility();
}
settings.onRefresh.call(element);
},
reset: function() {
module.verbose('Reseting all cached values');
if( $.isPlainObject(module.cache) ) {
module.cache.screen = {};
module.cache.element = {};
}
},
checkVisibility: function(scroll) {
module.verbose('Checking visibility of element', module.cache.element);
if( !disabled && module.is.visible() ) {
// save scroll position
module.save.scroll(scroll);
// update calculations derived from scroll
module.save.calculations();
// percentage
module.passed();
// reverse (must be first)
module.passingReverse();
module.topVisibleReverse();
module.bottomVisibleReverse();
module.topPassedReverse();
module.bottomPassedReverse();
// one time
module.onScreen();
module.offScreen();
module.passing();
module.topVisible();
module.bottomVisible();
module.topPassed();
module.bottomPassed();
// on update callback
if(settings.onUpdate) {
settings.onUpdate.call(element, module.get.elementCalculations());
}
}
},
passed: function(amount, newCallback) {
var
calculations = module.get.elementCalculations(),
amountInPixels
;
// assign callback
if(amount && newCallback) {
settings.onPassed[amount] = newCallback;
}
else if(amount !== undefined) {
return (module.get.pixelsPassed(amount) > calculations.pixelsPassed);
}
else if(calculations.passing) {
$.each(settings.onPassed, function(amount, callback) {
if(calculations.bottomVisible || calculations.pixelsPassed > module.get.pixelsPassed(amount)) {
module.execute(callback, amount);
}
else if(!settings.once) {
module.remove.occurred(callback);
}
});
}
},
onScreen: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onOnScreen,
callbackName = 'onScreen'
;
if(newCallback) {
module.debug('Adding callback for onScreen', newCallback);
settings.onOnScreen = newCallback;
}
if(calculations.onScreen) {
module.execute(callback, callbackName);
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback !== undefined) {
return calculations.onOnScreen;
}
},
offScreen: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onOffScreen,
callbackName = 'offScreen'
;
if(newCallback) {
module.debug('Adding callback for offScreen', newCallback);
settings.onOffScreen = newCallback;
}
if(calculations.offScreen) {
module.execute(callback, callbackName);
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback !== undefined) {
return calculations.onOffScreen;
}
},
passing: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onPassing,
callbackName = 'passing'
;
if(newCallback) {
module.debug('Adding callback for passing', newCallback);
settings.onPassing = newCallback;
}
if(calculations.passing) {
module.execute(callback, callbackName);
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback !== undefined) {
return calculations.passing;
}
},
topVisible: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onTopVisible,
callbackName = 'topVisible'
;
if(newCallback) {
module.debug('Adding callback for top visible', newCallback);
settings.onTopVisible = newCallback;
}
if(calculations.topVisible) {
module.execute(callback, callbackName);
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback === undefined) {
return calculations.topVisible;
}
},
bottomVisible: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onBottomVisible,
callbackName = 'bottomVisible'
;
if(newCallback) {
module.debug('Adding callback for bottom visible', newCallback);
settings.onBottomVisible = newCallback;
}
if(calculations.bottomVisible) {
module.execute(callback, callbackName);
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback === undefined) {
return calculations.bottomVisible;
}
},
topPassed: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onTopPassed,
callbackName = 'topPassed'
;
if(newCallback) {
module.debug('Adding callback for top passed', newCallback);
settings.onTopPassed = newCallback;
}
if(calculations.topPassed) {
module.execute(callback, callbackName);
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback === undefined) {
return calculations.topPassed;
}
},
bottomPassed: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onBottomPassed,
callbackName = 'bottomPassed'
;
if(newCallback) {
module.debug('Adding callback for bottom passed', newCallback);
settings.onBottomPassed = newCallback;
}
if(calculations.bottomPassed) {
module.execute(callback, callbackName);
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback === undefined) {
return calculations.bottomPassed;
}
},
passingReverse: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onPassingReverse,
callbackName = 'passingReverse'
;
if(newCallback) {
module.debug('Adding callback for passing reverse', newCallback);
settings.onPassingReverse = newCallback;
}
if(!calculations.passing) {
if(module.get.occurred('passing')) {
module.execute(callback, callbackName);
}
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback !== undefined) {
return !calculations.passing;
}
},
topVisibleReverse: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onTopVisibleReverse,
callbackName = 'topVisibleReverse'
;
if(newCallback) {
module.debug('Adding callback for top visible reverse', newCallback);
settings.onTopVisibleReverse = newCallback;
}
if(!calculations.topVisible) {
if(module.get.occurred('topVisible')) {
module.execute(callback, callbackName);
}
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback === undefined) {
return !calculations.topVisible;
}
},
bottomVisibleReverse: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onBottomVisibleReverse,
callbackName = 'bottomVisibleReverse'
;
if(newCallback) {
module.debug('Adding callback for bottom visible reverse', newCallback);
settings.onBottomVisibleReverse = newCallback;
}
if(!calculations.bottomVisible) {
if(module.get.occurred('bottomVisible')) {
module.execute(callback, callbackName);
}
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback === undefined) {
return !calculations.bottomVisible;
}
},
topPassedReverse: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onTopPassedReverse,
callbackName = 'topPassedReverse'
;
if(newCallback) {
module.debug('Adding callback for top passed reverse', newCallback);
settings.onTopPassedReverse = newCallback;
}
if(!calculations.topPassed) {
if(module.get.occurred('topPassed')) {
module.execute(callback, callbackName);
}
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback === undefined) {
return !calculations.onTopPassed;
}
},
bottomPassedReverse: function(newCallback) {
var
calculations = module.get.elementCalculations(),
callback = newCallback || settings.onBottomPassedReverse,
callbackName = 'bottomPassedReverse'
;
if(newCallback) {
module.debug('Adding callback for bottom passed reverse', newCallback);
settings.onBottomPassedReverse = newCallback;
}
if(!calculations.bottomPassed) {
if(module.get.occurred('bottomPassed')) {
module.execute(callback, callbackName);
}
}
else if(!settings.once) {
module.remove.occurred(callbackName);
}
if(newCallback === undefined) {
return !calculations.bottomPassed;
}
},
execute: function(callback, callbackName) {
var
calculations = module.get.elementCalculations(),
screen = module.get.screenCalculations()
;
callback = callback || false;
if(callback) {
if(settings.continuous) {
module.debug('Callback being called continuously', callbackName, calculations);
callback.call(element, calculations, screen);
}
else if(!module.get.occurred(callbackName)) {
module.debug('Conditions met', callbackName, calculations);
callback.call(element, calculations, screen);
}
}
module.save.occurred(callbackName);
},
remove: {
fixed: function() {
module.debug('Removing fixed position');
$module
.removeClass(className.fixed)
.css({
position : '',
top : '',
left : '',
zIndex : ''
})
;
},
occurred: function(callback) {
if(callback) {
var
occurred = module.cache.occurred
;
if(occurred[callback] !== undefined && occurred[callback] === true) {
module.debug('Callback can now be called again', callback);
module.cache.occurred[callback] = false;
}
}
else {
module.cache.occurred = {};
}
}
},
save: {
calculations: function() {
module.verbose('Saving all calculations necessary to determine positioning');
module.save.direction();
module.save.screenCalculations();
module.save.elementCalculations();
},
occurred: function(callback) {
if(callback) {
if(module.cache.occurred[callback] === undefined || (module.cache.occurred[callback] !== true)) {
module.verbose('Saving callback occurred', callback);
module.cache.occurred[callback] = true;
}
}
},
scroll: function(scrollPosition) {
scrollPosition = scrollPosition + settings.offset || $context.scrollTop() + settings.offset;
module.cache.scroll = scrollPosition;
},
direction: function() {
var
scroll = module.get.scroll(),
lastScroll = module.get.lastScroll(),
direction
;
if(scroll > lastScroll && lastScroll) {
direction = 'down';
}
else if(scroll < lastScroll && lastScroll) {
direction = 'up';
}
else {
direction = 'static';
}
module.cache.direction = direction;
return module.cache.direction;
},
elementPosition: function() {
var
element = module.cache.element,
screen = module.get.screenSize()
;
module.verbose('Saving element position');
// (quicker than $.extend)
element.fits = (element.height < screen.height);
element.offset = $module.offset();
element.width = $module.outerWidth();
element.height = $module.outerHeight();
// store
module.cache.element = element;
return element;
},
elementCalculations: function() {
var
screen = module.get.screenCalculations(),
element = module.get.elementPosition()
;
// offset
if(settings.includeMargin) {
element.margin = {};
element.margin.top = parseInt($module.css('margin-top'), 10);
element.margin.bottom = parseInt($module.css('margin-bottom'), 10);
element.top = element.offset.top - element.margin.top;
element.bottom = element.offset.top + element.height + element.margin.bottom;
}
else {
element.top = element.offset.top;
element.bottom = element.offset.top + element.height;
}
// visibility
element.topVisible = (screen.bottom >= element.top);
element.topPassed = (screen.top >= element.top);
element.bottomVisible = (screen.bottom >= element.bottom);
element.bottomPassed = (screen.top >= element.bottom);
element.pixelsPassed = 0;
element.percentagePassed = 0;
// meta calculations
element.onScreen = (element.topVisible && !element.bottomPassed);
element.passing = (element.topPassed && !element.bottomPassed);
element.offScreen = (!element.onScreen);
// passing calculations
if(element.passing) {
element.pixelsPassed = (screen.top - element.top);
element.percentagePassed = (screen.top - element.top) / element.height;
}
module.cache.element = element;
module.verbose('Updated element calculations', element);
return element;
},
screenCalculations: function() {
var
scroll = module.get.scroll()
;
module.save.direction();
module.cache.screen.top = scroll;
module.cache.screen.bottom = scroll + module.cache.screen.height;
return module.cache.screen;
},
screenSize: function() {
module.verbose('Saving window position');
module.cache.screen = {
height: $context.height()
};
},
position: function() {
module.save.screenSize();
module.save.elementPosition();
}
},
get: {
pixelsPassed: function(amount) {
var
element = module.get.elementCalculations()
;
if(amount.search('%') > -1) {
return ( element.height * (parseInt(amount, 10) / 100) );
}
return parseInt(amount, 10);
},
occurred: function(callback) {
return (module.cache.occurred !== undefined)
? module.cache.occurred[callback] || false
: false
;
},
direction: function() {
if(module.cache.direction === undefined) {
module.save.direction();
}
return module.cache.direction;
},
elementPosition: function() {
if(module.cache.element === undefined) {
module.save.elementPosition();
}
return module.cache.element;
},
elementCalculations: function() {
if(module.cache.element === undefined) {
module.save.elementCalculations();
}
return module.cache.element;
},
screenCalculations: function() {
if(module.cache.screen === undefined) {
module.save.screenCalculations();
}
return module.cache.screen;
},
screenSize: function() {
if(module.cache.screen === undefined) {
module.save.screenSize();
}
return module.cache.screen;
},
scroll: function() {
if(module.cache.scroll === undefined) {
module.save.scroll();
}
return module.cache.scroll;
},
lastScroll: function() {
if(module.cache.screen === undefined) {
module.debug('First scroll event, no last scroll could be found');
return false;
}
return module.cache.screen.top;
}
},
setting: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
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.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.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() {
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( (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 = [];
}
},
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 {
module.error(error.method, query);
return false;
}
});
}
if ( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
instance.save.scroll();
instance.save.calculations();
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.visibility.settings = {
name : 'Visibility',
namespace : 'visibility',
debug : false,
verbose : false,
performance : true,
// whether to use mutation observers to follow changes
observeChanges : true,
// check position immediately on init
initialCheck : true,
// whether to refresh calculations after all page images load
refreshOnLoad : true,
// whether to refresh calculations after page resize event
refreshOnResize : true,
// should call callbacks on refresh event (resize, etc)
checkOnRefresh : true,
// callback should only occur one time
once : true,
// callback should fire continuously whe evaluates to true
continuous : false,
// offset to use with scroll top
offset : 0,
// whether to include margin in elements position
includeMargin : false,
// scroll context for visibility checks
context : window,
// visibility check delay in ms (defaults to animationFrame)
throttle : false,
// special visibility type (image, fixed)
type : false,
// image only animation settings
transition : 'fade in',
duration : 1000,
// array of callbacks for percentage
onPassed : {},
// standard callbacks
onOnScreen : false,
onOffScreen : false,
onPassing : false,
onTopVisible : false,
onBottomVisible : false,
onTopPassed : false,
onBottomPassed : false,
// reverse callbacks
onPassingReverse : false,
onTopVisibleReverse : false,
onBottomVisibleReverse : false,
onTopPassedReverse : false,
onBottomPassedReverse : false,
// utility callbacks
onUpdate : false, // disabled by default for performance
onRefresh : function(){},
metadata : {
src: 'src'
},
className: {
fixed : 'fixed',
placeholder : 'placeholder'
},
error : {
method : 'The method you called is not defined.',
visible : 'Element is hidden, you must call refresh after element becomes visible'
}
};
})( jQuery, window , document ); | david3080/BicycleRoutingApp | www/lib/semantic-ui/dist/semantic.js | JavaScript | mit | 689,731 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.